kikocis/GraphRAG-SDK public
Changesets · Branches · Tags · Compare
| Changeset | c4d9d856add1b1fba9ef7d5cc7a1b6724b837a85c0ffed7de8ae8aef8af28666 |
|---|---|
| Author | Roi Lipman <roilipman@gmail.com> · 2024-05-27 09:17 +03:00 |
| Committer | Roi Lipman <roilipman@gmail.com> · 2024-05-27 14:01 +03:00 |
| Parents | None: the first changeset |
24 files changed
added README.md +0 −0
added data/madoff.txt +249 −0
| @@ -0,0 +1,249 @@ | ||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | +Episode guide | |
| 5 | +4 | |
| 6 | +Cast & crew | |
| 7 | +User reviews | |
| 8 | +FAQ | |
| 9 | +IMDbPro | |
| 10 | + | |
| 11 | +Madoff: The Monster of Wall Street | |
| 12 | +TV Mini Series | |
| 13 | +2023 | |
| 14 | +15 | |
| 15 | +1h 2m | |
| 16 | +IMDb RATING | |
| 17 | +YOUR RATING | |
| 18 | +Madoff: The Monster of Wall Street (2023) | |
| 19 | + | |
| 20 | +It follows the rise and fall of the American financier and ponzi schemer: Madoff. | |
| 21 | +Play trailer with sound1:50 | |
| 22 | +It follows the rise and fall of the American financier and ponzi schemer: Madoff. | |
| 23 | + | |
| 24 | +Stars | |
| 25 | +Joseph ScottoMelony FelicianoDonna Pastorello | |
| 26 | +See production info at IMDbPro | |
| 27 | +31 | |
| 28 | +User reviews | |
| 29 | +16 | |
| 30 | +Critic reviews | |
| 31 | +Episodes | |
| 32 | +4 | |
| 33 | +TOP-RATED | |
| 34 | +Wed, Jan 4, 2023 | |
| 35 | +S1.E4 | |
| 36 | +The Price of Trust | |
| 37 | +Madoff's scheme is exposed amid the 2008 financial market crisis. His victims' lives are upended as they trace years of obstacles to recoup their losses. | |
| 38 | +7.7 | |
| 39 | +/10 | |
| 40 | +TOP-RATED | |
| 41 | +Wed, Jan 4, 2023 | |
| 42 | +S1.E3 | |
| 43 | +See No Evil | |
| 44 | +Competitors investigate Madoff's impossible numbers and alert the Securities and Exchange Commission, but the agency shrugs off multiple red flags. | |
| 45 | +7.5 | |
| 46 | +/10 | |
| 47 | +BROWSE EPISODES | |
| 48 | +Videos | |
| 49 | +2 | |
| 50 | +Official Trailer | |
| 51 | +Trailer 1:50 | |
| 52 | +Watch Official Trailer | |
| 53 | +Madoff: The Monster Of Wall Street | |
| 54 | +Trailer 1:42 | |
| 55 | +Watch Madoff: The Monster Of Wall Street | |
| 56 | +Photos | |
| 57 | +12 | |
| 58 | +Madoff: The Monster of Wall Street (2023) | |
| 59 | +Ginger OToole and Joseph Scotto in Netflix docuseries Madoff: The Monster of Wall Street | |
| 60 | +Netflix docuseries Madoff: The Monster of Wall Street - Young Bernie Madoff | |
| 61 | +Netflix docuseries Madoff: The Monster of Wall Street - Young Bernie Madoff | |
| 62 | +Donna Pastorello and Eleanor Squillari in Madoff: The Monster of Wall Street (2023) | |
| 63 | +Donna Pastorello in Madoff: The Monster of Wall Street (2023) | |
| 64 | +Joseph Scotto, Donna Pastorello, Sarah Kuklis, Isa Camyar, Alex Olson, Kevin Delano, Cris Colicchio, and Ashley Rose Folino in Madoff: The Monster of Wall Street (2023) | |
| 65 | +Joseph Scotto and Cris Colicchio in Madoff: The Monster of Wall Street (2023) | |
| 66 | +Madoff: The Monster of Wall Street (2023) | |
| 67 | +Madoff: The Monster of Wall Street (2023) | |
| 68 | +Madoff: The Monster of Wall Street (2023) | |
| 69 | +Top cast | |
| 70 | +Joseph Scotto | |
| 71 | +Joseph Scotto | |
| 72 | +Bernie Madoff | |
| 73 | +Melony Feliciano | |
| 74 | +Melony Feliciano | |
| 75 | +Background Extra | |
| 76 | +Donna Pastorello | |
| 77 | +Donna Pastorello | |
| 78 | +Eleanor Squillari | |
| 79 | +Isa Camyar | |
| 80 | +Isa Camyar | |
| 81 | +Frank DiPascali | |
| 82 | +Sarah Kuklis | |
| 83 | +Sarah Kuklis | |
| 84 | +Ellen Hales | |
| 85 | +Alex Olson | |
| 86 | +Alex Olson | |
| 87 | +Mark Madoff | |
| 88 | +Elijah George | |
| 89 | +Elijah George | |
| 90 | +19th Floor Trader | |
| 91 | +Howie Schaal | |
| 92 | +Howie Schaal | |
| 93 | +Jerry O'Hara | |
| 94 | +Stephanie Beauchamp | |
| 95 | +Jodi Crupi | |
| 96 | +Cris Colicchio | |
| 97 | +Cris Colicchio | |
| 98 | +Peter Madoff | |
| 99 | +Alex Hammerli | |
| 100 | +Madoff Employee | |
| 101 | +Alicia Erlinger | |
| 102 | +Annette Bongiorno | |
| 103 | +Diana B. Henriques | |
| 104 | +Self - Author - The Wizard of Lies… | |
| 105 | +Kevin Delano | |
| 106 | +Andrew Madoff | |
| 107 | +Robert Loftus | |
| 108 | +19th Floor Trader | |
| 109 | +Paul Faggione | |
| 110 | +Paul Faggione | |
| 111 | +Jeffrey Tucker | |
| 112 | +Marla Freeman | |
| 113 | +Marla Freeman | |
| 114 | +Sonja Kohn | |
| 115 | +Rafael Antonio Vasquez | |
| 116 | +Rafael Antonio Vasquez | |
| 117 | +George Perez | |
| 118 | +All cast & crew | |
| 119 | +Production, box office & more at IMDbPro | |
| 120 | +More like this | |
| 121 | +Murdaugh Murders: A Southern Scandal | |
| 122 | +6.8 | |
| 123 | +Murdaugh Murders: A Southern Scandal | |
| 124 | + | |
| 125 | +Waco: American Apocalypse | |
| 126 | +7.0 | |
| 127 | +Waco: American Apocalypse | |
| 128 | + | |
| 129 | +Pepsi, Where's My Jet? | |
| 130 | +7.0 | |
| 131 | +Pepsi, Where's My Jet? | |
| 132 | + | |
| 133 | +The Hatchet Wielding Hitchhiker | |
| 134 | +6.2 | |
| 135 | +The Hatchet Wielding Hitchhiker | |
| 136 | + | |
| 137 | +American Manhunt: The Boston Marathon Bombing | |
| 138 | +7.5 | |
| 139 | +American Manhunt: The Boston Marathon Bombing | |
| 140 | + | |
| 141 | +MH370: The Plane That Disappeared | |
| 142 | +6.1 | |
| 143 | +MH370: The Plane That Disappeared | |
| 144 | + | |
| 145 | +Eat the Rich: The GameStop Saga | |
| 146 | +6.3 | |
| 147 | +Eat the Rich: The GameStop Saga | |
| 148 | + | |
| 149 | +Madoff | |
| 150 | +7.4 | |
| 151 | +Madoff | |
| 152 | + | |
| 153 | +FIFA Uncovered | |
| 154 | +7.4 | |
| 155 | +FIFA Uncovered | |
| 156 | + | |
| 157 | +Killer Sally | |
| 158 | +6.7 | |
| 159 | +Killer Sally | |
| 160 | + | |
| 161 | +Jeffrey Epstein: Filthy Rich | |
| 162 | +7.1 | |
| 163 | +Jeffrey Epstein: Filthy Rich | |
| 164 | + | |
| 165 | +Pamela: A Love Story | |
| 166 | +7.2 | |
| 167 | +Pamela: A Love Story | |
| 168 | + | |
| 169 | +Storyline | |
| 170 | +Did you know | |
| 171 | +Connections | |
| 172 | +Featured in Jeremy Vine: Episode #6.5 (2023) | |
| 173 | +User reviews | |
| 174 | +31 | |
| 175 | +FEATURED REVIEW | |
| 176 | +6 | |
| 177 | +/10 | |
| 178 | +Good to know but way too slow. | |
| 179 | +A very interesting documentary on a topic that I think is good to know for most people. But, in typical Netflix fashion, is dragged out over way too many episodes and cost you way too much of your time. | |
| 180 | + | |
| 181 | +The lack of original footage has been made up by some acting, but all scenes seem endlessly repeated. Good they interviewed a lot of involved people and they got a hand on some original content though. But it feels like it could fit in a 1 hour documentary movie. So yes this is a great topic, but I'd rather advice to read a news article on it than to spend your hours of precious time on Netflix. | |
| 182 | + | |
| 183 | +helpful | |
| 184 | +• | |
| 185 | +16 | |
| 186 | + | |
| 187 | +3 | |
| 188 | + | |
| 189 | +owen89Jan 10, 2023 | |
| 190 | +Top picks | |
| 191 | +Sign in to rate and Watchlist for personalized recommendations | |
| 192 | +FAQ | |
| 193 | +14 | |
| 194 | +How many seasons does Madoff: The Monster of Wall Street have? | |
| 195 | +Powered by Alexa | |
| 196 | +Details | |
| 197 | +Release date | |
| 198 | +January 4, 2023 (United Kingdom) | |
| 199 | +Country of origin | |
| 200 | +United States | |
| 201 | +Official site | |
| 202 | +Netflix Site | |
| 203 | +Language | |
| 204 | +English | |
| 205 | +Also known as | |
| 206 | +МЕЙДОФФ: Монстр із Волл-стріт | |
| 207 | +Production companies | |
| 208 | +RadicalMediaThird Eye Motion Picture Company | |
| 209 | +See more company credits at IMDbPro | |
| 210 | +Technical specs | |
| 211 | +Runtime | |
| 212 | +1 hour 2 minutes | |
| 213 | +Color | |
| 214 | +Color | |
| 215 | +Sound mix | |
| 216 | +Dolby Digital | |
| 217 | +Aspect ratio | |
| 218 | +16:9 HD | |
| 219 | +Related news | |
| 220 | +Contribute to this page | |
| 221 | +Suggest an edit or add missing content | |
| 222 | +IMDb Answers: Help fill gaps in our data | |
| 223 | +Learn more about contributing | |
| 224 | +More to explore | |
| 225 | +Production art | |
| 226 | +Photos | |
| 227 | +Hollywood Power Couples | |
| 228 | +See the gallery | |
| 229 | +Production art | |
| 230 | +Photos | |
| 231 | +The Greatest Character Actors of All Time | |
| 232 | +See the gallery | |
| 233 | +Poster | |
| 234 | +List | |
| 235 | +5 Movies to Watch While Gearing Up for 'Furiosa' | |
| 236 | +See our picks | |
| 237 | +Recently viewed | |
| 238 | +Madoff: The Monster of Wall Street (2023) | |
| 239 | +Madoff: The Monster of Wall Street | |
| 240 | +WeWork (2021) | |
| 241 | +WeWork | |
| 242 | +Follow IMDb on social | |
| 243 | +Get the IMDb app | |
| 244 | +For Android and iOS | |
| 245 | +Get the IMDb app | |
| 246 | +HelpSite IndexIMDbProBox Office MojoLicense IMDb Data | |
| 247 | +Press RoomAdvertisingJobsConditions of UsePrivacy Policy | |
| 248 | +Your Ads Privacy Choices | |
| 249 | +© 1990-2024 by IMDb.com, Inc. |
added pyproject.toml +17 −0
| @@ -0,0 +1,17 @@ | ||
| 1 | +[tool.poetry] | |
| 2 | +name = "rag-sdk" | |
| 3 | +version = "0.1.0" | |
| 4 | +description = "" | |
| 5 | +authors = ["Roi Lipman <roi.lipman@falkordb.com>"] | |
| 6 | +readme = "README.md" | |
| 7 | + | |
| 8 | +[tool.poetry.dependencies] | |
| 9 | +python = "^3.12" | |
| 10 | +falkordb = "^1.0.4" | |
| 11 | +openai = "^1.30.3" | |
| 12 | +pytest = "^8.2.1" | |
| 13 | + | |
| 14 | + | |
| 15 | +[build-system] | |
| 16 | +requires = ["poetry-core"] | |
| 17 | +build-backend = "poetry.core.masonry.api" |
added rag_sdk/Schema/__init__.py +1 −0
| @@ -0,0 +1,1 @@ | ||
| 1 | +from .schema import Schema |
added rag_sdk/Schema/auto_detect.py +456 −0
| @@ -0,0 +1,456 @@ | ||
| 1 | +import os | |
| 2 | +import json | |
| 3 | +import time | |
| 4 | +import queue | |
| 5 | +import sqlite3 | |
| 6 | +import concurrent.futures | |
| 7 | + | |
| 8 | +from rag_sdk.prompts import * | |
| 9 | +from openai import OpenAI | |
| 10 | +from sqlalchemy.orm import sessionmaker | |
| 11 | +from sqlalchemy import create_engine, inspect, MetaData, Table, types | |
| 12 | + | |
| 13 | +# Convert from SQLAlchemy type to Python type | |
| 14 | +def sqlalchemy_to_python_type(sqlalchemy_type): | |
| 15 | + if isinstance(sqlalchemy_type, types.Integer): | |
| 16 | + return int | |
| 17 | + elif isinstance(sqlalchemy_type, types.Numeric): | |
| 18 | + return float | |
| 19 | + elif isinstance(sqlalchemy_type, types.Float): | |
| 20 | + return float | |
| 21 | + elif isinstance(sqlalchemy_type, types.String): | |
| 22 | + return str | |
| 23 | + elif isinstance(sqlalchemy_type, types.Text): | |
| 24 | + return str | |
| 25 | + elif isinstance(sqlalchemy_type, types.Boolean): | |
| 26 | + return bool | |
| 27 | + elif isinstance(sqlalchemy_type, types.Date): | |
| 28 | + #return 'date' | |
| 29 | + return str | |
| 30 | + elif isinstance(sqlalchemy_type, types.DateTime): | |
| 31 | + #return 'datetime' | |
| 32 | + return str | |
| 33 | + elif isinstance(sqlalchemy_type, types.Time): | |
| 34 | + #return 'time' | |
| 35 | + return str | |
| 36 | + elif isinstance(sqlalchemy_type, types.LargeBinary): | |
| 37 | + #return bytes | |
| 38 | + return str | |
| 39 | + elif isinstance(sqlalchemy_type, types.JSON): | |
| 40 | + #return dict | |
| 41 | + return str | |
| 42 | + else: | |
| 43 | + return 'Unknown Type' | |
| 44 | + | |
| 45 | +# create entity node | |
| 46 | +def create_entity(s, client, model, name:str, columns) -> None: | |
| 47 | + e = s.add_entity(name) | |
| 48 | + | |
| 49 | + has_pk = False | |
| 50 | + for col in columns: | |
| 51 | + t = sqlalchemy_to_python_type(col['type']) | |
| 52 | + pk = bool(col['primary_key']) | |
| 53 | + name = col['name'] | |
| 54 | + | |
| 55 | + if pk: | |
| 56 | + has_pk = True | |
| 57 | + | |
| 58 | + e.add_attribute(name, t, unique=pk, mandatory=pk) | |
| 59 | + | |
| 60 | + # Require each entity to have at least one unique attribute | |
| 61 | + if has_pk is False: | |
| 62 | + user_msg = f"""Which of the following attributes is most suitble to identify | |
| 63 | + a graph node of type: {name} ? | |
| 64 | + List of attributes: {','.join([col['name'] for col in columns])} | |
| 65 | + """ | |
| 66 | + | |
| 67 | + response = client.chat.completions.create( | |
| 68 | + model=model, | |
| 69 | + messages=[ | |
| 70 | + {"role": "system", "content": FIND_UNIQUE_ATTRIBUTE_PROMPT}, | |
| 71 | + {"role": "user", "content": user_msg} | |
| 72 | + ] | |
| 73 | + ) | |
| 74 | + | |
| 75 | + attr = response.choices[0].message.content | |
| 76 | + attr = e.get_attribute(attr) | |
| 77 | + attr.unique = True | |
| 78 | + attr.mandatory = True | |
| 79 | + | |
| 80 | +# Create entity node in addition to a single relation | |
| 81 | +def create_entity_with_relation(s, client, model, name:str, columns, foreign_keys) -> None: | |
| 82 | + # Remove foreign_keys from columns | |
| 83 | + for foreign_key in foreign_keys: | |
| 84 | + for constrained_column in foreign_key['constrained_columns']: | |
| 85 | + for idx, col in enumerate(columns): | |
| 86 | + if col['name'] == constrained_column: | |
| 87 | + del columns[idx] | |
| 88 | + break | |
| 89 | + | |
| 90 | + # create entity | |
| 91 | + create_entity(s, client, model, name, columns) | |
| 92 | + | |
| 93 | + # Determine relation destination node type | |
| 94 | + dest = foreign_keys[0]['referred_table'] | |
| 95 | + | |
| 96 | + src = s.get_entity(name) | |
| 97 | + dest = s.get_entity(dest) | |
| 98 | + | |
| 99 | + # Get relationship name | |
| 100 | + user_msg = f"""Suggest a name for a relationship-type connecting | |
| 101 | + source node of type {src.name} to destination node of type {dest.name}""" | |
| 102 | + | |
| 103 | + response = client.chat.completions.create( | |
| 104 | + model=model, | |
| 105 | + messages=[ | |
| 106 | + {"role": "system", "content": RELATIONSHIP_NAMING_PROMPT}, | |
| 107 | + {"role": "user", "content": user_msg} | |
| 108 | + ] | |
| 109 | + ) | |
| 110 | + | |
| 111 | + relatoin_name = response.choices[0].message.content.upper() | |
| 112 | + | |
| 113 | + # Create relation | |
| 114 | + s.add_relation(relatoin_name, src, dest) | |
| 115 | + | |
| 116 | +# Create relation between two entities | |
| 117 | +def create_relation(s, name:str, foreign_keys): | |
| 118 | + src = foreign_keys[0]['referred_table'] | |
| 119 | + dest = foreign_keys[1]['referred_table'] | |
| 120 | + | |
| 121 | + # Get source and destination entities | |
| 122 | + # (src)-[]->(dest) | |
| 123 | + src = s.get_entity(src) | |
| 124 | + dest = s.get_entity(dest) | |
| 125 | + | |
| 126 | + # Create relation | |
| 127 | + s.add_relation(name.upper(), src, dest) | |
| 128 | + | |
| 129 | +# Convert SQL table into a node type or a relation | |
| 130 | +def convert_table(s, client, model, tbl, columns, foreign_keys): | |
| 131 | + # Depending on the number of foreign keys in table | |
| 132 | + # 0 -> Entity | |
| 133 | + # 1 -> Entity & Relation | |
| 134 | + # 2 -> Relation | |
| 135 | + l = len(foreign_keys) | |
| 136 | + | |
| 137 | + if l == 0: | |
| 138 | + create_entity(s, client, model, tbl, columns) | |
| 139 | + elif l == 1: | |
| 140 | + pass | |
| 141 | + create_entity_with_relation(s, client, model, tbl, columns, foreign_keys) | |
| 142 | + elif l == 2: | |
| 143 | + pass | |
| 144 | + create_relation(s, tbl, foreign_keys) | |
| 145 | + else: | |
| 146 | + print("can't process table with more then 2 forigen keys") | |
| 147 | + | |
| 148 | +def convert_tables(s, client, model, inspector, table_names): | |
| 149 | + # Start by converting tabels without foreign keys | |
| 150 | + for table_name in table_names: | |
| 151 | + columns = inspector.get_columns(table_name) | |
| 152 | + foreign_keys = inspector.get_foreign_keys(table_name) | |
| 153 | + if len(foreign_keys) == 0: | |
| 154 | + convert_table(s, client, model, table_name, columns, foreign_keys) | |
| 155 | + | |
| 156 | + # Continue on processing the rest of the tables | |
| 157 | + for table_name in table_names: | |
| 158 | + columns = inspector.get_columns(table_name) | |
| 159 | + foreign_keys = inspector.get_foreign_keys(table_name) | |
| 160 | + if len(foreign_keys) > 0: | |
| 161 | + convert_table(s, client, model, table_name, columns, foreign_keys) | |
| 162 | + | |
| 163 | +# Create graph ontology from a set of SQL tables | |
| 164 | +def generate_graph_schema(s, client, model): | |
| 165 | + # Connect to local SQLite DB | |
| 166 | + database_file = 'ontology.db' | |
| 167 | + connection_string = f'sqlite:///{database_file}' | |
| 168 | + | |
| 169 | + # Create an engine | |
| 170 | + engine = create_engine(connection_string) | |
| 171 | + | |
| 172 | + # Verify the connection by connecting to the database | |
| 173 | + connection = engine.connect() | |
| 174 | + | |
| 175 | + # Create a configured "Session" class | |
| 176 | + Session = sessionmaker(bind=engine) | |
| 177 | + | |
| 178 | + # Create a Session | |
| 179 | + session = Session() | |
| 180 | + | |
| 181 | + inspector = inspect(engine) | |
| 182 | + table_names = inspector.get_table_names() | |
| 183 | + | |
| 184 | + # Process tabels into schema | |
| 185 | + convert_tables(s, client, model, inspector, table_names) | |
| 186 | + | |
| 187 | + # Close the session when done | |
| 188 | + session.close() | |
| 189 | + | |
| 190 | + # Close the connection | |
| 191 | + connection.close() | |
| 192 | + | |
| 193 | + # Improve relations nameing | |
| 194 | + #for rel in s.relations: | |
| 195 | + # r = s.relations[rel] | |
| 196 | + # user_msg = f"""Suggest a name for a relationship-type connecting | |
| 197 | + # source node of type {r.src.name} to destination node of type {r.dest.name}""" | |
| 198 | + | |
| 199 | + # response = client.chat.completions.create( | |
| 200 | + # model=model, | |
| 201 | + # messages=[ | |
| 202 | + # {"role": "system", "content": RELATIONSHIP_NAMING_PROMPT}, | |
| 203 | + # {"role": "user", "content": user_msg} | |
| 204 | + # ] | |
| 205 | + # ) | |
| 206 | + | |
| 207 | + # old = r.name | |
| 208 | + # r.name = response.choices[0].message.content.upper() | |
| 209 | + # print(f"Renamed from {old} to: {r.name}") | |
| 210 | + | |
| 211 | +# OpenAI assistant tool | |
| 212 | +# queue sql statment | |
| 213 | +def run_sql(arg, queue): | |
| 214 | + sql = arg["sql"] | |
| 215 | + print(f"SQL: {sql}") | |
| 216 | + | |
| 217 | + queue.put(sql) | |
| 218 | + | |
| 219 | +# OpenAI available functions | |
| 220 | +available_functions = { | |
| 221 | + "run_sql": run_sql | |
| 222 | +} | |
| 223 | + | |
| 224 | +# Get OpenAI ontology detection assistant | |
| 225 | +def get_assistant(client, assistant_name, model): | |
| 226 | + # Try reusing existing assistant | |
| 227 | + if os.path.exists("./ONTOLOGY_ASSISTANT_ID"): | |
| 228 | + with open("./ONTOLOGY_ASSISTANT_ID", 'r') as f: | |
| 229 | + ASSISTANT_ID = f.read() | |
| 230 | + try: | |
| 231 | + return client.beta.assistants.retrieve(ASSISTANT_ID) | |
| 232 | + except: | |
| 233 | + pass | |
| 234 | + | |
| 235 | + # Create OpenAI assistant | |
| 236 | + assistant = client.beta.assistants.create( | |
| 237 | + name = assistant_name, | |
| 238 | + instructions = ONTOLOGY_DETECTION_SYSTEM_PROMPT, | |
| 239 | + model = model, | |
| 240 | + tools=[{ | |
| 241 | + "type": "function", | |
| 242 | + "function": { | |
| 243 | + "name": "run_sql", | |
| 244 | + "description": "Run SQL statement", | |
| 245 | + "parameters": { | |
| 246 | + "type": "object", | |
| 247 | + "properties": { | |
| 248 | + "sql": {"type": "string", "description": "SQL statement"} | |
| 249 | + }, | |
| 250 | + "required": ["sql"] | |
| 251 | + } | |
| 252 | + } | |
| 253 | + }] | |
| 254 | + ) | |
| 255 | + | |
| 256 | + # Save assistant ID to local file | |
| 257 | + with open("./ONTOLOGY_ASSISTANT_ID", 'w') as f: | |
| 258 | + f.write(assistant.id) | |
| 259 | + | |
| 260 | + return assistant | |
| 261 | + | |
| 262 | +# Start an interaction with OpenAI assistant | |
| 263 | +def initiate_interaction(client, assistant, user_message): | |
| 264 | + run = client.beta.threads.create_and_run( | |
| 265 | + assistant_id=assistant.id, | |
| 266 | + thread={ "messages": [ {"role": "user", "content": user_message} ] } | |
| 267 | + ) | |
| 268 | + | |
| 269 | + return run | |
| 270 | + | |
| 271 | +# OpenAI run handler | |
| 272 | +def handle_run(client, run, queue): | |
| 273 | + while True: | |
| 274 | + run = client.beta.threads.runs.retrieve(thread_id=run.thread_id, run_id=run.id) | |
| 275 | + | |
| 276 | + if run.status == "completed": | |
| 277 | + print("Done processing document") | |
| 278 | + return | |
| 279 | + | |
| 280 | + if run.status == "expired": | |
| 281 | + print(f"Processing expired") | |
| 282 | + return | |
| 283 | + | |
| 284 | + if run.status == "cancelling" or run.status == "cancelled" or run.status == "failed": | |
| 285 | + print(f"Processing failed") | |
| 286 | + return | |
| 287 | + | |
| 288 | + # wait for run to complete | |
| 289 | + if run.status == "queued": | |
| 290 | + time.sleep(1) | |
| 291 | + continue | |
| 292 | + | |
| 293 | + if run.status == "in_progress": | |
| 294 | + last_step_id = None | |
| 295 | + run_steps = [] | |
| 296 | + run_steps = client.beta.threads.runs.steps.list(thread_id=run.thread_id, run_id=run.id) | |
| 297 | + | |
| 298 | + for step in run_steps.data: | |
| 299 | + if step.status == "in_progress": | |
| 300 | + step_details = step.step_details | |
| 301 | + if step_details.type == "tool_calls": | |
| 302 | + for tool_call in step_details.tool_calls: | |
| 303 | + try: | |
| 304 | + if tool_call.type == "function": | |
| 305 | + func = tool_call.function | |
| 306 | + func_name = func.name | |
| 307 | + args = func.arguments | |
| 308 | + args = json.loads(args) | |
| 309 | + f = available_functions[func_name] | |
| 310 | + f(args, queue) | |
| 311 | + except: | |
| 312 | + print(f"tool_call: {tool_call}") | |
| 313 | + pass | |
| 314 | + | |
| 315 | + last_step_id = run_steps.last_id | |
| 316 | + | |
| 317 | + time.sleep(1) | |
| 318 | + continue | |
| 319 | + | |
| 320 | + if run.status == "requires_action": | |
| 321 | + action = run.required_action | |
| 322 | + if action.type == "submit_tool_outputs": | |
| 323 | + tool_outputs = action.submit_tool_outputs | |
| 324 | + outputs = [] | |
| 325 | + for tool in tool_outputs.tool_calls: | |
| 326 | + tool_call_id = tool.id | |
| 327 | + tool_type = tool.type | |
| 328 | + func = tool.function | |
| 329 | + func_name = func.name | |
| 330 | + args = func.arguments | |
| 331 | + args = json.loads(args) | |
| 332 | + | |
| 333 | + f = available_functions[func_name] | |
| 334 | + f(args, queue) | |
| 335 | + | |
| 336 | + outputs.append({ "tool_call_id": tool_call_id, "output": "OK" }) | |
| 337 | + | |
| 338 | + # respond to action | |
| 339 | + run = client.beta.threads.runs.submit_tool_outputs( | |
| 340 | + thread_id=run.thread_id, | |
| 341 | + run_id=run.id, | |
| 342 | + tool_outputs=outputs | |
| 343 | + ) | |
| 344 | + | |
| 345 | + continue | |
| 346 | + | |
| 347 | +# process source | |
| 348 | +# present content to LLM for graph ontology detection | |
| 349 | +def process_source(client, assistant, src, queue): | |
| 350 | + text = src.load()[:32000] | |
| 351 | + user_message = "Extract schema from following text:" + text | |
| 352 | + | |
| 353 | + run = initiate_interaction(client, assistant, user_message) | |
| 354 | + | |
| 355 | + handle_run(client, run, queue) | |
| 356 | + | |
| 357 | + client.beta.threads.delete(run.thread_id) | |
| 358 | + | |
| 359 | +# Detect graph ontology from a set of sources | |
| 360 | +def schema_auto_detect(schema, sources, model="gpt-3.5-turbo-0125"): | |
| 361 | + client = OpenAI() | |
| 362 | + | |
| 363 | + # Get assistant | |
| 364 | + assistant = get_assistant(client, "ontology detection", model) | |
| 365 | + | |
| 366 | + # Create a new local SQLite DB | |
| 367 | + db_file = "ontology.db" | |
| 368 | + if os.path.exists(db_file): | |
| 369 | + os.remove(db_file) | |
| 370 | + | |
| 371 | + # Process sources | |
| 372 | + q = queue.Queue() | |
| 373 | + with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor: | |
| 374 | + tasks = [] | |
| 375 | + # extract entities and relationships from each page | |
| 376 | + for src in sources: | |
| 377 | + task = executor.submit(process_source, client, assistant, src, q) | |
| 378 | + | |
| 379 | + # Wait for all tasks to complete | |
| 380 | + concurrent.futures.wait(tasks) | |
| 381 | + | |
| 382 | + # Collect duplicated CREATE statments | |
| 383 | + n = q.qsize() | |
| 384 | + tables = {} | |
| 385 | + for i in range(n): | |
| 386 | + stmt = q.get() | |
| 387 | + print(f"sql: {stmt}") | |
| 388 | + | |
| 389 | + # group by table name | |
| 390 | + # CREATE TABLE MoviePersonnel ( | |
| 391 | + s = stmt.index("CREATE TABLE ") + len("CREATE TABLE ") | |
| 392 | + e = stmt.index("(") - 1 | |
| 393 | + tbl = stmt[s:e] | |
| 394 | + print(f"tbl: {tbl}") | |
| 395 | + | |
| 396 | + if tbl not in tables: | |
| 397 | + tables[tbl] = [] | |
| 398 | + tables[tbl].append(stmt) | |
| 399 | + | |
| 400 | + # Merge duplicated create table statments | |
| 401 | + for k in tables: | |
| 402 | + while len(tables[k]) > 1: | |
| 403 | + user_msg = f"""Merge to following two SQL CREATE TABLE statments: | |
| 404 | + 1. {tables[k].pop()} | |
| 405 | + 2. {tables[k].pop()} | |
| 406 | + """ | |
| 407 | + | |
| 408 | + response = client.chat.completions.create( | |
| 409 | + model=model, | |
| 410 | + messages=[ | |
| 411 | + {"role": "system", "content": SQL_FOLDING_PROMPT}, | |
| 412 | + {"role": "user", "content": user_msg} | |
| 413 | + ] | |
| 414 | + ) | |
| 415 | + | |
| 416 | + merged_stmt = response.choices[0].message.content | |
| 417 | + print(f"merged_stmt: {merged_stmt}") | |
| 418 | + tables[k].append(merged_stmt) | |
| 419 | + | |
| 420 | + # Switch back from dict to array | |
| 421 | + tables = [tables[x][0] for x in tables] | |
| 422 | + | |
| 423 | + # execute SQL statments | |
| 424 | + con = sqlite3.connect(db_file) | |
| 425 | + cur = con.cursor() | |
| 426 | + | |
| 427 | + for stmt in tables: | |
| 428 | + print(f"Executing: {stmt}") | |
| 429 | + cur.execute(stmt) | |
| 430 | + con.commit() | |
| 431 | + | |
| 432 | + # Remove esoteric columns | |
| 433 | + #for i, stmt in enumerate(tables): | |
| 434 | + # user_msg = f"""Remove less descriptive columns from the following | |
| 435 | + # CREATE TABLE SQL statment: {stmt}""" | |
| 436 | + | |
| 437 | + # response = client.chat.completions.create( | |
| 438 | + # model=model, | |
| 439 | + # messages=[ | |
| 440 | + # {"role": "system", "content": SQL_FOCUS_PROMPT}, | |
| 441 | + # {"role": "user", "content": user_msg} | |
| 442 | + # ] | |
| 443 | + # ) | |
| 444 | + | |
| 445 | + # refined_stmt = response.choices[0].message.content | |
| 446 | + # if not refined_stmt.startswith("CREATE TABLE"): | |
| 447 | + # refined_stmt = stmt | |
| 448 | + | |
| 449 | + # print(f"refined_stmt: {refined_stmt}") | |
| 450 | + # tables[i] = refined_stmt | |
| 451 | + | |
| 452 | + cur.close() | |
| 453 | + con.close() | |
| 454 | + | |
| 455 | + # generate schema | |
| 456 | + generate_graph_schema(schema, client, model) |
added rag_sdk/Schema/decoder.py +80 −0
| @@ -0,0 +1,80 @@ | ||
| 1 | +import builtins | |
| 2 | +from .entity import Entity | |
| 3 | +from json import JSONDecoder | |
| 4 | + | |
| 5 | +# Decode Schema from JSON | |
| 6 | +class SchemaDecoder(): | |
| 7 | + def from_JSON(self, schema, json:str): | |
| 8 | + # Validate argument | |
| 9 | + if not isinstance(json, str) or json == "": | |
| 10 | + raise Exception("Unable to decode schema, make sure data is a none empty string") | |
| 11 | + | |
| 12 | + return self.decode(schema, JSONDecoder().decode(json)) | |
| 13 | + | |
| 14 | + # Create Schema from dict | |
| 15 | + def decode(self, schema, data:dict): | |
| 16 | + if not isinstance(data, dict): | |
| 17 | + raise Exception("Unable to decode schema, make sure data is a dict") | |
| 18 | + | |
| 19 | + # Validate JSON schema structure | |
| 20 | + if 'entities' not in data or 'relations' not in data: | |
| 21 | + raise Exception("Invalid schema format") | |
| 22 | + | |
| 23 | + entities = data['entities'] | |
| 24 | + relations = data['relations'] | |
| 25 | + | |
| 26 | + # Decode entities | |
| 27 | + for e in entities: | |
| 28 | + name, attributes = self._entity_decode(e) | |
| 29 | + e = schema.add_entity(name) | |
| 30 | + for attr in attributes: | |
| 31 | + e.add_attribute(attr['name'], attr['type'], attr['desc'], attr['unique'], attr['mandatory']) | |
| 32 | + | |
| 33 | + # Decode relations | |
| 34 | + for r in relations: | |
| 35 | + # Validate relation | |
| 36 | + if not isinstance(r, dict): | |
| 37 | + raise Exception("Invalid argument, expecting dict") | |
| 38 | + if 'name' not in r: | |
| 39 | + raise Exception("Invalid Relation format, missing 'name'") | |
| 40 | + if 'src' not in r: | |
| 41 | + raise Exception("Invalid Relation format, missing 'src'") | |
| 42 | + if 'dest' not in r: | |
| 43 | + raise Exception("Invalid Relation format, missing 'dest'") | |
| 44 | + | |
| 45 | + src = r['src'] | |
| 46 | + dest = r['dest'] | |
| 47 | + name = r['name'] | |
| 48 | + | |
| 49 | + src = schema.get_entity(src) | |
| 50 | + dest = schema.get_entity(dest) | |
| 51 | + | |
| 52 | + if src is None: | |
| 53 | + raise Exception(f"Missing src entity {r['src']}") | |
| 54 | + if dest is None: | |
| 55 | + raise Exception(f"Missing dest entity {r['dest']}") | |
| 56 | + | |
| 57 | + schema.add_relation(name, src, dest) | |
| 58 | + | |
| 59 | + return schema | |
| 60 | + | |
| 61 | + # Load Entity from dict | |
| 62 | + # see entityEncode generated structure | |
| 63 | + def _entity_decode(self, raw: dict): | |
| 64 | + if not isinstance(raw, dict): | |
| 65 | + raise Exception("Invalid argument, expecting dict") | |
| 66 | + if 'name' not in raw: | |
| 67 | + raise Exception("Invalid format, missing 'name'") | |
| 68 | + if 'attributes' not in raw: | |
| 69 | + raise Exception("Invalid format, missing 'attributes'") | |
| 70 | + | |
| 71 | + name = raw['name'] | |
| 72 | + attributes = raw['attributes'] | |
| 73 | + | |
| 74 | + for attr in attributes: | |
| 75 | + if 'name' not in attr or 'type' not in attr or 'unique' not in attr: | |
| 76 | + raise Exception("Invalid format, attribute must include a 'name', 'type' and 'unique' fields") | |
| 77 | + | |
| 78 | + attr['type'] = getattr(builtins, attr['type']) | |
| 79 | + | |
| 80 | + return name, attributes |
added rag_sdk/Schema/encoder.py +45 −0
| @@ -0,0 +1,45 @@ | ||
| 1 | +from json import JSONEncoder | |
| 2 | + | |
| 3 | +# Encode Schema into JSON | |
| 4 | +class SchemaEncoder(): | |
| 5 | + # encode schema to JSON string | |
| 6 | + def to_JSON(self, schema) -> str: | |
| 7 | + return JSONEncoder().encode(self.encode(schema)) | |
| 8 | + | |
| 9 | + # encode schema as dict | |
| 10 | + def encode(self, schema) -> dict: | |
| 11 | + # Make sure schema is valid | |
| 12 | + schema.validate() | |
| 13 | + | |
| 14 | + dict = {'entities': [], 'relations': []} | |
| 15 | + | |
| 16 | + for e in schema.entities: | |
| 17 | + e = schema.entities[e] | |
| 18 | + dict['entities'].append(self._encode_entity(e)) | |
| 19 | + | |
| 20 | + for r in schema.relations: | |
| 21 | + r = schema.relations[r] | |
| 22 | + dict['relations'].append(self._encode_relation(r)) | |
| 23 | + | |
| 24 | + return dict | |
| 25 | + | |
| 26 | + # Dump Entity into a dict | |
| 27 | + # format: | |
| 28 | + # {'name': name, | |
| 29 | + # 'attributes': [ | |
| 30 | + # {'name': attr_name, | |
| 31 | + # 'type': attr_type, | |
| 32 | + # 'unique': attr_unique},... | |
| 33 | + # ] | |
| 34 | + # } | |
| 35 | + def _encode_entity(self, e): | |
| 36 | + dict = {'name': e.name, 'attributes': []} | |
| 37 | + | |
| 38 | + for attr in e.attributes: | |
| 39 | + dict['attributes'].append({'name': attr.name, 'type': attr.type.__name__, 'desc': attr.desc, 'unique': attr.unique, 'mandatory': attr.mandatory}) | |
| 40 | + | |
| 41 | + return dict | |
| 42 | + | |
| 43 | + # Dump Relation into dict | |
| 44 | + def _encode_relation(self, r): | |
| 45 | + return {'name': r.name, 'src': r.src.name, 'dest': r.dest.name} |
added rag_sdk/Schema/entity.py +87 −0
| @@ -0,0 +1,87 @@ | ||
| 1 | +class Attribute(object): | |
| 2 | + def __init__(self, name:str, type:type, desc=None, unique=False, mandatory=False): | |
| 3 | + self.name = name | |
| 4 | + self.type = type | |
| 5 | + self.desc = desc | |
| 6 | + self.unique = unique | |
| 7 | + self.mandatory = mandatory | |
| 8 | + | |
| 9 | + def __eq__(self, other) -> bool: | |
| 10 | + if not isinstance(other, Attribute): | |
| 11 | + return False | |
| 12 | + | |
| 13 | + return (self.name == other.name and | |
| 14 | + self.type == other.type and | |
| 15 | + self.desc == other.desc and | |
| 16 | + self.unique == other.unique and | |
| 17 | + self.mandatory == other.mandatory) | |
| 18 | + | |
| 19 | + def __lt__(self, other): | |
| 20 | + return self.name < other.name | |
| 21 | + | |
| 22 | + def __hash__(self) -> int: | |
| 23 | + return hash(self.name) | |
| 24 | + | |
| 25 | +# Represents an ontolegy entity | |
| 26 | +class Entity(object): | |
| 27 | + def __init__(self, name:str): | |
| 28 | + if not isinstance(name, str) or name == "": | |
| 29 | + raise Exception("Entity name must be a none empty string") | |
| 30 | + | |
| 31 | + self.name = name | |
| 32 | + self.attributes = set([]) | |
| 33 | + | |
| 34 | + def __eq__(self, other) -> bool: | |
| 35 | + if not isinstance(other, Entity): | |
| 36 | + return False | |
| 37 | + | |
| 38 | + return (self.name == other.name and self.attributes == other.attributes) | |
| 39 | + | |
| 40 | + # Add attribute to entity | |
| 41 | + def add_attribute(self, name:str, type:type, desc=None, unique=False, mandatory=False): | |
| 42 | + # Validate arguments | |
| 43 | + if not isinstance(name, str) or name == "": | |
| 44 | + raise Exception("Attribute name must be a none empty string") | |
| 45 | + #if not isinstance(type, type) or type not in [int, str, bool]: | |
| 46 | + if type not in [int, float, str, bool]: | |
| 47 | + raise Exception("Attribute type must be one of the supported types") | |
| 48 | + if not isinstance(unique, bool): | |
| 49 | + raise Exception("primary_key must be of type bool") | |
| 50 | + if name in self.attributes: | |
| 51 | + raise Exception(f"Entity already contains attribute: {name}") | |
| 52 | + if isinstance(desc, str) and desc == "": | |
| 53 | + raise Exception(f"Invalid argument, desc should be a non empty string") | |
| 54 | + | |
| 55 | + desc = f"{self.name}'s {name}" if desc is None else desc | |
| 56 | + self.attributes.add(Attribute(name, type, desc, unique, mandatory)) | |
| 57 | + | |
| 58 | + # Remove attribute from entity | |
| 59 | + def remove_attribute(self, name:str): | |
| 60 | + # Validate argument | |
| 61 | + if not isinstance(name, str) or name == "": | |
| 62 | + raise Exception("Attribute name must be a none empty string") | |
| 63 | + | |
| 64 | + for attr in self.attributes: | |
| 65 | + if attr.name == name: | |
| 66 | + self.attributes.remove(attr) | |
| 67 | + return | |
| 68 | + | |
| 69 | + def get_attribute(self, name:str): | |
| 70 | + # Validate argument | |
| 71 | + if not isinstance(name, str) or name == "": | |
| 72 | + raise Exception("Attribute name must be a none empty string") | |
| 73 | + | |
| 74 | + for attr in self.attributes: | |
| 75 | + if attr.name == name: | |
| 76 | + return attr | |
| 77 | + | |
| 78 | + return None | |
| 79 | + | |
| 80 | + # returns a list of Entity's unique attributes | |
| 81 | + def unique_attributes(self): | |
| 82 | + unique_attrs = [] | |
| 83 | + for attr in self.attributes: | |
| 84 | + if attr.unique: | |
| 85 | + unique_attrs.append(attr) | |
| 86 | + | |
| 87 | + return sorted(unique_attrs) |
added rag_sdk/Schema/from_graph.py +48 −0
| @@ -0,0 +1,48 @@ | ||
| 1 | +from falkordb import Graph | |
| 2 | +from .entity import Entity | |
| 3 | +from .relation import Relation | |
| 4 | + | |
| 5 | +import builtins | |
| 6 | + | |
| 7 | +# Create a schema from an ontology graph | |
| 8 | +def schema_from_graph(s, g:Graph): | |
| 9 | + # Validate arguments | |
| 10 | + if not isinstance(g, Graph): | |
| 11 | + raise Exception("Invalid argument, g is expected to be a Graph") | |
| 12 | + | |
| 13 | + # Fetch entities | |
| 14 | + q = "MATCH (n) RETURN n" | |
| 15 | + res = g.query(q).result_set | |
| 16 | + | |
| 17 | + for row in res: | |
| 18 | + n = row[0] | |
| 19 | + name = n.labels[0] | |
| 20 | + | |
| 21 | + e = s.add_entity(name) | |
| 22 | + for prop in n.properties: | |
| 23 | + name = prop | |
| 24 | + prop = n.properties[prop] | |
| 25 | + | |
| 26 | + type = getattr(builtins, prop[0]) | |
| 27 | + desc = prop[1] | |
| 28 | + unique = prop[2] | |
| 29 | + mandatory = prop[3] | |
| 30 | + | |
| 31 | + e.add_attribute(name, type, desc, unique, mandatory) | |
| 32 | + | |
| 33 | + # Fetch relations | |
| 34 | + q = "MATCH (src)-[e]->(dest) RETURN src, e, dest" | |
| 35 | + res = g.query(q).result_set | |
| 36 | + | |
| 37 | + for row in res: | |
| 38 | + src = row[0].labels[0] | |
| 39 | + r = row[1].relation | |
| 40 | + dest = row[2].labels[0] | |
| 41 | + | |
| 42 | + src = s.get_entity(src) | |
| 43 | + dest = s.get_entity(dest) | |
| 44 | + | |
| 45 | + s.add_relation(r, src, dest) | |
| 46 | + | |
| 47 | + # Make sure schema is valid | |
| 48 | + s.validate() |
added rag_sdk/Schema/functions_gen.py +74 −0
| @@ -0,0 +1,74 @@ | ||
| 1 | +from .schema import Schema | |
| 2 | +from .entity import Entity | |
| 3 | +from .relation import Relation | |
| 4 | + | |
| 5 | +def relation_to_create_func(r:Relation): | |
| 6 | + src_lbl = r.src.name | |
| 7 | + dest_lbl = r.dest.name | |
| 8 | + func_name = r.name | |
| 9 | + | |
| 10 | + func = f"def {r.name}(args):\n" # def MovieStream(args): | |
| 11 | + func += "\targs = remove_none_values(args)\n" # args = remove_none_values(args) | |
| 12 | + | |
| 13 | + # extract required src arguments | |
| 14 | + src_attrs = r.src.unique_attributes() | |
| 15 | + | |
| 16 | + # extract required dest arguments | |
| 17 | + func += "\tq = \"MERGE (s:" + src_lbl + " {" | |
| 18 | + func += ", ".join([f"{attr.name}: " + f"${attr.name}" for attr in src_attrs]) | |
| 19 | + func += "}) " | |
| 20 | + | |
| 21 | + # extract required src arguments | |
| 22 | + dest_attrs = r.dest.unique_attributes() | |
| 23 | + | |
| 24 | + func += "MERGE (d:" + dest_lbl + " {" | |
| 25 | + func += ", ".join([f"{attr.name}: " + f"${attr.name}" for attr in dest_attrs]) | |
| 26 | + func += "}) " | |
| 27 | + | |
| 28 | + func += "MERGE (s)-[r:" + r.name + "]->(d)\"\n" | |
| 29 | + | |
| 30 | + # construct query params | |
| 31 | + func += "\tparams = {" | |
| 32 | + func += ", ".join([f"'{attr.name}': args['{attr.name}']" for attr in src_attrs]) | |
| 33 | + func += ", " | |
| 34 | + func += ", ".join([f"'{attr.name}': args['{attr.name}']" for attr in dest_attrs]) | |
| 35 | + func += "}\n" | |
| 36 | + | |
| 37 | + func += "\tg.query(q, params)\n" | |
| 38 | + | |
| 39 | + return (func_name, func) | |
| 40 | + | |
| 41 | +def entity_to_create_func(e:Entity): | |
| 42 | + func_name = f"Create_{e.name}" # Create_Actor | |
| 43 | + func = f"def {func_name}(args):\n" # def Create_Actor(args): | |
| 44 | + | |
| 45 | + func += "\targs = remove_none_values(args)\n" | |
| 46 | + func += "\tquery = \"MERGE (n:" + e.name + " {" # query = "MERGE (n:Actor { | |
| 47 | + | |
| 48 | + unique_attributes = e.unique_attributes() | |
| 49 | + | |
| 50 | + func += ", ".join([f"{attr.name}: ${attr.name}" for attr in unique_attributes]) + "})" | |
| 51 | + func += " SET n += $args\"\n" | |
| 52 | + | |
| 53 | + func += "\tparams = {" | |
| 54 | + func += ", ".join([f"'{attr.name}': args['{attr.name}']" for attr in unique_attributes]) | |
| 55 | + func += ", 'args': args}\n" | |
| 56 | + | |
| 57 | + func += "\tg.query(query, params)\n" | |
| 58 | + | |
| 59 | + return (func_name, func) | |
| 60 | + | |
| 61 | +def schema_to_functions(s:Schema): | |
| 62 | + if not isinstance(s, Schema): | |
| 63 | + raise Exception("Invalid argument, expecting a Schema object") | |
| 64 | + | |
| 65 | + functions = [] | |
| 66 | + for e in s.entities: | |
| 67 | + func = entity_to_create_func(s.entities[e]) | |
| 68 | + functions.append(func) | |
| 69 | + | |
| 70 | + for r in s.relations: | |
| 71 | + func = relation_to_create_func(s.relations[r]) | |
| 72 | + functions.append(func) | |
| 73 | + | |
| 74 | + return functions |
added rag_sdk/Schema/relation.py +28 −0
| @@ -0,0 +1,28 @@ | ||
| 1 | +from .entity import Entity | |
| 2 | + | |
| 3 | +# Represents an ontolegy relation | |
| 4 | +# A relation is composed of: | |
| 5 | +# 1. name | |
| 6 | +# 2. src entity | |
| 7 | +# 3. destination entity | |
| 8 | +class Relation(object): | |
| 9 | + def __init__(self, name:str, src:Entity, dest:Entity): | |
| 10 | + # Validate arguments | |
| 11 | + if not isinstance(name, str) or name == "": | |
| 12 | + raise Exception("Relation name must be a none empty string") | |
| 13 | + if not isinstance(src, Entity): | |
| 14 | + raise Exception("src must be am entity") | |
| 15 | + if not isinstance(dest, Entity): | |
| 16 | + raise Exception("dest must be am entity") | |
| 17 | + | |
| 18 | + self.src = src | |
| 19 | + self.dest = dest | |
| 20 | + self.name = name | |
| 21 | + | |
| 22 | + def __eq__(self, other) -> bool: | |
| 23 | + if not isinstance(other, Relation): | |
| 24 | + return False | |
| 25 | + | |
| 26 | + return (self.src == other.src and | |
| 27 | + self.dest == other.dest and | |
| 28 | + self.name == other.name) |
added rag_sdk/Schema/schema.py +141 −0
| @@ -0,0 +1,141 @@ | ||
| 1 | +from falkordb import Graph | |
| 2 | +from .entity import Entity | |
| 3 | +from .relation import Relation | |
| 4 | +from .encoder import SchemaEncoder | |
| 5 | +from .decoder import SchemaDecoder | |
| 6 | +from .to_graph import schema_to_graph | |
| 7 | +from .from_graph import schema_from_graph | |
| 8 | +from .auto_detect import schema_auto_detect | |
| 9 | + | |
| 10 | +# Knowledge Graph schema | |
| 11 | +# The schema captures graph entities in addition to their attributes | |
| 12 | +# and the relationship types between the entities | |
| 13 | +class Schema(object): | |
| 14 | + def __init__(self): | |
| 15 | + self.entities = {} | |
| 16 | + self.relations = {} | |
| 17 | + | |
| 18 | + def __eq__(self, other) -> bool: | |
| 19 | + if not isinstance(other, Schema): | |
| 20 | + return False | |
| 21 | + | |
| 22 | + if self.entities != other.entities: | |
| 23 | + return False | |
| 24 | + | |
| 25 | + if self.relations != other.relations: | |
| 26 | + return False | |
| 27 | + | |
| 28 | + return True | |
| 29 | + | |
| 30 | + # Add a new entity to schema | |
| 31 | + def add_entity(self, name:str): | |
| 32 | + # Validate arguments | |
| 33 | + if not isinstance(name, str) or name == "": | |
| 34 | + raise Exception(f"Invalid name argument, expecting none empty string") | |
| 35 | + if name in self.entities: | |
| 36 | + raise Exception(f"Entity {name} already exists") | |
| 37 | + | |
| 38 | + e = Entity(name) | |
| 39 | + self.entities[name] = e | |
| 40 | + return e | |
| 41 | + | |
| 42 | + # Get an entity from schema | |
| 43 | + def get_entity(self, name:str) -> Entity | None: | |
| 44 | + if not isinstance(name, str) or name == "": | |
| 45 | + raise Exception("Invalid argument, name should be a none empty string") | |
| 46 | + | |
| 47 | + if name in self.entities: | |
| 48 | + return self.entities[name] | |
| 49 | + else: | |
| 50 | + return None | |
| 51 | + | |
| 52 | + # Add a new relation to schema | |
| 53 | + def add_relation(self, name:str, src:Entity, dest:Entity): | |
| 54 | + # Validate arguments | |
| 55 | + if not isinstance(src, Entity) and not isinstance(src, str): | |
| 56 | + raise Exception(f"Invalid argument, src is expected to be either a string or an Entity") | |
| 57 | + if not isinstance(dest, Entity) and not isinstance(dest, str): | |
| 58 | + raise Exception(f"Invalid argument, dest is expected to be either a string or an Entity") | |
| 59 | + if not isinstance(name, str) or name == "": | |
| 60 | + raise Exception(f"Invalid name argument, expecting none empty string") | |
| 61 | + | |
| 62 | + if isinstance(src, str) and src == "": | |
| 63 | + raise Exception(f"Invalid src argument, expecting a non empty string") | |
| 64 | + if isinstance(dest, str) and dest == "": | |
| 65 | + raise Exception(f"Invalid dest argument, expecting a non empty string") | |
| 66 | + | |
| 67 | + if name in self.relations: | |
| 68 | + raise Exception(f"Relation {name} already exists") | |
| 69 | + | |
| 70 | + # fetch entities | |
| 71 | + if isinstance(src, str): | |
| 72 | + src = self.entities[src] | |
| 73 | + if isinstance(dest, str): | |
| 74 | + dest = self.entities[dest] | |
| 75 | + | |
| 76 | + # Both src and dest must have at least one unique attribute | |
| 77 | + if len(src.unique_attributes()) == 0: | |
| 78 | + raise Exception(f"{src.name} must have at least one unique attribute") | |
| 79 | + if len(dest.unique_attributes()) == 0: | |
| 80 | + raise Exception(f"{dest.name} must have at least one unique attribute") | |
| 81 | + | |
| 82 | + # Create relation and add it to schema | |
| 83 | + r = Relation(name, src, dest) | |
| 84 | + self.relations[name] = r | |
| 85 | + | |
| 86 | + return r | |
| 87 | + | |
| 88 | + # Validate schema | |
| 89 | + # Make sure schema is valid | |
| 90 | + def validate(self) -> bool: | |
| 91 | + # Make sure each Relation reference existing Entities | |
| 92 | + # And each referenced entity has at least one unique attribute | |
| 93 | + for r in self.relations: | |
| 94 | + r = self.relations[r] | |
| 95 | + src = r.src.name | |
| 96 | + dest = r.dest.name | |
| 97 | + if src not in self.entities: | |
| 98 | + raise Exception(f"Relation {r.name} reference a none existing entity {src}") | |
| 99 | + if dest not in self.entities: | |
| 100 | + raise Exception(f"Relation {r.name} reference a none existing entity {dest}") | |
| 101 | + | |
| 102 | + src = self.entities[src] | |
| 103 | + if len(src.unique_attributes()) == 0: | |
| 104 | + raise Exception(f"Relation {r.name} src endpoint {src.name} is missing a unique attribute") | |
| 105 | + | |
| 106 | + dest = self.entities[dest] | |
| 107 | + if len(dest.unique_attributes()) == 0: | |
| 108 | + raise Exception(f"Relation {r.name} src endpoint {dest.name} is missing a unique attribute") | |
| 109 | + | |
| 110 | + return True | |
| 111 | + | |
| 112 | + # Save schema as an ontology graph | |
| 113 | + def save_graph(self, g:Graph): | |
| 114 | + schema_to_graph(self, g) | |
| 115 | + | |
| 116 | + # encode schema to JSON string | |
| 117 | + def to_JSON(self) -> str: | |
| 118 | + encoder = SchemaEncoder() | |
| 119 | + return encoder.to_JSON(self) | |
| 120 | + | |
| 121 | + @classmethod | |
| 122 | + # Create a schema from an ontology graph | |
| 123 | + def from_graph(cls, g:Graph): | |
| 124 | + s = cls() | |
| 125 | + schema_from_graph(s, g) | |
| 126 | + return s | |
| 127 | + | |
| 128 | + @classmethod | |
| 129 | + # Auto detect schema from sources | |
| 130 | + def auto_detect(cls, sources, model="gpt-3.5-turbo-0125") -> 'Schema': | |
| 131 | + s = cls() | |
| 132 | + schema_auto_detect(s, sources, model) | |
| 133 | + return s | |
| 134 | + | |
| 135 | + @classmethod | |
| 136 | + # Create a schema from JSON | |
| 137 | + def from_JSON(cls, json:str) -> 'Schema': | |
| 138 | + s = cls() | |
| 139 | + decoder = SchemaDecoder() | |
| 140 | + decoder.from_JSON(s, json) | |
| 141 | + return s |
added rag_sdk/Schema/to_graph.py +54 −0
| @@ -0,0 +1,54 @@ | ||
| 1 | +from falkordb import Graph | |
| 2 | +from .entity import Entity | |
| 3 | +from .relation import Relation | |
| 4 | + | |
| 5 | +# Save schema as graph | |
| 6 | +def schema_to_graph(s, g:Graph) -> None: | |
| 7 | + # Validate arguments | |
| 8 | + if not isinstance(g, Graph): | |
| 9 | + raise Exception("Invalid argument, g is expected to be a Graph") | |
| 10 | + | |
| 11 | + # Make sure schema is valid | |
| 12 | + s.validate() | |
| 13 | + | |
| 14 | + # Clear graph | |
| 15 | + try: | |
| 16 | + g.delete() | |
| 17 | + except: | |
| 18 | + pass | |
| 19 | + | |
| 20 | + # Create graph entities | |
| 21 | + entity_ids = {} | |
| 22 | + for e in s.entities: | |
| 23 | + e = s.entities[e] | |
| 24 | + | |
| 25 | + # Construct entity creation query | |
| 26 | + q = f"""CREATE (n:{e.name}) | |
| 27 | + SET n = $args | |
| 28 | + RETURN ID(n)""" | |
| 29 | + | |
| 30 | + # Build query arguments | |
| 31 | + args = {} | |
| 32 | + for attr in e.attributes: | |
| 33 | + args[attr.name] = [attr.type.__name__, attr.desc, attr.unique, attr.mandatory] | |
| 34 | + | |
| 35 | + # Run query and get entity id | |
| 36 | + id = g.query(q, params={'args': args}).result_set[0][0] | |
| 37 | + | |
| 38 | + # Save | |
| 39 | + entity_ids[e.name] = id | |
| 40 | + | |
| 41 | + # Create graph relations | |
| 42 | + for r in s.relations: | |
| 43 | + r = s.relations[r] | |
| 44 | + | |
| 45 | + # Construct relationship creation query | |
| 46 | + q = f"""MATCH (src), (dest) | |
| 47 | + WHERE ID(src) = $src AND ID(dest) = $dest | |
| 48 | + CREATE (src)-[:{r.name}]->(dest)""" | |
| 49 | + | |
| 50 | + # Build query arguments | |
| 51 | + args = {'src': entity_ids[r.src.name], 'dest':entity_ids[r.dest.name]} | |
| 52 | + | |
| 53 | + # Run query and get entity id | |
| 54 | + g.query(q, params=args) |
added rag_sdk/Schema/tools_gen.py +138 −0
| @@ -0,0 +1,138 @@ | ||
| 1 | +from .entity import Entity | |
| 2 | +from .schema import Schema | |
| 3 | +from .relation import Relation | |
| 4 | + | |
| 5 | +def type_mapping(t) -> str: | |
| 6 | + if t not in [str, int, float, bool]: | |
| 7 | + raise Exception(f"Unsupported type: {t.__name__}") | |
| 8 | + | |
| 9 | + if t == str: | |
| 10 | + return "string" | |
| 11 | + elif t == bool: | |
| 12 | + return "boolean" | |
| 13 | + else: | |
| 14 | + return "number" | |
| 15 | + | |
| 16 | +def relation_to_tool(r:Relation): | |
| 17 | + # { | |
| 18 | + # "type": "function", | |
| 19 | + # "function": { | |
| 20 | + # "name": "directed", | |
| 21 | + # "description": "Form a connection between a director and a movie", | |
| 22 | + # "parameters": { | |
| 23 | + # "type": "object", | |
| 24 | + # "properties": { | |
| 25 | + # "src": {"type": "string", "description": "director's name"}, | |
| 26 | + # "dest": {"type": "string", "description": "movie's title"} | |
| 27 | + # }, | |
| 28 | + # "required": ["src", "dest"] | |
| 29 | + # } | |
| 30 | + # } | |
| 31 | + # } | |
| 32 | + | |
| 33 | + src = r.src | |
| 34 | + dest = r.dest | |
| 35 | + | |
| 36 | + tool = {} | |
| 37 | + tool['type'] = "function" | |
| 38 | + tool['function'] = {} | |
| 39 | + tool['function']['name'] = r.name | |
| 40 | + tool['function']['description'] = "Form a connection between " + src.name + " and " + dest.name | |
| 41 | + | |
| 42 | + tool['function']['parameters'] = {} | |
| 43 | + tool['function']['parameters']['type'] = "object" | |
| 44 | + tool['function']['parameters']['properties'] = {} | |
| 45 | + | |
| 46 | + required = [] | |
| 47 | + | |
| 48 | + # process edge's src | |
| 49 | + # see if src node has a unique attribute | |
| 50 | + attrs = src.unique_attributes() | |
| 51 | + for attr in attrs: | |
| 52 | + tool['function']['parameters']['properties'][attr.name] = {} | |
| 53 | + tool['function']['parameters']['properties'][attr.name]['type'] = type_mapping(attr.type) | |
| 54 | + if attr.desc is not None: | |
| 55 | + tool['function']['parameters']['properties'][attr.name]['description'] = attr.desc | |
| 56 | + else: | |
| 57 | + tool['function']['parameters']['properties'][attr.name]['description'] = src.name + "'s " + attr.name | |
| 58 | + required.append(attr.name) | |
| 59 | + | |
| 60 | + # process edge's destination | |
| 61 | + # see if dest node has a unique attribute | |
| 62 | + attrs = dest.unique_attributes() | |
| 63 | + for attr in attrs: | |
| 64 | + tool['function']['parameters']['properties'][attr.name] = {} | |
| 65 | + tool['function']['parameters']['properties'][attr.name]['type'] = type_mapping(attr.type) | |
| 66 | + if attr.desc is not None: | |
| 67 | + tool['function']['parameters']['properties'][attr.name]['description'] = attr.desc | |
| 68 | + else: | |
| 69 | + tool['function']['parameters']['properties'][attr.name]['description'] = dest.name + "'s " + attr.name | |
| 70 | + required.append(attr.name) | |
| 71 | + | |
| 72 | + tool['function']['parameters']['required'] = required | |
| 73 | + | |
| 74 | + return tool | |
| 75 | + | |
| 76 | +def entity_to_tool(e:Entity): | |
| 77 | + # { | |
| 78 | + # "type": "function", | |
| 79 | + # "function": { | |
| 80 | + # "name": "directed", | |
| 81 | + # "description": "Form a connection between a director and a movie", | |
| 82 | + # "parameters": { | |
| 83 | + # "type": "object", | |
| 84 | + # "properties": { | |
| 85 | + # "src": {"type": "string", "description": "director's name"}, | |
| 86 | + # "dest": {"type": "string", "description": "movie's title"} | |
| 87 | + # }, | |
| 88 | + # "required": ["src", "dest"] | |
| 89 | + # } | |
| 90 | + # } | |
| 91 | + # } | |
| 92 | + | |
| 93 | + tool = {} | |
| 94 | + tool['type'] = "function" | |
| 95 | + tool['function'] = {} | |
| 96 | + | |
| 97 | + tool['function']['name'] = "Create_" + e.name | |
| 98 | + tool['function']['description'] = "Create a new " + e.name | |
| 99 | + | |
| 100 | + tool['function']['parameters'] = {} | |
| 101 | + tool['function']['parameters']['type'] = "object" | |
| 102 | + tool['function']['parameters']['properties'] = {} | |
| 103 | + | |
| 104 | + unique_attributes = [] | |
| 105 | + for attr in e.attributes: | |
| 106 | + attribute_name = attr.name | |
| 107 | + attribute_type = type_mapping(attr.type) | |
| 108 | + attribute_unique = attr.unique | |
| 109 | + | |
| 110 | + tool['function']['parameters']['properties'][attribute_name] = {} | |
| 111 | + tool['function']['parameters']['properties'][attribute_name]['type'] = attribute_type | |
| 112 | + if attr.desc is None: | |
| 113 | + tool['function']['parameters']['properties'][attribute_name]['description'] = f"{e.name}'s {attr.name}" | |
| 114 | + else: | |
| 115 | + tool['function']['parameters']['properties'][attribute_name]['description'] = attr.desc | |
| 116 | + | |
| 117 | + if attribute_unique: | |
| 118 | + unique_attributes.append(attribute_name) | |
| 119 | + | |
| 120 | + tool['function']['parameters']['required'] = unique_attributes | |
| 121 | + | |
| 122 | + return tool | |
| 123 | + | |
| 124 | +# Create OpenAI tools from schema | |
| 125 | +def schema_to_tools(s:Schema): | |
| 126 | + if not isinstance(s, Schema): | |
| 127 | + raise Exception("Invalid argument, expecting a Schema object") | |
| 128 | + | |
| 129 | + tools = [] | |
| 130 | + for e in s.entities: | |
| 131 | + tool = entity_to_tool(s.entities[e]) | |
| 132 | + tools.append(tool) | |
| 133 | + | |
| 134 | + for r in s.relations: | |
| 135 | + tool = relation_to_tool(s.relations[r]) | |
| 136 | + tools.append(tool) | |
| 137 | + | |
| 138 | + return tools |
added rag_sdk/__init__.py +2 −0
| @@ -0,0 +1,2 @@ | ||
| 1 | +from .kg import KG | |
| 2 | +from .source import Source |
added rag_sdk/kg.py +169 −0
| @@ -0,0 +1,169 @@ | ||
| 1 | +import os | |
| 2 | +import queue | |
| 3 | +import concurrent.futures | |
| 4 | +from typing_extensions import AbstractSet | |
| 5 | + | |
| 6 | +from .prompts import * | |
| 7 | +from openai import OpenAI | |
| 8 | +from falkordb import FalkorDB | |
| 9 | +from .query_graph import query | |
| 10 | +from .Schema.schema import Schema | |
| 11 | +from .source import Source, AbstractSource | |
| 12 | +from .Schema.tools_gen import schema_to_tools | |
| 13 | +from .Schema.functions_gen import schema_to_functions | |
| 14 | + | |
| 15 | +class KG(object): | |
| 16 | + """Knowledge Graph model data as a network of entities and relations | |
| 17 | + To create one it is best to provide a schema which will define the graph's ontology | |
| 18 | + In addition to a set of sources from which entities and relations will be extracted. | |
| 19 | + """ | |
| 20 | + def __init__(self, name:str, host:str="127.0.0.1", port:int=6379, username:str|None=None, password:str|None=None, | |
| 21 | + model:str="gpt-4-1106-preview", schema:Schema|None=None): | |
| 22 | + """ | |
| 23 | + Initialize Knowledge Graph | |
| 24 | + | |
| 25 | + Parameters: | |
| 26 | + name (str): Knowledge graph name. | |
| 27 | + host (str): FalkorDB hostname. | |
| 28 | + port (int): FalkorDB port number. | |
| 29 | + username (str|None): FalkorDB username. | |
| 30 | + password (str|None): FalkorDB password. | |
| 31 | + model (str): OpenAI model to use. | |
| 32 | + """ | |
| 33 | + | |
| 34 | + # connect to database | |
| 35 | + self.db = FalkorDB(host=host, port=port, username=username, password=password) | |
| 36 | + self.graph = self.db.select_graph(name) | |
| 37 | + | |
| 38 | + self.name = name | |
| 39 | + self.model = model | |
| 40 | + self.schema = schema | |
| 41 | + self.client = None # OpenAI client | |
| 42 | + self.sources = set([]) | |
| 43 | + self.ontolegy_ratio = 0.1 # Sampaling ratio for ontolegy detection | |
| 44 | + | |
| 45 | + def add_source(self, source:str) -> AbstractSource: | |
| 46 | + """ | |
| 47 | + Add source from which knowledge will be extracted | |
| 48 | + | |
| 49 | + Parameters: | |
| 50 | + source (src): path to source | |
| 51 | + | |
| 52 | + Returns: | |
| 53 | + AbstractSource: A source object | |
| 54 | + """ | |
| 55 | + | |
| 56 | + if not isinstance(source, str) or source == "": | |
| 57 | + raise Exception("Invalid argument, source should be a none empty string.") | |
| 58 | + | |
| 59 | + s = Source(source) | |
| 60 | + self.sources.add(s) | |
| 61 | + | |
| 62 | + return s | |
| 63 | + | |
| 64 | + def remove_source(self, source:str|AbstractSource): | |
| 65 | + """ | |
| 66 | + Remove source from sources | |
| 67 | + | |
| 68 | + Parameters: | |
| 69 | + source (str|AbstractSource): source to remove | |
| 70 | + """ | |
| 71 | + | |
| 72 | + if not isinstance(source, str) and not isinstance(source, AbstractSource): | |
| 73 | + raise Exception("Invalid argument, source should be a string or a Source") | |
| 74 | + | |
| 75 | + if isinstance(source, str): | |
| 76 | + for s in self.sources: | |
| 77 | + if s.source == source: | |
| 78 | + self.sources.remove(s) | |
| 79 | + break | |
| 80 | + else: | |
| 81 | + self.sources.remove(source) | |
| 82 | + | |
| 83 | + def list_sources(self) -> list[AbstractSource]: | |
| 84 | + """ | |
| 85 | + List of sources associated with knowledge graph | |
| 86 | + | |
| 87 | + Returns: | |
| 88 | + list[AbstractSource]: sources | |
| 89 | + """ | |
| 90 | + | |
| 91 | + return [s.source for s in self.sources] | |
| 92 | + | |
| 93 | + def _createKGWithSchema(self): | |
| 94 | + # Save schema as an ontology graph | |
| 95 | + self.schema.save_graph(self.graph) | |
| 96 | + | |
| 97 | + # Create Knowledge Graph construction assistant | |
| 98 | + | |
| 99 | + # Generate assistant's toolings | |
| 100 | + tools = schema_to_tools(self.schema) | |
| 101 | + | |
| 102 | + # Generate functions from schema | |
| 103 | + funcs = schema_to_functions(self.schema) | |
| 104 | + functions_names = [func[0] for func in funcs] | |
| 105 | + functions_impl = [func[1] for func in funcs] | |
| 106 | + | |
| 107 | + # 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) | |
| 131 | + | |
| 132 | + # Run assistant | |
| 133 | + result = dynamic_module.build_graph_from_sources(self, self.client, self.sources) | |
| 134 | + | |
| 135 | + def _createKGWithoutSchema(self): | |
| 136 | + pass | |
| 137 | + | |
| 138 | + def create(self): | |
| 139 | + """ | |
| 140 | + Create knowledge graph | |
| 141 | + Extract entities and relations from sources | |
| 142 | + """ | |
| 143 | + self.client = OpenAI() | |
| 144 | + | |
| 145 | + if self.schema is not None: | |
| 146 | + self._createKGWithSchema() | |
| 147 | + else: | |
| 148 | + self._createKGWithoutSchema() | |
| 149 | + | |
| 150 | + | |
| 151 | + def ask(self, question:str, messages:list=None) -> tuple[str, list]: | |
| 152 | + """ | |
| 153 | + Query the knowledge graph using natural language | |
| 154 | + if the query is asked as part of a longer conversation make sure to | |
| 155 | + include past messages. | |
| 156 | + | |
| 157 | + Rreturns: | |
| 158 | + tuple[str, list]: answer, conversation messages | |
| 159 | + | |
| 160 | + 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) | |
| 163 | + """ | |
| 164 | + | |
| 165 | + if messages is None: | |
| 166 | + messages = [] | |
| 167 | + | |
| 168 | + answer = query(self, question, messages, self.model) | |
| 169 | + return (answer, messages) |
added rag_sdk/prompts.py +76 −0
| @@ -0,0 +1,76 @@ | ||
| 1 | +ONTOLOGY_DETECTION_SYSTEM_PROMPT = """Create SQL statement which will capture the different entities and the relations between them in the provided text. | |
| 2 | +Each table should represent either a single entity type with the entity's attributes as the table columns or a relation between two entities, using foreign keys. | |
| 3 | +For example an IMDB document is likely to produce 5 tables: Movie, Actor and Director each with its own columns and ACTED and DIRECTED tables. | |
| 4 | +Do not create an ID primary key column but set the most compelling attribute as the entity's primary key | |
| 5 | +Make sure to call the run_sql function provided in your tools set for each sql statement generated.""" | |
| 6 | + | |
| 7 | +KNOWLEDGE_EXTRACTION_SYSTEM_PROMPT = """You are a helpful assistant with the goal of extracting | |
| 8 | +entities and relationships from text""" | |
| 9 | + | |
| 10 | +SQL_FOLDING_PROMPT = """The following two CREATE TABLE SQL statments are | |
| 11 | +creating the same table name, consolidate the two into a single | |
| 12 | +CREATE TABLE SQL statment. | |
| 13 | +Remove all duplicated columns. | |
| 14 | +Make sure the number of PRIMARY KEYs and FOREIGN KEYs is maintained. | |
| 15 | +Reply only with the result SQL statment, the reply should start with: | |
| 16 | +CREATE TABLE and end with ); | |
| 17 | +For example: given the two CREATE TABLE SQL: | |
| 18 | +CREATE TABLE Person (FirstName string, LastName string, Age int); | |
| 19 | +CREATE TABLE Person (SurName string, ForeName string, Height int); | |
| 20 | +The response should be: | |
| 21 | +CREATE TABLE Person (FirstName string, LastName string, Age int, Height int); | |
| 22 | +""" | |
| 23 | + | |
| 24 | +SQL_FOCUS_PROMPT = """Given a CREATE TABLE SQL statment the table name | |
| 25 | + represents some entity, in case the number of columns in the table is | |
| 26 | + greater than 5, remove columns which are less descriptive of the entity. | |
| 27 | + Do NOT remove columns which are either a PRIMARY KEY or a FOREIGN KEY. | |
| 28 | + Make sure to leave at least 5 columns. | |
| 29 | + Do NOT rename the table name. | |
| 30 | + Reply only with the result SQL statment, the reply should start with: | |
| 31 | + CREATE TABLE and end with ); | |
| 32 | + For example: given the CREATE TABLE SQL: | |
| 33 | + CREATE TABLE Movie ( | |
| 34 | + Title string PRIMARY KEY, | |
| 35 | + Genre string, | |
| 36 | + ReleaseYear int, | |
| 37 | + Rating string, | |
| 38 | + Language string, | |
| 39 | + BoxOffice string, | |
| 40 | + streaming_date STRING, | |
| 41 | + runtime STRING | |
| 42 | + ); | |
| 43 | + The response should be: | |
| 44 | + CREATE TABLE Movie ( | |
| 45 | + Title string PRIMARY KEY, | |
| 46 | + Genre string, | |
| 47 | + ReleaseYear int, | |
| 48 | + Rating string, | |
| 49 | + runtime STRING | |
| 50 | + ); | |
| 51 | + Another example: given the CREATE TABLE SQL: | |
| 52 | + CREATE TABLE Episode ( | |
| 53 | + show_title VARCHAR(255), | |
| 54 | + show_year VARCHAR(4), | |
| 55 | + season INT, | |
| 56 | + episode_number INT, | |
| 57 | + episode_title VARCHAR(255), | |
| 58 | + air_date DATE, | |
| 59 | + episode_rating DECIMAL(2, 1), | |
| 60 | + FOREIGN KEY (show_title, show_year) REFERENCES TVShow(title, year) | |
| 61 | + ); | |
| 62 | + You are not allowed to remove either show_title or show_year as these are part of the table's | |
| 63 | + foreign key. | |
| 64 | + """ | |
| 65 | + | |
| 66 | +RELATIONSHIP_NAMING_PROMPT = """"You are a Cypher expert, help suggest names for | |
| 67 | +relationship types connecting source node to destination node. | |
| 68 | +Respond only with the suggested name. | |
| 69 | +For example given source node of type 'Actor' and destination node of type 'Movie' | |
| 70 | +Replay with: ACTED""" | |
| 71 | + | |
| 72 | +FIND_UNIQUE_ATTRIBUTE_PROMPT = """From the list of attributes describing a graph node | |
| 73 | +pick the most suitble attribute to act as a unique identifier of the node. | |
| 74 | +Respond only with the suggested attribute name | |
| 75 | +For example given a list of attributes: series_title, air_date, season_number, episode_number, title | |
| 76 | +Describing the graph entity "Episode" Reply with: title""" |
added rag_sdk/source.py +86 −0
| @@ -0,0 +1,86 @@ | ||
| 1 | +import re | |
| 2 | +import requests | |
| 3 | +from bs4 import BeautifulSoup | |
| 4 | +from abc import ABC, abstractmethod | |
| 5 | + | |
| 6 | +def download_resource(url): | |
| 7 | + print(f"Downloading: {url}") | |
| 8 | + | |
| 9 | + # Send an HTTP GET request to the URL | |
| 10 | + response = requests.get(url) | |
| 11 | + | |
| 12 | + # Check if the request was successful (status code 200) | |
| 13 | + content = None | |
| 14 | + if response.status_code == 200: | |
| 15 | + # Retrieve content | |
| 16 | + content = response.text | |
| 17 | + else: | |
| 18 | + print(f"Failed to retrieve content. Status code: {response.status_code}") | |
| 19 | + | |
| 20 | + return content | |
| 21 | + | |
| 22 | +def Source(source:str): | |
| 23 | + if not isinstance(source, str) or source == "": | |
| 24 | + raise Exception("Invalid argument, source should be a none empty string.") | |
| 25 | + | |
| 26 | + if ".pdf" in source.lower(): | |
| 27 | + return PDF(source) | |
| 28 | + elif ".html" in source.lower(): | |
| 29 | + return HTML(source) | |
| 30 | + else: | |
| 31 | + return TEXT(source) | |
| 32 | + | |
| 33 | +class AbstractSource(ABC): | |
| 34 | + def __init__(self, source:str): | |
| 35 | + self.source = source | |
| 36 | + self.content = None | |
| 37 | + | |
| 38 | + @abstractmethod | |
| 39 | + def load(self) -> str: | |
| 40 | + pass | |
| 41 | + | |
| 42 | + def __eq__(self, other) -> bool: | |
| 43 | + if not isinstance(other, AbstractSource): | |
| 44 | + return False | |
| 45 | + | |
| 46 | + return self.source == other.source | |
| 47 | + | |
| 48 | + def __hash__(self): | |
| 49 | + return hash(self.source) | |
| 50 | + | |
| 51 | +class PDF(AbstractSource): | |
| 52 | + def __init__(self, source): | |
| 53 | + super().__init__(source) | |
| 54 | + | |
| 55 | + def load(self): | |
| 56 | + # extract text from PDF, populate self.content | |
| 57 | + self.content = None | |
| 58 | + | |
| 59 | +class TEXT(AbstractSource): | |
| 60 | + def __init__(self, source): | |
| 61 | + super().__init__(source) | |
| 62 | + | |
| 63 | + def load(self): | |
| 64 | + if self.content is None: | |
| 65 | + # populate self.content | |
| 66 | + with open(self.source, 'r') as f: | |
| 67 | + self.content = f.read() | |
| 68 | + | |
| 69 | + return self.content | |
| 70 | + | |
| 71 | +class HTML(AbstractSource): | |
| 72 | + def __init__(self, source): | |
| 73 | + super().__init__(source) | |
| 74 | + | |
| 75 | + def load(self): | |
| 76 | + with open(self.source, 'r') as f: | |
| 77 | + self.content = f.read() | |
| 78 | + | |
| 79 | + # extract text from HTML, populate self.content | |
| 80 | + soup = BeautifulSoup(self.content, 'html.parser') | |
| 81 | + | |
| 82 | + # Extract text from the HTML | |
| 83 | + self.content = soup.get_text() | |
| 84 | + | |
| 85 | + # Remove extra newlines | |
| 86 | + self.content = re.sub(r'\n{2,}', '\n', self.content) |
added rag_sdk/template.py +148 −0
| @@ -0,0 +1,148 @@ | ||
| 1 | +import json | |
| 2 | +import time | |
| 3 | +import concurrent.futures | |
| 4 | +from openai import OpenAI | |
| 5 | +from prompts import KNOWLEDGE_EXTRACTION_SYSTEM_PROMPT | |
| 6 | +from falkordb import FalkorDB | |
| 7 | + | |
| 8 | +g = None # graph | |
| 9 | +client = None # OpenAI client | |
| 10 | + | |
| 11 | +tools = [<TOOLS>] | |
| 12 | + | |
| 13 | +<FUNCTIONS> | |
| 14 | + | |
| 15 | +available_functions = <AVAILABLE_FUNCTIONS> | |
| 16 | + | |
| 17 | +def remove_none_values(args): | |
| 18 | + return {key: value for key, value in args.items() if value is not None} | |
| 19 | + | |
| 20 | +def create_assistant(client, assistant_name, instructions, model): | |
| 21 | + assistant = client.beta.assistants.create( | |
| 22 | + name = assistant_name, | |
| 23 | + instructions = instructions, | |
| 24 | + model = model, | |
| 25 | + tools = tools | |
| 26 | + ) | |
| 27 | + | |
| 28 | + return assistant | |
| 29 | + | |
| 30 | +def initiate_interaction(client, assistant, user_message): | |
| 31 | + run = client.beta.threads.create_and_run( | |
| 32 | + assistant_id=assistant.id, | |
| 33 | + thread={ "messages": [ {"role": "user", "content": user_message} ] } | |
| 34 | + ) | |
| 35 | + | |
| 36 | + return run | |
| 37 | + | |
| 38 | +def handle_run(client, run): | |
| 39 | + while True: | |
| 40 | + run = client.beta.threads.runs.retrieve(thread_id=run.thread_id, run_id=run.id) | |
| 41 | + | |
| 42 | + if run.status == "completed": | |
| 43 | + print("Run completed") | |
| 44 | + return | |
| 45 | + | |
| 46 | + if run.status == "expired": | |
| 47 | + print(f"Run expired") | |
| 48 | + return | |
| 49 | + | |
| 50 | + if run.status == "cancelling" or run.status == "cancelled" or run.status == "failed": | |
| 51 | + print(f"Run failed") | |
| 52 | + return | |
| 53 | + | |
| 54 | + # wait for run to complete | |
| 55 | + if run.status == "queued": | |
| 56 | + print("Run queued") | |
| 57 | + time.sleep(1) | |
| 58 | + continue | |
| 59 | + | |
| 60 | + if run.status == "in_progress": | |
| 61 | + last_step_id = None | |
| 62 | + print("Run in progress") | |
| 63 | + run_steps = [] | |
| 64 | + # if last_step_id is None: | |
| 65 | + # run_steps = client.beta.threads.runs.steps.list(thread_id=run.thread_id, run_id=run.id) | |
| 66 | + # else: | |
| 67 | + # run_steps = client.beta.threads.runs.steps.list(thread_id=run.thread_id, run_id=run.id, after=last_step_id) | |
| 68 | + run_steps = client.beta.threads.runs.steps.list(thread_id=run.thread_id, run_id=run.id) | |
| 69 | + | |
| 70 | + for step in run_steps.data: | |
| 71 | + if step.status == "in_progress": | |
| 72 | + step_details = step.step_details | |
| 73 | + if step_details.type == "tool_calls": | |
| 74 | + for tool_call in step_details.tool_calls: | |
| 75 | + try: | |
| 76 | + if tool_call.type == "function": | |
| 77 | + func = tool_call.function | |
| 78 | + func_name = func.name | |
| 79 | + args = func.arguments | |
| 80 | + args = json.loads(args) | |
| 81 | + print(f"Function: {func_name}, {args}") | |
| 82 | + f = available_functions[func_name] | |
| 83 | + f(args) | |
| 84 | + except: | |
| 85 | + print(f"tool_call: {tool_call}") | |
| 86 | + pass | |
| 87 | + | |
| 88 | + last_step_id = run_steps.last_id | |
| 89 | + | |
| 90 | + time.sleep(1) | |
| 91 | + continue | |
| 92 | + | |
| 93 | + if run.status == "requires_action": | |
| 94 | + print(f"Run requires action") | |
| 95 | + action = run.required_action | |
| 96 | + if action.type == "submit_tool_outputs": | |
| 97 | + tool_outputs = action.submit_tool_outputs | |
| 98 | + outputs = [] | |
| 99 | + for tool in tool_outputs.tool_calls: | |
| 100 | + tool_call_id = tool.id | |
| 101 | + tool_type = tool.type | |
| 102 | + func = tool.function | |
| 103 | + func_name = func.name | |
| 104 | + args = func.arguments | |
| 105 | + args = json.loads(args) | |
| 106 | + print(f"Function: {func_name}, {args}") | |
| 107 | + | |
| 108 | + f = available_functions[func_name] | |
| 109 | + f(args) | |
| 110 | + | |
| 111 | + outputs.append({ "tool_call_id": tool_call_id, "output": "OK" }) | |
| 112 | + | |
| 113 | + # respond to action | |
| 114 | + run = client.beta.threads.runs.submit_tool_outputs( | |
| 115 | + thread_id=run.thread_id, | |
| 116 | + run_id=run.id, | |
| 117 | + tool_outputs=outputs | |
| 118 | + ) | |
| 119 | + | |
| 120 | + continue | |
| 121 | + | |
| 122 | +def process_source(client, assistant, src): | |
| 123 | + text = src.load()[:32000] | |
| 124 | + user_message = f"Extracts entities and relations from the following text:\n {text}" | |
| 125 | + | |
| 126 | + run = initiate_interaction(client, assistant, user_message) | |
| 127 | + | |
| 128 | + handle_run(client, run) | |
| 129 | + | |
| 130 | + client.beta.threads.delete(run.thread_id) | |
| 131 | + | |
| 132 | +def build_graph_from_sources(kg, client, srcs:set): | |
| 133 | + global g | |
| 134 | + g = kg.graph | |
| 135 | + | |
| 136 | + assistant = create_assistant(client, kg.name, KNOWLEDGE_EXTRACTION_SYSTEM_PROMPT, model=kg.model) | |
| 137 | + | |
| 138 | + # Create thread pool | |
| 139 | + with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor: | |
| 140 | + tasks = [] | |
| 141 | + # extract entities and relationships from each page | |
| 142 | + for src in srcs: | |
| 143 | + task = executor.submit(process_source, client, assistant, src) | |
| 144 | + | |
| 145 | + # Wait for all tasks to complete | |
| 146 | + concurrent.futures.wait(tasks) | |
| 147 | + | |
| 148 | + print("Done") |
added template.py +148 −0
| @@ -0,0 +1,148 @@ | ||
| 1 | +import json | |
| 2 | +import time | |
| 3 | +import concurrent.futures | |
| 4 | +from openai import OpenAI | |
| 5 | +from rag_sdk.prompts import KNOWLEDGE_EXTRACTION_SYSTEM_PROMPT | |
| 6 | +from falkordb import FalkorDB | |
| 7 | + | |
| 8 | +g = None # graph | |
| 9 | +client = None # OpenAI client | |
| 10 | + | |
| 11 | +tools = [<TOOLS>] | |
| 12 | + | |
| 13 | +<FUNCTIONS> | |
| 14 | + | |
| 15 | +available_functions = <AVAILABLE_FUNCTIONS> | |
| 16 | + | |
| 17 | +def remove_none_values(args): | |
| 18 | + return {key: value for key, value in args.items() if value is not None} | |
| 19 | + | |
| 20 | +def create_assistant(client, assistant_name, instructions, model): | |
| 21 | + assistant = client.beta.assistants.create( | |
| 22 | + name = assistant_name, | |
| 23 | + instructions = instructions, | |
| 24 | + model = model, | |
| 25 | + tools = tools | |
| 26 | + ) | |
| 27 | + | |
| 28 | + return assistant | |
| 29 | + | |
| 30 | +def initiate_interaction(client, assistant, user_message): | |
| 31 | + run = client.beta.threads.create_and_run( | |
| 32 | + assistant_id=assistant.id, | |
| 33 | + thread={ "messages": [ {"role": "user", "content": user_message} ] } | |
| 34 | + ) | |
| 35 | + | |
| 36 | + return run | |
| 37 | + | |
| 38 | +def handle_run(client, run): | |
| 39 | + while True: | |
| 40 | + run = client.beta.threads.runs.retrieve(thread_id=run.thread_id, run_id=run.id) | |
| 41 | + | |
| 42 | + if run.status == "completed": | |
| 43 | + print("Run completed") | |
| 44 | + return | |
| 45 | + | |
| 46 | + if run.status == "expired": | |
| 47 | + print(f"Run expired") | |
| 48 | + return | |
| 49 | + | |
| 50 | + if run.status == "cancelling" or run.status == "cancelled" or run.status == "failed": | |
| 51 | + print(f"Run failed") | |
| 52 | + return | |
| 53 | + | |
| 54 | + # wait for run to complete | |
| 55 | + if run.status == "queued": | |
| 56 | + print("Run queued") | |
| 57 | + time.sleep(1) | |
| 58 | + continue | |
| 59 | + | |
| 60 | + if run.status == "in_progress": | |
| 61 | + last_step_id = None | |
| 62 | + print("Run in progress") | |
| 63 | + run_steps = [] | |
| 64 | + # if last_step_id is None: | |
| 65 | + # run_steps = client.beta.threads.runs.steps.list(thread_id=run.thread_id, run_id=run.id) | |
| 66 | + # else: | |
| 67 | + # run_steps = client.beta.threads.runs.steps.list(thread_id=run.thread_id, run_id=run.id, after=last_step_id) | |
| 68 | + run_steps = client.beta.threads.runs.steps.list(thread_id=run.thread_id, run_id=run.id) | |
| 69 | + | |
| 70 | + for step in run_steps.data: | |
| 71 | + if step.status == "in_progress": | |
| 72 | + step_details = step.step_details | |
| 73 | + if step_details.type == "tool_calls": | |
| 74 | + for tool_call in step_details.tool_calls: | |
| 75 | + try: | |
| 76 | + if tool_call.type == "function": | |
| 77 | + func = tool_call.function | |
| 78 | + func_name = func.name | |
| 79 | + args = func.arguments | |
| 80 | + args = json.loads(args) | |
| 81 | + print(f"Function: {func_name}, {args}") | |
| 82 | + f = available_functions[func_name] | |
| 83 | + f(args) | |
| 84 | + except: | |
| 85 | + print(f"tool_call: {tool_call}") | |
| 86 | + pass | |
| 87 | + | |
| 88 | + last_step_id = run_steps.last_id | |
| 89 | + | |
| 90 | + time.sleep(1) | |
| 91 | + continue | |
| 92 | + | |
| 93 | + if run.status == "requires_action": | |
| 94 | + print(f"Run requires action") | |
| 95 | + action = run.required_action | |
| 96 | + if action.type == "submit_tool_outputs": | |
| 97 | + tool_outputs = action.submit_tool_outputs | |
| 98 | + outputs = [] | |
| 99 | + for tool in tool_outputs.tool_calls: | |
| 100 | + tool_call_id = tool.id | |
| 101 | + tool_type = tool.type | |
| 102 | + func = tool.function | |
| 103 | + func_name = func.name | |
| 104 | + args = func.arguments | |
| 105 | + args = json.loads(args) | |
| 106 | + print(f"Function: {func_name}, {args}") | |
| 107 | + | |
| 108 | + f = available_functions[func_name] | |
| 109 | + f(args) | |
| 110 | + | |
| 111 | + outputs.append({ "tool_call_id": tool_call_id, "output": "OK" }) | |
| 112 | + | |
| 113 | + # respond to action | |
| 114 | + run = client.beta.threads.runs.submit_tool_outputs( | |
| 115 | + thread_id=run.thread_id, | |
| 116 | + run_id=run.id, | |
| 117 | + tool_outputs=outputs | |
| 118 | + ) | |
| 119 | + | |
| 120 | + continue | |
| 121 | + | |
| 122 | +def process_source(client, assistant, src): | |
| 123 | + text = src.load()[:32000] | |
| 124 | + user_message = f"Extracts entities and relations from the following text:\n {text}" | |
| 125 | + | |
| 126 | + run = initiate_interaction(client, assistant, user_message) | |
| 127 | + | |
| 128 | + handle_run(client, run) | |
| 129 | + | |
| 130 | + client.beta.threads.delete(run.thread_id) | |
| 131 | + | |
| 132 | +def build_graph_from_sources(kg, client, srcs:set): | |
| 133 | + global g | |
| 134 | + g = kg.graph | |
| 135 | + | |
| 136 | + assistant = create_assistant(client, kg.name, KNOWLEDGE_EXTRACTION_SYSTEM_PROMPT, model=kg.model) | |
| 137 | + | |
| 138 | + # Create thread pool | |
| 139 | + with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor: | |
| 140 | + tasks = [] | |
| 141 | + # extract entities and relationships from each page | |
| 142 | + for src in srcs: | |
| 143 | + task = executor.submit(process_source, client, assistant, src) | |
| 144 | + | |
| 145 | + # Wait for all tasks to complete | |
| 146 | + concurrent.futures.wait(tasks) | |
| 147 | + | |
| 148 | + print("Done") |
added tests/__init__.py +0 −0
added tests/test_auto_detect.py +12 −0
| @@ -0,0 +1,12 @@ | ||
| 1 | +import unittest | |
| 2 | +from rag_sdk import Source | |
| 3 | +from rag_sdk.Schema import Schema | |
| 4 | + | |
| 5 | +class TestSchemaAutoDetect(unittest.TestCase): | |
| 6 | + def test_schema(self): | |
| 7 | + sources = [Source("./data/madoff.txt")] | |
| 8 | + s = Schema.auto_detect(sources) | |
| 9 | + print(f"schema: {s.to_JSON()}") | |
| 10 | + | |
| 11 | +if __name__ == '__main__': | |
| 12 | + unittest.main() |
added tests/test_kg.py +49 −0
| @@ -0,0 +1,49 @@ | ||
| 1 | +import unittest | |
| 2 | +from rag_sdk.kg import KG | |
| 3 | +from rag_sdk.Schema import Schema | |
| 4 | + | |
| 5 | +class TestKG(unittest.TestCase): | |
| 6 | + def test_kg_sources(self): | |
| 7 | + g = KG("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 | + | |
| 30 | + def test_kg_creation(self): | |
| 31 | + # Create schema | |
| 32 | + 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') | |
| 36 | + | |
| 37 | + g = KG("IMDB", schema=s) | |
| 38 | + g.add_source("./data/madoff.txt") | |
| 39 | + | |
| 40 | + g.create() | |
| 41 | + | |
| 42 | + answer, messages = g.ask("List a few actors") | |
| 43 | + print(f"answer: {answer}") | |
| 44 | + | |
| 45 | + answer, messages = g.ask("list additional actors", messages) | |
| 46 | + print(f"answer: {answer}") | |
| 47 | + | |
| 48 | +if __name__ == '__main__': | |
| 49 | + unittest.main() |
added tests/test_schema.py +195 −0
| @@ -0,0 +1,195 @@ | ||
| 1 | +import unittest | |
| 2 | +from falkordb import FalkorDB | |
| 3 | +from rag_sdk import Source | |
| 4 | +from rag_sdk.Schema import Schema | |
| 5 | +from rag_sdk.Schema.tools_gen import schema_to_tools | |
| 6 | +from rag_sdk.Schema.functions_gen import schema_to_functions | |
| 7 | + | |
| 8 | +class TestSchema(unittest.TestCase): | |
| 9 | + def test_schema(self): | |
| 10 | + s = Schema() | |
| 11 | + | |
| 12 | + f = s.add_entity('Fighter') | |
| 13 | + f.add_attribute('name', str, unique=True) | |
| 14 | + f.add_attribute('height', int) | |
| 15 | + | |
| 16 | + m = s.add_entity('Match') | |
| 17 | + m.add_attribute('date', int, unique=True) | |
| 18 | + m.add_attribute('id', int, unique=True) | |
| 19 | + m.add_attribute('rounds', int) | |
| 20 | + | |
| 21 | + s.add_relation('WON', f, m) | |
| 22 | + s.add_relation('LOST', f, m) | |
| 23 | + | |
| 24 | + s.validate() | |
| 25 | + | |
| 26 | + dump = s.to_JSON() | |
| 27 | + s = Schema.from_JSON(dump) | |
| 28 | + | |
| 29 | + def test_schema_tools(self): | |
| 30 | + s = Schema() | |
| 31 | + | |
| 32 | + f = s.add_entity('Fighter') | |
| 33 | + f.add_attribute('name', str, unique=True) | |
| 34 | + f.add_attribute('height', int, desc="Fighter's height in cm") | |
| 35 | + | |
| 36 | + m = s.add_entity('Match') | |
| 37 | + m.add_attribute('date', int, unique=True, desc="Match date in UNIX timestamp") | |
| 38 | + m.add_attribute('id', int, unique=True, desc="Fight number") | |
| 39 | + m.add_attribute('rounds', int, desc="Number of rounds, either 3 or 5") | |
| 40 | + | |
| 41 | + s.add_relation('WON', f, m) | |
| 42 | + s.add_relation('LOST', f, m) | |
| 43 | + | |
| 44 | + tools = schema_to_tools(s) | |
| 45 | + self.assertEqual(len(tools), 4) | |
| 46 | + | |
| 47 | + tool = {'type': 'function', | |
| 48 | + 'function': | |
| 49 | + {'name': 'Create_Fighter', | |
| 50 | + 'description': 'Create a new Fighter', | |
| 51 | + 'parameters': {'type': 'object', 'properties': | |
| 52 | + {'name': {'type': 'string', 'description': "Fighter's name"}, | |
| 53 | + 'height': {'type': 'number', 'description': "Fighter's height in cm"} | |
| 54 | + }, | |
| 55 | + 'required': ['name']} | |
| 56 | + } | |
| 57 | + } | |
| 58 | + self.assertIn(tool, tools) | |
| 59 | + | |
| 60 | + def test_schema_funs(self): | |
| 61 | + s = Schema() | |
| 62 | + | |
| 63 | + f = s.add_entity('Fighter') | |
| 64 | + f.add_attribute('name', str, unique=True) | |
| 65 | + f.add_attribute('height', int, desc="Fighter's height in cm") | |
| 66 | + | |
| 67 | + m = s.add_entity('Match') | |
| 68 | + m.add_attribute('date', int, unique=True, desc="Match date in UNIX timestamp") | |
| 69 | + m.add_attribute('id', int, unique=True, desc="Fight number") | |
| 70 | + m.add_attribute('rounds', int, desc="Number of rounds, either 3 or 5") | |
| 71 | + | |
| 72 | + s.add_relation('WON', f, m) | |
| 73 | + s.add_relation('LOST', f, m) | |
| 74 | + | |
| 75 | + funcs = schema_to_functions(s) | |
| 76 | + self.assertEqual(len(funcs), 4) | |
| 77 | + | |
| 78 | + func = ('Create_Fighter', 'def Create_Fighter(args):\n\targs = remove_none_values(args)\n\tquery = "MERGE (n:Fighter {name: $name}) SET n += $args"\n\tparams = {\'name\': args[\'name\'], \'args\': args}\n\tg.query(query, params)\n') | |
| 79 | + self.assertIn(func, funcs) | |
| 80 | + | |
| 81 | + func = ('Create_Match', 'def Create_Match(args):\n\targs = remove_none_values(args)\n\tquery = "MERGE (n:Match {date: $date, id: $id}) SET n += $args"\n\tparams = {\'date\': args[\'date\'], \'id\': args[\'id\'], \'args\': args}\n\tg.query(query, params)\n') | |
| 82 | + self.assertIn(func, funcs) | |
| 83 | + | |
| 84 | + func = ('WON', 'def WON(args):\n\targs = remove_none_values(args)\n\tq = "MERGE (s:Fighter {name: $name}) MERGE (d:Match {date: $date, id: $id}) MERGE (s)-[r:WON]->(d)"\n\tparams = {\'name\': args[\'name\'], \'date\': args[\'date\'], \'id\': args[\'id\']}\n\tg.query(q, params)\n') | |
| 85 | + self.assertIn(func, funcs) | |
| 86 | + | |
| 87 | + func = ('LOST', 'def LOST(args):\n\targs = remove_none_values(args)\n\tq = "MERGE (s:Fighter {name: $name}) MERGE (d:Match {date: $date, id: $id}) MERGE (s)-[r:LOST]->(d)"\n\tparams = {\'name\': args[\'name\'], \'date\': args[\'date\'], \'id\': args[\'id\']}\n\tg.query(q, params)\n') | |
| 88 | + self.assertIn(func, funcs) | |
| 89 | + | |
| 90 | + # Test creation of ontology graph from schema | |
| 91 | + def test_schema_to_graph(self): | |
| 92 | + s = Schema() | |
| 93 | + | |
| 94 | + f = s.add_entity('Fighter') | |
| 95 | + f.add_attribute('name', str, unique=True) | |
| 96 | + f.add_attribute('height', int, desc="Fighter's height in cm") | |
| 97 | + | |
| 98 | + m = s.add_entity('Match') | |
| 99 | + m.add_attribute('date', int, unique=True, desc="Match date in UNIX timestamp") | |
| 100 | + m.add_attribute('id', int, unique=True, desc="Fight number") | |
| 101 | + m.add_attribute('rounds', int, desc="Number of rounds, either 3 or 5") | |
| 102 | + | |
| 103 | + s.add_relation('WON', f, m) | |
| 104 | + s.add_relation('LOST', f, m) | |
| 105 | + | |
| 106 | + db = FalkorDB() | |
| 107 | + g = db.select_graph('UFC') | |
| 108 | + s.save_graph(g) | |
| 109 | + | |
| 110 | + # Assert topology graph | |
| 111 | + | |
| 112 | + # Expecting 2 nodes and 2 edges | |
| 113 | + res = g.query("MATCH (n) RETURN count(n)").result_set[0][0] | |
| 114 | + self.assertEqual(res, 2) | |
| 115 | + | |
| 116 | + res = g.query("MATCH ()-[e]->() RETURN count(e)").result_set[0][0] | |
| 117 | + self.assertEqual(res, 2) | |
| 118 | + | |
| 119 | + # Validate Fighter ndoe | |
| 120 | + n = g.query("MATCH (f:Fighter) RETURN f").result_set[0][0] | |
| 121 | + | |
| 122 | + self.assertEqual(n.labels[0], "Fighter") | |
| 123 | + | |
| 124 | + self.assertEqual(n.properties['name'][0], 'str') | |
| 125 | + self.assertEqual(n.properties['name'][1], "Fighter's name") | |
| 126 | + self.assertEqual(n.properties['name'][2], True) | |
| 127 | + self.assertEqual(n.properties['name'][3], False) | |
| 128 | + | |
| 129 | + self.assertEqual(n.properties['height'][0], 'int') | |
| 130 | + self.assertEqual(n.properties['height'][1], "Fighter's height in cm") | |
| 131 | + self.assertEqual(n.properties['height'][2], False) | |
| 132 | + self.assertEqual(n.properties['height'][3], False) | |
| 133 | + | |
| 134 | + # Validate Match ndoe | |
| 135 | + n = g.query("MATCH (m:Match) RETURN m").result_set[0][0] | |
| 136 | + | |
| 137 | + self.assertEqual(n.labels[0], "Match") | |
| 138 | + | |
| 139 | + self.assertEqual(n.properties['rounds'][0], 'int') | |
| 140 | + self.assertEqual(n.properties['rounds'][1], "Number of rounds, either 3 or 5") | |
| 141 | + self.assertEqual(n.properties['rounds'][2], False) | |
| 142 | + self.assertEqual(n.properties['rounds'][3], False) | |
| 143 | + | |
| 144 | + self.assertEqual(n.properties['date'][0], 'int') | |
| 145 | + self.assertEqual(n.properties['date'][1], "Match date in UNIX timestamp") | |
| 146 | + self.assertEqual(n.properties['date'][2], True) | |
| 147 | + self.assertEqual(n.properties['date'][3], False) | |
| 148 | + | |
| 149 | + self.assertEqual(n.properties['id'][0], 'int') | |
| 150 | + self.assertEqual(n.properties['id'][1], "Fight number") | |
| 151 | + self.assertEqual(n.properties['id'][2], True) | |
| 152 | + self.assertEqual(n.properties['id'][3], False) | |
| 153 | + | |
| 154 | + # Validate WON edge | |
| 155 | + res = g.query("MATCH (src)-[:WON]->(dest) RETURN src, dest").result_set[0] | |
| 156 | + src = res[0] | |
| 157 | + dest = res[1] | |
| 158 | + | |
| 159 | + self.assertEqual(src.labels[0], "Fighter") | |
| 160 | + self.assertEqual(dest.labels[0], "Match") | |
| 161 | + | |
| 162 | + # Validate LOST edge | |
| 163 | + res = g.query("MATCH (src)-[:LOST]->(dest) RETURN src, dest").result_set[0] | |
| 164 | + src = res[0] | |
| 165 | + dest = res[1] | |
| 166 | + | |
| 167 | + self.assertEqual(src.labels[0], "Fighter") | |
| 168 | + self.assertEqual(dest.labels[0], "Match") | |
| 169 | + | |
| 170 | + # Test creation of schema from ontology graph | |
| 171 | + def test_schema_from_graph(self): | |
| 172 | + # Create ontology graph from schema | |
| 173 | + s = Schema() | |
| 174 | + | |
| 175 | + f = s.add_entity('Fighter') | |
| 176 | + f.add_attribute('name', str, unique=True) | |
| 177 | + f.add_attribute('height', int, desc="Fighter's height in cm") | |
| 178 | + | |
| 179 | + m = s.add_entity('Match') | |
| 180 | + m.add_attribute('date', int, unique=True, desc="Match date in UNIX timestamp") | |
| 181 | + m.add_attribute('id', int, unique=True, desc="Fight number") | |
| 182 | + m.add_attribute('rounds', int, desc="Number of rounds, either 3 or 5") | |
| 183 | + | |
| 184 | + s.add_relation('WON', f, m) | |
| 185 | + s.add_relation('LOST', f, m) | |
| 186 | + | |
| 187 | + db = FalkorDB() | |
| 188 | + g = db.select_graph('UFC') | |
| 189 | + s.save_graph(g) | |
| 190 | + | |
| 191 | + # Recreate schema from ontology graph | |
| 192 | + self.assertEqual(s, Schema.from_graph(g)) | |
| 193 | + | |
| 194 | +if __name__ == '__main__': | |
| 195 | + unittest.main() |