File size: 5,586 Bytes
78499a5
 
 
f69c5f9
 
78499a5
f69c5f9
78499a5
f69c5f9
 
78499a5
 
 
f69c5f9
 
78499a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f69c5f9
 
78499a5
f69c5f9
78499a5
 
 
 
 
 
 
 
 
 
 
 
f69c5f9
 
78499a5
f69c5f9
 
78499a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f69c5f9
 
78499a5
f69c5f9
 
78499a5
f69c5f9
2bcb840
f69c5f9
78499a5
 
 
 
 
 
 
 
 
f69c5f9
 
78499a5
 
 
 
 
 
 
f69c5f9
78499a5
f69c5f9
78499a5
 
 
 
 
 
 
 
 
f69c5f9
78499a5
 
 
 
 
 
 
 
 
 
f69c5f9
78499a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f69c5f9
 
78499a5
f69c5f9
2bcb840
f69c5f9
78499a5
 
 
 
 
 
 
 
 
f69c5f9
 
78499a5
 
f69c5f9
 
 
78499a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f69c5f9
78499a5
 
 
 
 
 
 
 
 
f69c5f9
 
 
78499a5
f69c5f9
 
78499a5
f69c5f9
 
78499a5
f69c5f9
 
78499a5
f69c5f9
78499a5
 
 
 
 
 
 
 
 
 
 
 
 
 
f69c5f9
567197e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
import os
import json
import time
import gradio as gr
import networkx as nx
from groq import Groq
from dotenv import load_dotenv

load_dotenv()

# -----------------------------
# API
# -----------------------------
client = Groq(api_key=os.getenv("GROQ_API_KEY"))

# -----------------------------
# Fallback data (avoid startup crash)
# -----------------------------
if not os.path.exists("data"):
    os.makedirs("data", exist_ok=True)

if not os.path.exists("data/chunks.json"):
    dummy_chunks = [
        {
            "chunk_id": "demo_1",
            "company": "apple",
            "doc_name": "sample_doc",
            "period": "2024",
            "text": "Apple reported strong revenue growth in FY2024.",
            "question": "",
            "answer": "",
            "source": "demo"
        }
    ]

    with open("data/chunks.json", "w", encoding="utf-8") as f:
        json.dump(dummy_chunks, f)

if not os.path.exists("data/entities.json"):
    with open("data/entities.json", "w", encoding="utf-8") as f:
        json.dump([], f)

# -----------------------------
# Load data
# -----------------------------
with open("data/chunks.json", encoding="utf-8") as f:
    chunks = json.load(f)

with open("data/entities.json", encoding="utf-8") as f:
    entities = json.load(f)

# -----------------------------
# Build graph
# -----------------------------
def build_graph():
    G = nx.Graph()

    for c in chunks:
        company = c.get("company", "unknown")
        doc = c.get("doc_name", "unknown_doc")
        cid = c.get("chunk_id", "unknown_chunk")
        text = c.get("text", "")

        G.add_node(cid, type="chunk", text=text, company=company)
        G.add_node(company, type="company")
        G.add_node(doc, type="filing")

        G.add_edge(company, doc, rel="FILED")
        G.add_edge(doc, cid, rel="CONTAINS")

    return G


G = build_graph()

COMPANIES = [
    "apple", "microsoft", "amazon",
    "google", "tesla", "3m",
    "boeing", "amd"
]

STOPWORDS = {
    "what", "was", "the", "in",
    "of", "a", "an", "is", "are",
    "how", "did", "does", "we",
    "if", "that", "you", "as",
    "based", "on", "which", "has",
    "for", "by", "per"
}

# -----------------------------
# LLM Query
# -----------------------------
def query_llm(question):
    t0 = time.time()

    r = client.chat.completions.create(
        model="llama3-70b-8192",
        messages=[{"role": "user", "content": question}],
        max_tokens=200
    )

    return (
        r.choices[0].message.content,
        r.usage.total_tokens,
        round(time.time() - t0, 2)
    )

# -----------------------------
# GraphRAG Query
# -----------------------------
def query_graphrag(question):
    t0 = time.time()

    keywords = [
        w.lower().strip("?.,")
        for w in question.split()
        if w.lower() not in STOPWORDS and len(w) > 2
    ]

    chunk_scores = {}

    for node, data in G.nodes(data=True):
        if data.get("type") != "chunk":
            continue

        text = (
            data.get("text", "") +
            " " +
            data.get("company", "")
        ).lower()

        score = sum(1 for kw in keywords if kw in text)

        if score > 0:
            chunk_scores[node] = score

    top = sorted(
        chunk_scores,
        key=chunk_scores.get,
        reverse=True
    )[:2]

    if not top:
        top = [
            n for n, d in G.nodes(data=True)
            if d.get("type") == "chunk"
        ][:2]

    context = "\n\n".join([
        G.nodes[n].get("text", "")
        for n in top
    ])

    prompt = f"""
Context:
{context}

Question:
{question}

Answer:
"""

    r = client.chat.completions.create(
        model="llama3-70b-8192",
        messages=[{"role": "user", "content": prompt}],
        max_tokens=200
    )

    return (
        r.choices[0].message.content,
        r.usage.total_tokens,
        round(time.time() - t0, 2)
    )

# -----------------------------
# Compare
# -----------------------------
def compare(question):
    if not question.strip():
        return "-", "-", "-", "-", "-", "-", "-"

    llm_ans, llm_tok, llm_lat = query_llm(question)
    grag_ans, grag_tok, grag_lat = query_graphrag(question)

    reduction = (
        round((llm_tok - grag_tok) / llm_tok * 100, 1)
        if llm_tok > 0 else 0
    )

    return (
        llm_ans,
        str(llm_tok),
        f"{llm_lat}s",
        grag_ans,
        str(grag_tok),
        f"{grag_lat}s",
        f"{reduction}% token reduction"
    )

# -----------------------------
# UI
# -----------------------------
with gr.Blocks(title="GraphRAG vs LLM") as demo:
    gr.Markdown("# GraphRAG vs LLM")

    inp = gr.Textbox(
        label="Question",
        placeholder="What was Apple's revenue?"
    )

    btn = gr.Button("Run")

    with gr.Row():
        with gr.Column():
            gr.Markdown("### LLM Only")
            llm_ans = gr.Textbox(lines=5)
            llm_tok = gr.Textbox(label="Tokens")
            llm_lat = gr.Textbox(label="Latency")

        with gr.Column():
            gr.Markdown("### GraphRAG")
            grag_ans = gr.Textbox(lines=5)
            grag_tok = gr.Textbox(label="Tokens")
            grag_lat = gr.Textbox(label="Latency")

    summary = gr.Textbox(label="Token Reduction")

    btn.click(
        compare,
        inputs=inp,
        outputs=[
            llm_ans,
            llm_tok,
            llm_lat,
            grag_ans,
            grag_tok,
            grag_lat,
            summary
        ]
    )

demo.launch(server_name="0.0.0.0", server_port=7860, share=True)