Elffuss BraidHub

kikocis/GraphRAG-SDK public

add examples
Changesetb98ebd0cb2bd4a642a390742894d24c2049f28a88eec54b2e5167caaae4afdcb
AuthorRoi Lipman <roilipman@gmail.com> · 2024-06-10 11:17 +03:00
CommitterRoi Lipman <roilipman@gmail.com> · 2024-06-10 11:22 +03:00
Parentsc1b0da01842e

Browse the files at this changeset

6 files changed

modified .wordlist.txt +1 −0
@@ -3,3 +3,4 @@
33 GraphRAG
44 OpenAI
55 FalkorDB
6+github
deleted examples/github.py +0 −103
@@ -1,103 +0,0 @@
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- # Manually define schema
15- s = Schema()
16-
17- # Entities:
18- # 1. File
19- # 2. Directory
20- # 3. Commit
21- # 4. Branch
22- # 5. Repository
23- # 6. Organization
24- # 7. User
25-
26- file = s.add_entity('File')
27- file.add_attribute('Name', str, unique=True, mandatory=True)
28- file.add_attribute('Extension', str, unique=True, mandatory=True)
29-
30- dir = s.add_entity('Directory')
31- dir.add_attribute('Name', str, unique=True, mandatory=True)
32-
33- commit = s.add_entity('Commit')
34- commit.add_attribute('Message', str)
35- commit.add_attribute('Date', int, desc="Commit date as UNIX timestamp")
36- commit.add_attribute('Hash', str, unique=True, mandatory=True)
37-
38- branch = s.add_entity('Branch')
39- branch.add_attribute('Name', str, unique=True, mandatory=True)
40-
41- repo = s.add_entity('Repository')
42- repo.add_attribute('Name', str, unique=True, mandatory=True)
43- repo.add_attribute('Description', str)
44- repo.add_attribute('Issues', int, desc="Number of issues")
45-
46- organization = s.add_entity('Organization')
47- organization.add_attribute('Name', str, unique=True, mandatory=True)
48-
49- user = s.add_entity('User')
50- user.add_attribute('Name', str, unique=True, mandatory=True)
51- user.add_attribute('Location', str, desc="Where the user is from")
52-
53- # Relations:
54- # 1. (Repository)-[CONTAINS]->(File)
55- # 2. (Repository)-[CONTAINS]->(Directory)
56- # 3. (Repository)-[CONTAINS]->(Commit)
57- # 4. (Repository)-[CONTAINS]->(bracnh)
58- # 5. (Organization)-[OWNS]->(Repository)
59- # 6. (User)-[STAR]->(Repository)
60- # 7. (User)-[PART_OF]->(Organization)
61-
62- s.add_relation("CONTAINS", repo, file)
63- s.add_relation("CONTAINS", repo, dir)
64- s.add_relation("CONTAINS", repo, commit)
65- s.add_relation("CONTAINS", repo, branch)
66- s.add_relation("OWNS", organization, repo)
67- s.add_relation("STAR", user, repo)
68- s.add_relation("PART_OF", user, organization)
69-
70- # Print schema
71- # print(s.to_JSON())
72-
73- # Create Knowledge Graph
74- g = KnowledgeGraph("Github", schema=s, model="gpt-3.5-turbo-0125")
75-
76- # Ingest
77- # Define sources from which knowledge will be extracted
78- sources = [
79- Source("https://github.com/FalkorDB/FalkorDB",
80- instruction="Extract organization, repository, users, files and directories. make sure to form connections"),
81- Source("https://github.com/FalkorDB/FalkorDB/stargazers",
82- instruction="Extract users who've stared this repo, make sure to create each user and connect it via an edge to the repo node."),
83- Source("https://github.com/FalkorDB/FalkorDB/branches", instruction="Extract branches and connect them to the repository"),
84- Source("https://github.com/FalkorDB/FalkorDB/commits", instruction="Extract commits and connect them to the repository")]
85-
86- g.process_sources(sources)
87-
88- # Query the repo
89- msgs = []
90- questions = ["List a few stargazers",
91- "List a few commits",
92- "How many Markdown files are there in the FalkorDB repository?",
93- "Which organization owns the FalkorDB repository?",
94- "Any of the Stargazers are also associated with the repo's organization?",
95- "Does the FalkorDB repository has a 'main' branch?"]
96-
97- for q in questions:
98- print(f"Question: {q}")
99- ans, msgs = g.ask(q, history=msgs)
100- print(f"Answer: {ans}")
101-
102-if __name__ == "__main__":
103- main()
added examples/github/README.md +77 −0
@@ -0,0 +1,77 @@
1+# Construct a knowledge graph from a GitHub repository
2+
3+The main entities and relations extracted:
4+
5+## Entities
6+
7+- File
8+- Directory
9+- Commit
10+- Branch
11+- Repository
12+- Organization
13+- User
14+
15+## Relations
16+
17+- (Repository)-[CONTAINS]->(File)
18+- (Repository)-[CONTAINS]->(Directory)
19+- (Repository)-[CONTAINS]->(Commit)
20+- (Repository)-[CONTAINS]->(branch)
21+- (Organization)-[OWNS]->(Repository)
22+- (User)-[STAR]->(Repository)
23+- (User)-[PART_OF]->(Organization)
24+
25+## Run
26+
27+Run FalkorDB:
28+```sh
29+docker run -p 6379:6379 -p 3000:3000 -it --rm -v ./data:/data falkordb/falkordb:edge
30+```
31+
32+Construct knowledge graph from github URL
33+```sh
34+python examples/github/github.py -r https://github.com/falkorDB/falkordb
35+```
36+
37+## Output
38+
39+```sh
40+python examples/github/github.py
41+2024-06-10 10:05:36,912 - graphrag_sdk.kg - DEBUG - Run in progress
42+...
43+Question: List a few stargazers
44+
45+2024-06-10 10:07:55,729 - graphrag_sdk.query_graph - DEBUG - Model suggested query: MATCH (u:User)-[:STAR]->(r:Repository) RETURN u.Name, r.Name LIMIT 5
46+
47+Answer: Here are a few stargazers:
48+1. User: dekelev - Repository: FalkorDB
49+2. User: qdrddr - Repository: FalkorDB
50+3. User: MikeLP - Repository: FalkorDB
51+4. User: johnpccd - Repository: FalkorDB
52+5. User: ohdearquant - Repository: FalkorDB
53+
54+Question: Does the FalkorDB repository has a 'main' branch?
55+
56+2024-06-10 10:08:08,774 - graphrag_sdk.query_graph - DEBUG - Model suggested query: MATCH (:Repository {Name: 'FalkorDB'})-[:CONTAINS]->(b:Branch {Name: 'main'}) RETURN b
57+
58+Answer: No, the FalkorDB repository does not have a 'main' branch in the knowledge graph.
59+
60+How can I help you with?
61+Summerise stargazers locations
62+
63+2024-06-10 10:27:51,036 - graphrag_sdk.query_graph - DEBUG - Model suggested query: MATCH (u:User)-[:STAR]->(r:Repository) RETURN u.Location, COUNT(u) as StargazersCount
64+
65+Answer: Here is a summary of stargazers locations along with the count of stargazers from each location:
66+- San Francisco, CA USA: 1 stargazer
67+- Sydney, Australia: 1 stargazer
68+- Houston, TX: 1 stargazer
69+- Mountain: 1 stargazer
70+- Bengaluru, India: 1 stargazer
71+- New York: 1 stargazer
72+- Bangkok, Thailand: 1 stargazer
73+- Russia: 1 stargazer
74+- Israel: 1 stargazer
75+- Unknown Location: 37 stargazers
76+- Mempool: 1 stargazer
77+```
added examples/github/github.py +120 −0
@@ -0,0 +1,120 @@
1+import argparse
2+from graphrag_sdk.schema import Schema
3+from graphrag_sdk import KnowledgeGraph, Source
4+
5+import logging
6+logger = logging.getLogger("graphrag_sdk")
7+
8+# Configure the root logger
9+handler = logging.StreamHandler()
10+handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
11+logger.addHandler(handler)
12+logger.setLevel(logging.DEBUG)
13+
14+def main():
15+ # Create the parser
16+ parser = argparse.ArgumentParser(description="Github Knowledge Graph")
17+
18+ # Add arguments
19+ parser.add_argument('-r', '--repository', type=str, help='Repository URL', default='https://github.com/FalkorDB/FalkorDB')
20+
21+ # Parse the arguments
22+ args = parser.parse_args()
23+ repo_url = args.repository
24+
25+ # Manually define schema
26+ s = Schema()
27+
28+ # Entities:
29+ # 1. File
30+ # 2. Directory
31+ # 3. Commit
32+ # 4. Branch
33+ # 5. Repository
34+ # 6. Organization
35+ # 7. User
36+
37+ file = s.add_entity('File')
38+ file.add_attribute('Name', str, unique=True, mandatory=True)
39+ file.add_attribute('Extension', str, unique=True, mandatory=True)
40+
41+ dir = s.add_entity('Directory')
42+ dir.add_attribute('Name', str, unique=True, mandatory=True)
43+
44+ commit = s.add_entity('Commit')
45+ commit.add_attribute('Message', str)
46+ commit.add_attribute('Date', int, desc="Commit date as UNIX timestamp")
47+ commit.add_attribute('Hash', str, unique=True, mandatory=True)
48+
49+ branch = s.add_entity('Branch')
50+ branch.add_attribute('Name', str, unique=True, mandatory=True)
51+
52+ repo = s.add_entity('Repository')
53+ repo.add_attribute('Name', str, unique=True, mandatory=True)
54+ repo.add_attribute('Description', str)
55+ repo.add_attribute('Issues', int, desc="Number of issues")
56+
57+ organization = s.add_entity('Organization')
58+ organization.add_attribute('Name', str, unique=True, mandatory=True)
59+
60+ user = s.add_entity('User')
61+ user.add_attribute('Name', str, unique=True, mandatory=True)
62+ user.add_attribute('Location', str, desc="Where the user is from")
63+
64+ # Relations:
65+ # 1. (Repository)-[CONTAINS]->(File)
66+ # 2. (Repository)-[CONTAINS]->(Directory)
67+ # 3. (Repository)-[CONTAINS]->(Commit)
68+ # 4. (Repository)-[CONTAINS]->(branch)
69+ # 5. (Organization)-[OWNS]->(Repository)
70+ # 6. (User)-[STAR]->(Repository)
71+ # 7. (User)-[PART_OF]->(Organization)
72+
73+ s.add_relation("CONTAINS", repo, file)
74+ s.add_relation("CONTAINS", repo, dir)
75+ s.add_relation("CONTAINS", repo, commit)
76+ s.add_relation("CONTAINS", repo, branch)
77+ s.add_relation("OWNS", organization, repo)
78+ s.add_relation("STAR", user, repo)
79+ s.add_relation("PART_OF", user, organization)
80+
81+ # Print schema
82+ # print(s.to_JSON())
83+
84+ # Create Knowledge Graph
85+ g = KnowledgeGraph("Github", schema=s, model="gpt-3.5-turbo-0125")
86+
87+ # Ingest
88+ # Define sources from which knowledge will be extracted
89+ sources = [
90+ Source(repo_url,
91+ instruction="Extract organization, repository, users, files and directories. make sure to form connections"),
92+ Source(f"{repo_url}/stargazers",
93+ instruction="Extract users who've stared this repo, make sure to create each user and connect it via an edge to the repo node."),
94+ Source(f"{repo_url}/branches", instruction="Extract branches and connect them to the repository"),
95+ Source(f"{repo_url}/commits", instruction="Extract commits and connect them to the repository")]
96+
97+ g.process_sources(sources)
98+
99+ # Query the repo
100+ msgs = []
101+ questions = ["List a few stargazers",
102+ "List a few commits",
103+ "How many Markdown files are there in the FalkorDB repository?",
104+ "Which organization owns the FalkorDB repository?",
105+ "Any of the Stargazers are also associated with the repo's organization?",
106+ "Does the FalkorDB repository has a 'main' branch?"]
107+
108+ print("List of predefined questions:")
109+ for q in questions:
110+ print(f"Question: {q}\n")
111+ ans, msgs = g.ask(q, history=msgs)
112+ print(f"\nAnswer: {ans}")
113+
114+ while True:
115+ q = input("How can I help you with?\n")
116+ ans, msgs = g.ask(q, history=msgs)
117+ print(f"Answer: {ans}")
118+
119+if __name__ == "__main__":
120+ main()
added examples/rottentomatoes/README.md +89 −0
@@ -0,0 +1,89 @@
1+# Auto detect schema
2+
3+This demo show cases the auto detection feature of the Schema object
4+Once a schema is detected we'll recommend the user to review it and make any necessary adjustments.
5+
6+## Schema
7+
8+A schema defines both entities and relations
9+
10+### Entity
11+
12+An entity contains both a label and a set of attributes
13+
14+### Relation
15+
16+Relations are defined by a relationship-type, source and destination nodes triplet e.g. `(Person)-[LIVES]->(City)`
17+
18+## Run
19+
20+Run FalkorDB:
21+```sh
22+docker run -p 6379:6379 -p 3000:3000 -it --rm -v ./data:/data falkordb/falkordb:edge
23+```
24+
25+Detect schema, adjust and create knowledge graph
26+```sh
27+python examples/rottentomatoes/rottentomatoes.py
28+```
29+
30+## Output
31+
32+```sh
33+python examples/rottentomatoes/rottentomatoes.py
34+...
35+Auto detected schema:
36+{
37+ "entities": [
38+ {
39+ "name": "Movies",
40+ "attributes": [
41+ {
42+ "name": "Rating",
43+ "type": "str",
44+ "desc": "Movies's Rating",
45+ "unique": false,
46+ "mandatory": false
47+ },
48+ {
49+ "name": "Duration",
50+ "type": "str",
51+ "desc": "Movies's Duration",
52+ "unique": true,
53+ "mandatory": true
54+ },
55+ {
56+ "name": "Genre",
57+ "type": "str",
58+ "desc": "Movies's Genre",
59+ "unique": false,
60+ "mandatory": false
61+ },
62+ {
63+ "name": "Title",
64+ "type": "str",
65+ "desc": "Movies's Title",
66+ "unique": false,
67+ "mandatory": false
68+ }
69+ ]
70+ },
71+ ...
72+ "relations": []
73+}
74+...
75+2024-06-10 11:05:35,997 - graphrag_sdk.kg - DEBUG - Done processing https://www.rottentomatoes.com/m/the_matrix_resurrections
76+2024-06-10 11:05:35,997 - graphrag_sdk.kg - DEBUG - Done
77+
78+Question: List a few actors
79+2024-06-10 11:05:36,890 - graphrag_sdk.query_graph - DEBUG - Model suggested query: MATCH (a:Actor) RETURN a.Name LIMIT 5
80+Answer: Here are a few actors:
81+1. Keanu Reeves
82+2. Laurence Fishburne
83+3. Carrie-Anne Moss
84+4. Hugo Weaving
85+5. Yahya Abdul-Mateen II
86+Question: Which movie has the heighest Rating?
87+2024-06-10 11:05:40,828 - graphrag_sdk.query_graph - DEBUG - Model suggested query: MATCH (m:Movie) RETURN m.Title, m.Rating ORDER BY m.Rating DESC LIMIT 1
88+Answer: The movie "The Matrix" has the highest rating with a rating of 83.
89+```
added examples/rottentomatoes/rottentomatoes.py +72 −0
@@ -0,0 +1,72 @@
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()