Update app.py
Browse files
app.py
CHANGED
|
@@ -1,95 +1,96 @@
|
|
| 1 |
-
import json
|
| 2 |
-
|
| 3 |
-
from fastapi import FastAPI
|
| 4 |
-
import gradio as gr
|
| 5 |
-
|
| 6 |
-
# ----------------------------
|
| 7 |
-
# FastAPI App
|
| 8 |
-
# ----------------------------
|
| 9 |
-
app = FastAPI()
|
| 10 |
-
|
| 11 |
-
@app.get("/")
|
| 12 |
-
def home():
|
| 13 |
-
return {"status": "GraphRAG running"}
|
| 14 |
-
|
| 15 |
-
# ----------------------------
|
| 16 |
-
# Load Data
|
| 17 |
-
# ----------------------------
|
| 18 |
-
DATA_DIR = "data"
|
| 19 |
-
|
| 20 |
-
chunks = []
|
| 21 |
-
entities = []
|
| 22 |
-
metadata = []
|
| 23 |
-
|
| 24 |
-
try:
|
| 25 |
-
with open(os.path.join(DATA_DIR, "chunks.json"), "r", encoding="utf-8") as f:
|
| 26 |
-
chunks = json.load(f)
|
| 27 |
-
|
| 28 |
-
with open(os.path.join(DATA_DIR, "entities.json"), "r", encoding="utf-8") as f:
|
| 29 |
-
entities = json.load(f)
|
| 30 |
-
|
| 31 |
-
with open(os.path.join(DATA_DIR, "metadata.json"), "r", encoding="utf-8") as f:
|
| 32 |
-
metadata = json.load(f)
|
| 33 |
-
|
| 34 |
-
print(f"Loaded {len(chunks)} chunks")
|
| 35 |
-
|
| 36 |
-
except Exception as e:
|
| 37 |
-
print(f"Error loading data: {e}")
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
# ----------------------------
|
| 41 |
-
# Simple Search Function
|
| 42 |
-
# ----------------------------
|
| 43 |
-
def search_query(query):
|
| 44 |
-
if not query.strip():
|
| 45 |
-
return "Enter a query"
|
| 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 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os, sys, json, time
|
| 2 |
+
sys.path.insert(0, ".")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
+
# run ingest if needed
|
| 5 |
+
if not os.path.exists("data/chunks.json"):
|
| 6 |
+
exec(open("ingest.py").read())
|
| 7 |
|
| 8 |
+
import gradio as gr
|
| 9 |
+
from groq import Groq
|
| 10 |
+
import networkx as nx
|
| 11 |
+
from dotenv import load_dotenv
|
| 12 |
+
load_dotenv()
|
| 13 |
+
|
| 14 |
+
client = Groq(api_key=os.getenv("GROQ_API_KEY"))
|
| 15 |
+
|
| 16 |
+
def build_graph():
|
| 17 |
+
chunks = json.load(open("data/chunks.json", encoding="utf-8"))
|
| 18 |
+
entities = json.load(open("data/entities.json", encoding="utf-8"))
|
| 19 |
+
G = nx.Graph()
|
| 20 |
+
for c in chunks:
|
| 21 |
+
G.add_node(c["chunk_id"], type="chunk", text=c["text"], company=c["company"])
|
| 22 |
+
G.add_node(c["company"], type="company")
|
| 23 |
+
G.add_node(c["doc_name"], type="filing")
|
| 24 |
+
G.add_edge(c["company"], c["doc_name"], rel="FILED")
|
| 25 |
+
G.add_edge(c["doc_name"], c["chunk_id"], rel="CONTAINS")
|
| 26 |
+
for e in entities:
|
| 27 |
+
for ent in e["entities"]:
|
| 28 |
+
eid = f"{ent['label']}_{ent['text'][:50]}"
|
| 29 |
+
G.add_node(eid, type="entity", text=ent["text"])
|
| 30 |
+
G.add_edge(e["chunk_id"], eid, rel="MENTIONS")
|
| 31 |
+
return G
|
| 32 |
+
|
| 33 |
+
G = build_graph()
|
| 34 |
+
COMPANIES = ["apple","microsoft","amazon","google","tesla","3m","boeing","amd"]
|
| 35 |
+
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"}
|
| 36 |
+
|
| 37 |
+
def query_llm(question):
|
| 38 |
+
t0 = time.time()
|
| 39 |
+
r = client.chat.completions.create(
|
| 40 |
+
model="llama3-70b-8192",
|
| 41 |
+
messages=[{"role":"user","content":question}],
|
| 42 |
+
max_tokens=200
|
| 43 |
)
|
| 44 |
+
return r.choices[0].message.content, r.usage.total_tokens, round(time.time()-t0,2)
|
| 45 |
+
|
| 46 |
+
def query_graphrag(question):
|
| 47 |
+
t0 = time.time()
|
| 48 |
+
keywords = [w.lower().strip("?.,") for w in question.split() if w.lower() not in STOPWORDS and len(w)>2]
|
| 49 |
+
mentioned = [c for c in COMPANIES if c in question.lower()]
|
| 50 |
+
chunk_scores = {}
|
| 51 |
+
for node, data in G.nodes(data=True):
|
| 52 |
+
if data.get("type") != "chunk": continue
|
| 53 |
+
text = (data.get("text","") + " " + data.get("company","")).lower()
|
| 54 |
+
score = sum(1 for kw in keywords if kw in text)
|
| 55 |
+
if score > 0: chunk_scores[node] = score
|
| 56 |
+
top = sorted(chunk_scores, key=chunk_scores.get, reverse=True)[:2]
|
| 57 |
+
if mentioned:
|
| 58 |
+
top = [n for n in top if any(c in G.nodes[n].get("company","").lower() for c in mentioned)][:2]
|
| 59 |
+
if not top:
|
| 60 |
+
top = [n for n,d in G.nodes(data=True) if d.get("type")=="chunk"][:2]
|
| 61 |
+
context = "\n\n".join([G.nodes[n].get("text","") for n in top])
|
| 62 |
+
prompt = f"Context:\n{context}\n\nQuestion: {question}\nAnswer:"
|
| 63 |
+
r = client.chat.completions.create(
|
| 64 |
+
model="llama3-70b-8192",
|
| 65 |
+
messages=[{"role":"user","content":prompt}],
|
| 66 |
+
max_tokens=200
|
| 67 |
)
|
| 68 |
+
return r.choices[0].message.content, r.usage.total_tokens, round(time.time()-t0,2)
|
| 69 |
+
|
| 70 |
+
def compare(question):
|
| 71 |
+
if not question.strip():
|
| 72 |
+
return "β","β","β","β","β","β","β"
|
| 73 |
+
llm_ans, llm_tok, llm_lat = query_llm(question)
|
| 74 |
+
grag_ans, grag_tok, grag_lat = query_graphrag(question)
|
| 75 |
+
reduction = round((llm_tok - grag_tok) / llm_tok * 100, 1) if llm_tok > 0 else 0
|
| 76 |
+
return llm_ans, str(llm_tok), f"{llm_lat}s", grag_ans, str(grag_tok), f"{grag_lat}s", f"{reduction}% token reduction"
|
| 77 |
+
|
| 78 |
+
with gr.Blocks(title="GraphRAG vs LLM") as demo:
|
| 79 |
+
gr.Markdown("# GraphRAG vs LLM Only\nFinancial Q&A β TigerGraph Hackathon")
|
| 80 |
+
inp = gr.Textbox(label="Question", placeholder="What was Apple's revenue in FY2022?")
|
| 81 |
+
btn = gr.Button("Run", variant="primary")
|
| 82 |
+
with gr.Row():
|
| 83 |
+
with gr.Column():
|
| 84 |
+
gr.Markdown("### LLM Only")
|
| 85 |
+
llm_ans = gr.Textbox(label="Answer", lines=4)
|
| 86 |
+
llm_tok = gr.Textbox(label="Tokens")
|
| 87 |
+
llm_lat = gr.Textbox(label="Latency")
|
| 88 |
+
with gr.Column():
|
| 89 |
+
gr.Markdown("### GraphRAG")
|
| 90 |
+
grag_ans = gr.Textbox(label="Answer", lines=4)
|
| 91 |
+
grag_tok = gr.Textbox(label="Tokens")
|
| 92 |
+
grag_lat = gr.Textbox(label="Latency")
|
| 93 |
+
summary = gr.Textbox(label="Token Reduction")
|
| 94 |
+
btn.click(compare, inputs=[inp], outputs=[llm_ans,llm_tok,llm_lat,grag_ans,grag_tok,grag_lat,summary])
|
| 95 |
+
|
| 96 |
+
demo.launch()
|