-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
211 lines (163 loc) · 5.75 KB
/
app.py
File metadata and controls
211 lines (163 loc) · 5.75 KB
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
import streamlit as st
import faiss
import json
import numpy as np
from sentence_transformers import SentenceTransformer
from groq import Groq
from neo4j import GraphDatabase
from dotenv import load_dotenv
import os
load_dotenv()
st.set_page_config(page_title="Medicine GraphRAG AI", layout="wide")
GROQ_API_KEY = st.secrets["GROQ_API_KEY"]
NEO4J_URI = st.secrets["NEO4J_URI"]
NEO4J_USER = st.secrets["NEO4J_USERNAME"]
NEO4J_PASSWORD = st.secrets["NEO4J_PASSWORD"]
NEO4J_DATABASE = st.secrets.get("NEO4J_DATABASE", "neo4j")
FAISS_INDEX_PATH = "db/medicine_embeddings.index"
METADATA_PATH = "db/metadata.json"
EMBED_MODEL = "BAAI/bge-large-en-v1.5"
LLM_MODEL = "openai/gpt-oss-120b"
# ---------------------------------------------------------
# LOAD MODELS & DATABASES (CACHED)
# ---------------------------------------------------------
@st.cache_resource
def load_faiss():
return faiss.read_index(FAISS_INDEX_PATH)
@st.cache_resource
def load_metadata():
with open(METADATA_PATH, "r") as f:
return json.load(f)
@st.cache_resource
def load_embedder():
return SentenceTransformer(EMBED_MODEL)
@st.cache_resource
def load_llm():
return Groq(api_key=GROQ_API_KEY)
@st.cache_resource
def load_neo4j():
driver = GraphDatabase.driver(
NEO4J_URI,
auth=(NEO4J_USER, NEO4J_PASSWORD),
max_connection_lifetime=3600,
max_connection_pool_size=50,
connection_acquisition_timeout=120
)
# Test the connection
driver.verify_connectivity()
return driver
faiss_index = load_faiss()
metadata = load_metadata()
embedder = load_embedder()
groq_client = load_llm()
# Load Neo4j with error handling
try:
neo4j_driver = load_neo4j()
st.sidebar.success("✅ Connected to Neo4j")
except Exception as e:
st.sidebar.error(f"❌ Neo4j Connection Failed: {str(e)}")
st.error(f"Database connection error. Please check your Neo4j credentials and connection: {str(e)}")
neo4j_driver = None
# ---------------------------------------------------------
# GRAPH EXPANSION — FETCH RELATED NODES
# ---------------------------------------------------------
def get_graph_info(drug_name):
if neo4j_driver is None:
return {}
query = """
MATCH (d:Drug {name: $name})-[r]->(n)
RETURN type(r) AS relation, n.name AS value
LIMIT 200
"""
try:
with neo4j_driver.session(database=NEO4J_DATABASE) as session:
result = session.run(query, name=drug_name).data()
except Exception as e:
st.warning(f"Could not fetch graph data for {drug_name}: {str(e)}")
return {}
graph_dict = {}
for row in result:
relation = row["relation"]
value = row["value"]
graph_dict.setdefault(relation, []).append(value)
return graph_dict
# ---------------------------------------------------------
# SEMANTIC SEARCH (FAISS)
# ---------------------------------------------------------
def semantic_search(query, top_k=5):
query_emb = embedder.encode(query).astype("float32")
distances, indices = faiss_index.search(
np.array([query_emb]), top_k
)
results = []
for idx in indices[0]:
results.append(metadata[idx])
return results
# ---------------------------------------------------------
# LLM ANSWER USING GROQ
# ---------------------------------------------------------
def answer_with_groq(query, retrieved, graph_info):
system_prompt = """
You are a medical question answering assistant.
You must:
- Use the retrieved medicine information.
- Use graph relations (substitutes, side effects, uses, classes).
- Never hallucinate facts.
- Respond using ONLY provided context.
"""
# Build context from FAISS metadata
text_block = ""
for item in retrieved:
text_block += f"""
Medicine: {item['name']}
Uses: {item['uses']}
Side Effects: {item['side_effects']}
Manufacturer: {item['manufacturer']}
"""
# Add graph info
graph_text = ""
for medicine, relations in graph_info.items():
graph_text += f"\nGraph Data for {medicine}:\n"
for rel, vals in relations.items():
graph_text += f"{rel}: {', '.join(vals)}\n"
full_prompt = f"""
{system_prompt}
User Query:
{query}
Retrieved Medicine Data:
{text_block}
Graph Knowledge:
{graph_text}
Final Answer:
"""
response = groq_client.chat.completions.create(
model=LLM_MODEL,
messages=[{"role": "user", "content": full_prompt}],
temperature=0.2,
)
return response.choices[0].message.content
# ---------------------------------------------------------
# STREAMLIT UI
# ---------------------------------------------------------
st.title("💊 Medicine GraphRAG AI")
st.write("Semantic Search + Graph DB + LLM reasoning using Groq GPT-OSS-20B")
query = st.text_input("Enter your medical query:", placeholder="e.g., best medicine for acidity")
if st.button("Search"):
if not query.strip():
st.warning("Please enter a query.")
else:
st.info("🔍 Searching medicines via FAISS semantic search...")
results = semantic_search(query)
st.write("### 🔬 Top Relevant Medicines")
for r in results:
st.write(f"**{r['name']}** — {r['uses']}")
st.info("🧠 Expanding Knowledge Graph for all retrieved medicines...")
graph_dict = {}
for r in results:
graph_dict[r["name"]] = get_graph_info(r["name"])
st.write("### 🧬 Graph Relations Found")
st.json(graph_dict)
st.success("🤖 Generating LLM Answer...")
answer = answer_with_groq(query, results, graph_dict)
st.write("### 🩺 Final Answer")
st.success(answer)