datdevsteve commited on
Commit
a32cd95
·
verified ·
1 Parent(s): d57fadf

Update nivra_agent.py

Browse files
Files changed (1) hide show
  1. nivra_agent.py +44 -49
nivra_agent.py CHANGED
@@ -3,6 +3,7 @@
3
  #=========================================
4
 
5
  import os
 
6
  import requests
7
  from dotenv import load_dotenv
8
 
@@ -13,24 +14,22 @@ from agent.image_symptom_tool import analyze_symptom_image
13
  load_dotenv()
14
 
15
  # ==================================================
16
- # Lazy singleton for RAG (HF-safe)
17
  # ==================================================
18
 
19
  _rag = None
20
 
21
-
22
  def get_rag():
23
  global _rag
24
  if _rag is None:
25
  _rag = NivraRAGRetriever()
26
  return _rag
27
 
28
-
29
  # ==================================================
30
  # SYSTEM PROMPT
31
  # ==================================================
32
 
33
- SYSTEM_PROMPT = """You are Nivra, a smart and helpful AI Healthcare Assistant with multimodal capabilities.
34
 
35
  🧠 **INTELLIGENT ROUTING RULES** (CRITICAL - Read First):
36
  1. **IF USER DESCRIBES PERSONAL SYMPTOMS** → Use structured medical format
@@ -98,10 +97,8 @@ Tuberculosis (TB) is caused by Mycobacterium tuberculosis bacteria, spread throu
98
 
99
  **FINAL CHECK**: Does user describe PERSONAL symptoms? YES=Medical format with respective token wrapping, NO=Natural response with respective token wrapping."""
100
 
101
-
102
-
103
  # ==================================================
104
- # GROQ RAW HTTP (HF SAFE)
105
  # ==================================================
106
 
107
  def call_groq(prompt: str) -> str:
@@ -110,7 +107,7 @@ def call_groq(prompt: str) -> str:
110
  return "⚠️ GROQ_API_KEY not configured."
111
 
112
  session = requests.Session()
113
- session.trust_env = False # HF Spaces proxy killer
114
 
115
  response = session.post(
116
  "https://api.groq.com/openai/v1/chat/completions",
@@ -130,54 +127,23 @@ def call_groq(prompt: str) -> str:
130
  )
131
 
132
  if response.status_code != 200:
133
- raise RuntimeError(
134
- f"Groq API error {response.status_code}: {response.text}"
135
- )
136
 
137
  return response.json()["choices"][0]["message"]["content"].strip()
138
 
139
  # ==================================================
140
- # MAIN CHAT FUNCTION
141
  # ==================================================
142
 
143
  def nivra_chat(user_input, chat_history=None):
144
-
145
- if isinstance(user_input, dict):
146
- user_input = user_input.get("text") or user_input.get("message", "")
147
  user_input = str(user_input).strip()
148
-
149
- input_lower = user_input.lower()
150
- text_keywords = ["fever", "headache", "cough", "pain", "vomiting", "chills"]
151
-
152
  tool_results = []
153
 
154
- # -------------------------
155
- # Text symptom tool
156
- # -------------------------
157
- if any(k in input_lower for k in text_keywords):
158
- try:
159
- tool_results.append(analyze_symptom_text.invoke(user_input))
160
- except Exception:
161
- tool_results.append("TEXT TOOL FAILED")
162
-
163
- # -------------------------
164
- # RAG retrieval
165
- # -------------------------
166
  try:
 
167
  tool_results.append(get_rag().getRelevantDocs(user_input))
168
  except Exception:
169
- tool_results.append("RAG FAILED")
170
-
171
- # Fallback
172
- if any("FAILED" in str(r) for r in tool_results):
173
- return (
174
- "[TOOLS USED] Tools failed - Network issue\n"
175
- f"[SYMPTOMS] {user_input}\n"
176
- "[PRIMARY DIAGNOSIS] Possible viral fever/infection\n"
177
- "[DIAGNOSIS DESCRIPTION] Fever+chills suggests infection.\n"
178
- "[FIRST AID] Rest, hydrate, paracetamol.\n"
179
- "[EMERGENCY] No"
180
- )
181
 
182
  final_prompt = f"""
183
  TOOL RESULTS:
@@ -189,11 +155,40 @@ USER INPUT:
189
  Provide diagnosis:
190
  """
191
 
 
 
 
 
 
 
 
 
 
 
 
 
