Elffuss BraidHub

kikocis/GraphRAG-SDK public

main · 15.6 KiBRawPermalink
1{
2 "cells": [
3 {
4 "cell_type": "markdown",
5 "metadata": {},
6 "source": [
7 "# Using GraphRAG-SDK to Create a Knowledge Graph and RAG System from Unstructured Documents\n",
8 "\n",
9 "GraphRAG-SDK provides a powerful tool, enhanced by LLM technology, to build a Retrieval-Augmented Generation (RAG) system. This example demonstrates how to load UFC HTML files, automatically detect ontology based on 10% of the files, and create a Knowledge Graph (KG) to enable a question-answerable RAG system."
10 ]
11 },
12 {
13 "cell_type": "code",
14 "execution_count": null,
15 "metadata": {},
16 "outputs": [],
17 "source": [
18 "!pip install graphrag_sdk"
19 ]
20 },
21 {
22 "cell_type": "code",
23 "execution_count": 1,
24 "metadata": {},
25 "outputs": [
26 {
27 "data": {
28 "text/plain": [
29 "True"
30 ]
31 },
32 "execution_count": 1,
33 "metadata": {},
34 "output_type": "execute_result"
35 }
36 ],
37 "source": [
38 "import os\n",
39 "import json\n",
40 "import random\n",
41 "from dotenv import load_dotenv\n",
42 "from graphrag_sdk.source import Source\n",
43 "from graphrag_sdk import KnowledgeGraph, Ontology\n",
44 "from graphrag_sdk.models.openai import OpenAiGenerativeModel\n",
45 "from graphrag_sdk.model_config import KnowledgeGraphModelConfig\n",
46 "\n",
47 "# Load environment variables\n",
48 "load_dotenv()\n",
49 "\n",
50 "# Configuration\n",
51 "# OPENAI_API_KEY = \"sk-\"# OpenAI API key"
52 ]
53 },
54 {
55 "cell_type": "markdown",
56 "metadata": {},
57 "source": [
58 "### Import Source Data from Disk\n",
59 "\n",
60 "This example uses UFC HTML files as the source data. We will import these files as `Source` objects."
61 ]
62 },
63 {
64 "cell_type": "code",
65 "execution_count": 2,
66 "metadata": {},
67 "outputs": [],
68 "source": [
69 "# Data folder.\n",
70 "src_files = \"data/fight\"\n",
71 "sources = []\n",
72 "\n",
73 "# For each file in the source directory, create a new Source object.\n",
74 "for file in os.listdir(src_files):\n",
75 " sources.append(Source(os.path.join(src_files, file)))"
76 ]
77 },
78 {
79 "cell_type": "markdown",
80 "metadata": {},
81 "source": [
82 "### Ontology from the Sources\n",
83 "\n",
84 "Next, we will utilize an LLM to automatically extract ontology from a portion of the data (10%) and save it as a JSON file for manual review. We will also add `boundaries` to the ontology detection process to ensure the desired ontology is accurately identified."
85 ]
86 },
87 {
88 "cell_type": "code",
89 "execution_count": 3,
90 "metadata": {},
91 "outputs": [],
92 "source": [
93 "# Define the percentage of files that will be used to auto-create the ontology.\n",
94 "percent = 0.1 # This represents 10%. You can adjust this value (e.g., 0.2 for 20%).\n",
95 "\n",
96 "boundaries = \"\"\"\n",
97 " Extract only the most relevant information about UFC fighters, fights, and events.\n",
98 " Avoid creating entities for details that can be expressed as attributes.\n",
99 "\"\"\"\n",
100 "\n",
101 "# Define the model to be used for the ontology\n",
102 "model = OpenAiGenerativeModel(model_name=\"gpt-4o\")\n",
103 "\n",
104 "# Randomly select a percentage of files from sources.\n",
105 "sampled_sources = random.sample(sources, round(len(sources) * percent))\n",
106 "\n",
107 "ontology = Ontology.from_sources(\n",
108 " sources=sampled_sources,\n",
109 " boundaries=boundaries,\n",
110 " model=model,\n",
111 ")\n",
112 "\n",
113 "# Save the ontology to the disk as a json file.\n",
114 "with open(\"ontology.json\", \"w\", encoding=\"utf-8\") as file:\n",
115 " file.write(json.dumps(ontology.to_json(), indent=2))"
116 ]
117 },
118 {
119 "cell_type": "markdown",
120 "metadata": {},
121 "source": [
122 "Review the Ontology"
123 ]
124 },
125 {
126 "cell_type": "code",
127 "execution_count": 4,
128 "metadata": {},
129 "outputs": [
130 {
131 "name": "stdout",
132 "output_type": "stream",
133 "text": [
134 "{\n",
135 " \"entities\": [\n",
136 " {\n",
137 " \"label\": \"Event\",\n",
138 " \"attributes\": [\n",
139 " {\n",
140 " \"name\": \"title\",\n",
141 " \"type\": \"string\",\n",
142 " \"unique\": true,\n",
143 " \"required\": true\n",
144 " },\n",
145 " {\n",
146 " \"name\": \"date\",\n",
147 " \"type\": \"string\",\n",
148 " \"unique\": false,\n",
149 " \"required\": true\n",
150 " },\n",
151 " {\n",
152 " \"name\": \"location\",\n",
153 " \"type\": \"string\",\n",
154 " \"unique\": false,\n",
155 " \"required\": true\n",
156 " }\n",
157 " ],\n",
158 " \"description\": \"\"\n",
159 " },\n",
160 " {\n",
161 " \"label\": \"Fight\",\n",
162 " \"attributes\": [\n",
163 " {\n",
164 " \"name\": \"title\",\n",
165 " \"type\": \"string\",\n",
166 " \"unique\": true,\n",
167 " \"required\": true\n",
168 " },\n",
169 " {\n",
170 " \"name\": \"method\",\n",
171 " \"type\": \"string\",\n",
172 " \"unique\": false,\n",
173 " \"required\": true\n",
174 " },\n",
175 " {\n",
176 " \"name\": \"rounds\",\n",
177 " \"type\": \"number\",\n",
178 " \"unique\": false,\n",
179 " \"required\": true\n",
180 " },\n",
181 " {\n",
182 " \"name\": \"referee\",\n",
183 " \"type\": \"string\",\n",
184 " \"unique\": false,\n",
185 " \"required\": true\n",
186 " },\n",
187 " {\n",
188 " \"name\": \"result_details\",\n",
189 " \"type\": \"string\",\n",
190 " \"unique\": false,\n",
191 " \"required\": true\n",
192 " }\n",
193 " ],\n",
194 " \"description\": \"\"\n",
195 " },\n",
196 " {\n",
197 " \"label\": \"Fighter\",\n",
198 " \"attributes\": [\n",
199 " {\n",
200 " \"name\": \"name\",\n",
201 " \"type\": \"string\",\n",
202 " \"unique\": true,\n",
203 " \"required\": true\n",
204 " },\n",
205 " {\n",
206 " \"name\": \"nickname\",\n",
207 " \"type\": \"string\",\n",
208 " \"unique\": false,\n",
209 " \"required\": false\n",
210 " },\n",
211 " {\n",
212 " \"name\": \"outcome\",\n",
213 " \"type\": \"string\",\n",
214 " \"unique\": false,\n",
215 " \"required\": true\n",
216 " }\n",
217 " ],\n",
218 " \"description\": \"\"\n",
219 " },\n",
220 " {\n",
221 " \"label\": \"FightStatistics\",\n",
222 " \"attributes\": [\n",
223 " {\n",
224 " \"name\": \"fighter_name\",\n",
225 " \"type\": \"string\",\n",
226 " \"unique\": true,\n",
227 " \"required\": true\n",
228 " },\n",
229 " {\n",
230 " \"name\": \"knockdowns\",\n",
231 " \"type\": \"number\",\n",
232 " \"unique\": false,\n",
233 " \"required\": true\n",
234 " },\n",
235 " {\n",
236 " \"name\": \"significant_strikes\",\n",
237 " \"type\": \"number\",\n",
238 " \"unique\": false,\n",
239 " \"required\": true\n",
240 " },\n",
241 " {\n",
242 " \"name\": \"significant_strikes_attempted\",\n",
243 " \"type\": \"number\",\n",
244 " \"unique\": false,\n",
245 " \"required\": true\n",
246 " },\n",
247 " {\n",
248 " \"name\": \"significant_strikes_percentage\",\n",
249 " \"type\": \"number\",\n",
250 " \"unique\": false,\n",
251 " \"required\": true\n",
252 " },\n",
253 " {\n",
254 " \"name\": \"total_strikes\",\n",
255 " \"type\": \"number\",\n",
256 " \"unique\": false,\n",
257 " \"required\": true\n",
258 " },\n",
259 " {\n",
260 " \"name\": \"total_strikes_attempted\",\n",
261 " \"type\": \"number\",\n",
262 " \"unique\": false,\n",
263 " \"required\": true\n",
264 " },\n",
265 " {\n",
266 " \"name\": \"takedowns\",\n",
267 " \"type\": \"number\",\n",
268 " \"unique\": false,\n",
269 " \"required\": true\n",
270 " },\n",
271 " {\n",
272 " \"name\": \"takedowns_attempted\",\n",
273 " \"type\": \"number\",\n",
274 " \"unique\": false,\n",
275 " \"required\": true\n",
276 " },\n",
277 " {\n",
278 " \"name\": \"takedown_percentage\",\n",
279 " \"type\": \"number\",\n",
280 " \"unique\": false,\n",
281 " \"required\": true\n",
282 " },\n",
283 " {\n",
284 " \"name\": \"submissions_attempted\",\n",
285 " \"type\": \"number\",\n",
286 " \"unique\": false,\n",
287 " \"required\": true\n",
288 " },\n",
289 " {\n",
290 " \"name\": \"passes\",\n",
291 " \"type\": \"number\",\n",
292 " \"unique\": false,\n",
293 " \"required\": true\n",
294 " },\n",
295 " {\n",
296 " \"name\": \"reversals\",\n",
297 " \"type\": \"number\",\n",
298 " \"unique\": false,\n",
299 " \"required\": true\n",
300 " }\n",
301 " ],\n",
302 " \"description\": \"\"\n",
303 " }\n",
304 " ],\n",
305 " \"relations\": [\n",
306 " {\n",
307 " \"label\": \"PART_OF\",\n",
308 " \"source\": {\n",
309 " \"label\": \"Fight\"\n",
310 " },\n",
311 " \"target\": {\n",
312 " \"label\": \"Event\"\n",
313 " },\n",
314 " \"attributes\": []\n",
315 " },\n",
316 " {\n",
317 " \"label\": \"PARTICIPATED_IN\",\n",
318 " \"source\": {\n",
319 " \"label\": \"Fighter\"\n",
320 " },\n",
321 " \"target\": {\n",
322 " \"label\": \"Fight\"\n",
323 " },\n",
324 " \"attributes\": []\n",
325 " },\n",
326 " {\n",
327 " \"label\": \"RELATED_STATS\",\n",
328 " \"source\": {\n",
329 " \"label\": \"FightStatistics\"\n",
330 " },\n",
331 " \"target\": {\n",
332 " \"label\": \"Fighter\"\n",
333 " },\n",
334 " \"attributes\": []\n",
335 " },\n",
336 " {\n",
337 " \"label\": \"HAS_STATS\",\n",
338 " \"source\": {\n",
339 " \"label\": \"Fight\"\n",
340 " },\n",
341 " \"target\": {\n",
342 " \"label\": \"FightStatistics\"\n",
343 " },\n",
344 " \"attributes\": []\n",
345 " }\n",
346 " ]\n",
347 "}\n"
348 ]
349 }
350 ],
351 "source": [
352 "print(json.dumps(ontology.to_json(), indent=4))"
353 ]
354 },
355 {
356 "cell_type": "markdown",
357 "metadata": {},
358 "source": [
359 "### KG from Sources and Ontology\n",
360 "\n",
361 "After reviewing the ontology, we will load it and use it to create a Knowledge Graph (KG) from the sources."
362 ]
363 },
364 {
365 "cell_type": "code",
366 "execution_count": 5,
367 "metadata": {},
368 "outputs": [],
369 "source": [
370 "# After approving the ontology, load it from disk.\n",
371 "ontology_file = \"ontology.json\"\n",
372 "with open(ontology_file, \"r\", encoding=\"utf-8\") as file:\n",
373 " ontology = Ontology.from_json(json.loads(file.read()))\n",
374 "\n",
375 "kg = KnowledgeGraph(\n",
376 " name=\"ufc\",\n",
377 " model_config=KnowledgeGraphModelConfig.with_model(model),\n",
378 " ontology=ontology,\n",
379 ")\n",
380 "kg.process_sources(sources)"
381 ]
382 },
383 {
384 "cell_type": "markdown",
385 "metadata": {},
386 "source": [
387 "### Graph RAG\n",
388 "\n",
389 "At this point, we have a Knowledge Graph based on our data, and we can use it in our GraphRAG system. We can utilize the `ask` method for single questions or the `chat_session` method for engaging in conversations."
390 ]
391 },
392 {
393 "cell_type": "code",
394 "execution_count": 6,
395 "metadata": {},
396 "outputs": [
397 {
398 "name": "stdout",
399 "output_type": "stream",
400 "text": [
401 "('The last five fights were:\\n\\n1. **Julian Marquez vs Marc-Andre Barriault** on **2024-05-11** with **3 rounds**.\\n2. **Julian Marquez vs Marc-Andre Barriault** on **2024-05-11** with **3 rounds**.\\n3. **Julian Marquez vs Marc-Andre Barriault** on **2024-05-11** with **3 rounds**.\\n4. **Julian Marquez vs Marc-Andre Barriault** on **2024-05-11** with **3 rounds**.\\n5. **Julian Marquez vs Marc-Andre Barriault** on **2024-05-11** with **3 rounds**.', <graphrag_sdk.models.openai.OpenAiChatSession object at 0x75b36cd9f710>)\n",
402 "Salsa Boy is the nickname of Waldo Cortes-Acosta.\n",
403 "Salsa Boy, whose real name is Waldo Cortes-Acosta, participated in a fight on May 11, 2024, during the UFC Fight Night: Lewis vs. Nascimento event. He fought in the Heavyweight class and won the match by unanimous decision.\n"
404 ]
405 }
406 ],
407 "source": [
408 "# Single question.\n",
409 "response = kg.ask(\"What were the last five fights? When were they? How many rounds did they have?\")\n",
410 "print(response)\n",
411 "# Conversation.\n",
412 "chat = kg.chat_session()\n",
413 "response = chat.send_message(\"Who is Salsa Boy?\")\n",
414 "print(response)\n",
415 "response = chat.send_message(\"Tell me about one of his fights?\")\n",
416 "print(response)"
417 ]
418 }
419 ],
420 "metadata": {
421 "kernelspec": {
422 "display_name": ".venv",
423 "language": "python",
424 "name": "python3"
425 },
426 "language_info": {
427 "codemirror_mode": {
428 "name": "ipython",
429 "version": 3
430 },
431 "file_extension": ".py",
432 "mimetype": "text/x-python",
433 "name": "python",
434 "nbconvert_exporter": "python",
435 "pygments_lexer": "ipython3",
436 "version": "3.11.9"
437 }
438 },
439 "nbformat": 4,
440 "nbformat_minor": 2
441}