| 1 | from graphrag_sdk.schema import Schema |
| 2 | from graphrag_sdk import KnowledgeGraph, Source |
| 3 | |
| 4 | import logging |
| 5 | logger = logging.getLogger("graphrag_sdk") |
| 6 | |
| 7 | # Configure the root logger |
| 8 | handler = logging.StreamHandler() |
| 9 | handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')) |
| 10 | logger.addHandler(handler) |
| 11 | logger.setLevel(logging.DEBUG) |
| 12 | |
| 13 | def main(): |
| 14 | # Auto detect schema based on a single URL |
| 15 | source = Source("https://www.rottentomatoes.com/m/matrix") |
| 16 | s = Schema.auto_detect([source]) |
| 17 | |
| 18 | # Print schema |
| 19 | print("Auto detected schema:") |
| 20 | print(s.to_JSON()) |
| 21 | |
| 22 | # Manually define schema |
| 23 | s = Schema() |
| 24 | |
| 25 | # Entities: |
| 26 | # 1. Actor |
| 27 | # 2. Director |
| 28 | # 3. Movie |
| 29 | |
| 30 | actor = s.add_entity('Actor') |
| 31 | actor.add_attribute('Name', str, unique=True, mandatory=True) |
| 32 | |
| 33 | director = s.add_entity('Director') |
| 34 | director.add_attribute('Name', str, unique=True, mandatory=True) |
| 35 | |
| 36 | movie = s.add_entity('Movie') |
| 37 | movie.add_attribute('Title', str, unique=True, mandatory=True) |
| 38 | movie.add_attribute('ReleaseYear', int) |
| 39 | movie.add_attribute('Rating', int) |
| 40 | |
| 41 | # Relations: |
| 42 | # 1. (Actor)-[ACTED]->(Movie) |
| 43 | # 2. (Director)-[DIRECTED]->(Movie) |
| 44 | |
| 45 | s.add_relation("ACTED", actor, movie) |
| 46 | s.add_relation("DIRECTED", director, movie) |
| 47 | |
| 48 | # Create Knowledge Graph |
| 49 | g = KnowledgeGraph("rottentomatoes", schema=s, model="gpt-3.5-turbo-0125") |
| 50 | |
| 51 | # Ingest |
| 52 | # Define sources from which knowledge will be created |
| 53 | sources = [ |
| 54 | Source("https://www.rottentomatoes.com/m/matrix"), |
| 55 | Source("https://www.rottentomatoes.com/m/matrix_reloaded"), |
| 56 | Source("https://www.rottentomatoes.com/m/the_matrix_resurrections")] |
| 57 | |
| 58 | g.process_sources(sources) |
| 59 | |
| 60 | # Query |
| 61 | msgs = [] |
| 62 | questions = ["List a few actors", |
| 63 | "Which actors played in all three movies?", |
| 64 | "Which movie has the heighest Rating?"] |
| 65 | |
| 66 | for q in questions: |
| 67 | print(f"Question: {q}") |
| 68 | ans, msgs = g.ask(q, history=msgs) |
| 69 | print(f"Answer: {ans}") |
| 70 | |
| 71 | if __name__ == "__main__": |
| 72 | main() |