Elffuss BraidHub

kikocis/GraphRAG-SDK public

7d7ed3464b93 · 5.0 KiBRawPermalink
1import json
2from openai import OpenAI
3
4import logging
5logger = logging.getLogger(__name__)
6
7# Equipet assistant with tools:
8tools = [
9 {
10 "type": "function",
11 "function": {
12 "name": "run_cypher_query",
13 "description": "Run a Cypher query against the graph",
14 "parameters": {
15 "type": "object",
16 "properties": {
17 "query": {
18 "type": "string",
19 "description": "query to execute",
20 },
21 },
22 "required": ["query"],
23 },
24 },
25 }
26]
27
28def run_cypher_query(g, q):
29 return g.query(q).result_set
30
31# convert a schema into a string representation
32def _graph_schema_to_prompt(s) -> str:
33 # Build a string description of graph schema
34 desc = "The knowladge graph schema is as follows:\n"
35
36 #--------------------------------------------------------------------------
37 # Describe labels
38 #--------------------------------------------------------------------------
39
40 # list labels
41 desc = desc + "The graph contains the following node labels:\n";
42 for e in s.entities:
43 desc += e.name + "\n"
44
45 # specify attributes associated with each entity
46 for e in s.entities:
47 lbl_name = e.name
48 attributes = e.attributes
49 attr_count = len(attributes)
50
51 if (attr_count == 0):
52 desc += f"The {lbl_name} label has no attributes\n"
53 else:
54 desc += f"The {lbl_name} label is associated with the following attribute(s):\n"
55 for attr in attributes:
56 attr_name = attr.name
57 attr_type = attr.type.__name__
58 desc += f"{attr_name} which is of type {attr_type}\n"
59
60 desc += "The graph contains the following relationship types:\n"
61
62 #--------------------------------------------------------------------------
63 # Describe relationships
64 #--------------------------------------------------------------------------
65
66 # list relations
67 for rel in s.relations:
68 src = rel.src.name
69 relationship_type = rel.name
70 dest = rel.dest.name
71 desc += f"{relationship_type}\n"
72 desc += f"The {relationship_type} relationship connects the following labels:\n"
73 desc += f"{src} is connected via {relationship_type} to {dest}\n"
74
75 desc += "This is the end of the knowladge graph schema description.\n"
76
77 return desc;
78
79def run_conversation(g, question, messages, model) -> str:
80 client = OpenAI()
81
82 # Step 1: send the conversation and available functions to the model
83 messages.append({"role": "user", "content": question})
84
85 response = client.chat.completions.create(
86 model=model,
87 messages=messages,
88 tools=tools,
89 tool_choice="auto", # auto is default, but we'll be explicit
90 )
91
92 response_message = response.choices[0].message
93 tool_calls = response_message.tool_calls
94
95 # Step 2: check if the model wanted to call a function
96 if tool_calls:
97 # Step 3: call the function
98 # Note: the JSON response may not always be valid; be sure to handle errors
99 available_functions = {
100 "run_cypher_query": run_cypher_query,
101 } # only one function in this example, but you can have multiple
102 messages.append(response_message) # extend conversation with assistant's reply
103 # Step 4: send the info for each function call and function response to the model
104 for tool_call in tool_calls:
105 function_name = tool_call.function.name
106 function_to_call = available_functions[function_name]
107 function_args = json.loads(tool_call.function.arguments)
108 q = function_args.get("query")
109 logger.debug(f"Model suggested query: {q}")
110
111 function_response = function_to_call(g, q)
112 messages.append(
113 {
114 "tool_call_id": tool_call.id,
115 "role": "tool",
116 "name": function_name,
117 "content": str(function_response),
118 }
119 ) # extend conversation with function response
120 second_response = client.chat.completions.create(
121 model=model,
122 messages=messages,
123 ) # get a new response from the model where it can see the function response
124
125 return second_response.choices[0].message.content
126
127 return None
128
129def query(kg, question:str, messages:list, model="gpt-4-1106-preview") -> str:
130 # Build system message
131 if len(messages) == 0:
132 # graph schema
133 schema_desc = _graph_schema_to_prompt(kg.schema)
134 messages.append(
135 {"role": "system", "content": f"""You are a graph database expert fluent in the Cypher query language
136 with access to the following knowledge graph: {schema_desc}"""})
137
138 # Get an answer
139 answer = run_conversation(kg.graph, question, messages, model)
140
141 # Append answer to conversation
142 messages.append({"role": "assistant", "content": answer})
143
144 return answer