192
  try:
193
- return call_groq(final_prompt)
194
  except Exception as e:
195
- print("❌ GROQ ERROR:", e)
196
- return (
197
- "⚠️ Temporary AI service issue.\n\n"
198
- "Please try again in a moment."
199
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  #=========================================
4
 
5
  import os
6
+ import base64
7
  import requests
8
  from dotenv import load_dotenv
9
 
 
14
  load_dotenv()
15
 
16
  # ==================================================
17
+ # Lazy singleton for RAG
18
  # ==================================================
19
 
20
  _rag = None
21
 
 
22
  def get_rag():
23
  global _rag
24
  if _rag is None:
25
  _rag = NivraRAGRetriever()
26
  return _rag
27
 
 
28
  # ==================================================
29
  # SYSTEM PROMPT
30
  # ==================================================
31
 
32
+ YSTEM_PROMPT = """You are Nivra, a smart and helpful AI Healthcare Assistant with multimodal capabilities.
33
 
34
  🧠 **INTELLIGENT ROUTING RULES** (CRITICAL - Read First):
35
  1. **IF USER DESCRIBES PERSONAL SYMPTOMS** → Use structured medical format
 
97
 
98
  **FINAL CHECK**: Does user describe PERSONAL symptoms? YES=Medical format with respective token wrapping, NO=Natural response with respective token wrapping."""
99
 
 
 
100
  # ==================================================
101
+ # GROQ CALL
102
  # ==================================================
103
 
104
  def call_groq(prompt: str) -> str:
 
107
  return "⚠️ GROQ_API_KEY not configured."
108
 
109
  session = requests.Session()
110
+ session.trust_env = False
111
 
112
  response = session.post(
113
  "https://api.groq.com/openai/v1/chat/completions",
 
127
  )
128
 
129
  if response.status_code != 200:
130
+ raise RuntimeError(f"Groq error {response.status_code}: {response.text}")
 
 
131
 
132
  return response.json()["choices"][0]["message"]["content"].strip()
133
 
134
  # ==================================================
135
+ # TEXT CHAT (UNCHANGED)
136
  # ==================================================
137
 
138
  def nivra_chat(user_input, chat_history=None):
 
 
 
139
  user_input = str(user_input).strip()
 
 
 
 
140
  tool_results = []
141
 
 
 
 
 
 
 
 
 
 
 
 
 
142
  try:
143
+ tool_results.append(analyze_symptom_text.invoke(user_input))
144
  tool_results.append(get_rag().getRelevantDocs(user_input))
145
  except Exception:
146
+ tool_results.append("TOOL FAILURE")
 
 
 
 
 
 
 
 
 
 
 
147
 
148
  final_prompt = f"""
149
  TOOL RESULTS:
 
155
  Provide diagnosis:
156
  """
157
 
158
+ return call_groq(final_prompt)
159
+
160
+ # ==================================================
161
+ # 🆕 IMAGE DIAGNOSIS ENTRY POINT
162
+ # ==================================================
163
+
164
+ def nivra_vision(image_base64: str, hint_text: str = "") -> str:
165
+ """
166
+ image_base64: base64-encoded image string
167
+ hint_text: optional user description
168
+ """
169
+
170
  try:
171
+ image_result = analyze_symptom_image.invoke(image_base64)
172
  except Exception as e:
173
+ return f"""
174
+ [TOOLS USED] analyze_symptom_image [/TOOLS USED]
175
+ [SYMPTOMS] Image could not be analyzed [/SYMPTOMS]
176
+ [PRIMARY DIAGNOSIS] Unable to assess from image [/PRIMARY DIAGNOSIS]
177
+ [DIAGNOSIS DESCRIPTION]
178
+ Image analysis failed. Please try again with a clearer image.
179
+ [/DIAGNOSIS DESCRIPTION]
180
+ [FIRST AID] Consult a healthcare professional [/FIRST AID]
181
+ [EMERGENCY CONSULTATION REQUIRED] Yes [/EMERGENCY CONSULTATION REQUIRED]
182
+ """
183
+
184
+ final_prompt = f"""
185
+ IMAGE ANALYSIS:
186
+ {image_result}
187
+
188
+ USER CONTEXT:
189
+ {hint_text}
190
+
191
+ Provide medical image-based preliminary assessment:
192
+ """
193
+
194
+ return call_groq(final_prompt)