Muhammadidrees commited on
Commit
eb1c0c7
·
verified ·
1 Parent(s): ca92d1b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -117
app.py CHANGED
@@ -1,121 +1,54 @@
1
- import gradio as gr
2
  import os
3
- from openai import OpenAI
4
-
5
- # 🔹 Set your Grok (xAI) API Key securely
6
- os.environ["XAI_API_KEY"] = "xai-2ftlCxHfSh3eCmrzNVWlC8X1r4w06GQTPLK8YFwJdwjgFXK0oW0H6QvR4NN5N0fhkLLEkibGBY7Q1e6m"
7
-
8
- # 🔹 Initialize client for Grok
9
- client = OpenAI(
10
- api_key=os.getenv("XAI_API_KEY"),
11
- base_url="https://api.x.ai/v1" # xAI Grok endpoint
 
 
 
 
 
 
 
 
 
 
 
12
  )
13
 
14
- # 🔹 Define model (latest general-purpose)
15
- MODEL_ID = "grok-beta" # or "grok-2", check console for available models
16
-
17
- # ---------------- AI Response Function ----------------
18
- def respond(albumin, creatinine, glucose, crp, mcv, rdw, alp, wbc, lymphocytes,
19
- hemoglobin, pv, age, gender, height, weight):
20
-
21
- system_message = (
22
- "You are an AI Health Assistant that analyzes laboratory biomarkers "
23
- "and generates structured, patient-friendly health summaries.\n\n"
24
- "Your task is to evaluate the provided biomarkers and generate an AI-driven medical report "
25
- "with insights, observations, and clear explanations.\n"
26
- "You must strictly follow this structured format:\n\n"
27
- "### Tabular Mapping\n"
28
- "| Biomarker | Value | Status (Low/Normal/High) | AI-Inferred Insight |Reference Range|\n"
29
- "Include all available biomarkers: Albumin, Creatinine, Glucose, CRP, MCV, RDW, ALP, WBC, "
30
- "Lymphocytes, Hemoglobin, Plasma Viscosity (PV).\n\n"
31
- "### Executive Summary\n"
32
- "- Top 3 Health Priorities.\n"
33
- "- Key Strengths (normal biomarkers).\n\n"
34
- "### System-Specific Analysis\n"
35
- "- Organ systems: Liver, Kidney, Immune, Blood, etc.\n"
36
- "- Status: “Optimal” | “Monitor” | “Needs Attention”.\n"
37
- "- Write concise, supportive explanations.\n\n"
38
- "### Personalized Action Plan\n"
39
- "- Recommendations: Nutrition, Lifestyle, Testing, Consultation.\n"
40
- "- Never recommend medication.\n\n"
41
- "### Interaction Alerts\n"
42
- "- Highlight potential relationships (e.g., high CRP + low Albumin).\n\n"
43
- "### Constraints\n"
44
- "- No diagnosis or prescriptions.\n"
45
- "- Use only provided data.\n"
46
- "- Always recommend seeing a healthcare professional.\n"
47
- "- Include normal reference ranges for each biomarker.\n"
48
- "- Use patient-friendly language."
49
- )
50
-
51
- user_message = (
52
- f"Patient Information:\n"
53
- f"- Age: {age} years\n"
54
- f"- Gender: {gender}\n"
55
- f"- Height: {height} cm\n"
56
- f"- Weight: {weight} kg\n\n"
57
- f"Biomarker Values:\n"
58
- f"- Albumin: {albumin} g/dL\n"
59
- f"- Creatinine: {creatinine} mg/dL\n"
60
- f"- Glucose: {glucose} mg/dL\n"
61
- f"- CRP: {crp} mg/L\n"
62
- f"- MCV: {mcv} fL\n"
63
- f"- RDW: {rdw} %\n"
64
- f"- ALP: {alp} U/L\n"
65
- f"- WBC: {wbc} x10^3/μL\n"
66
- f"- Lymphocytes: {lymphocytes} %\n"
67
- f"- Hemoglobin: {hemoglobin} g/dL\n"
68
- f"- Plasma Viscosity (PV): {pv} mPa·s"
69
- )
70
-
71
- completion = client.chat.completions.create(
72
- model=MODEL_ID,
73
- messages=[
74
- {"role": "system", "content": system_message},
75
- {"role": "user", "content": user_message}
76
- ],
77
- temperature=0.2,
78
- max_tokens=2000
79
- )
80
-
81
- return completion.choices[0].message.content
82
-
83
-
84
- # ---------------- Gradio UI ----------------
85
- with gr.Blocks() as demo:
86
- gr.Markdown("## 🧪 AI Health Assistant (Extended Biomarkers via Grok API)")
87
-
88
- with gr.Row():
89
- with gr.Column():
90
- albumin = gr.Textbox(label="Albumin (g/dL)", value="4.5")
91
- creatinine = gr.Textbox(label="Creatinine (mg/dL)", value="1.5")
92
- glucose = gr.Textbox(label="Glucose (mg/dL, fasting)", value="160")
93
- crp = gr.Textbox(label="CRP (mg/L)", value="2.5")
94
- mcv = gr.Textbox(label="MCV (fL)", value="150")
95
- rdw = gr.Textbox(label="RDW (%)", value="15")
96
- alp = gr.Textbox(label="ALP (U/L)", value="146")
97
- wbc = gr.Textbox(label="WBC (10^3/μL)", value="10.5")
98
- lymphocytes = gr.Textbox(label="Lymphocytes (%)", value="38")
99
- hemoglobin = gr.Textbox(label="Hemoglobin (g/dL)", value="13.5")
100
- pv = gr.Textbox(label="Plasma Viscosity (mPa·s)", value="1.7")
101
-
102
- with gr.Column():
103
- age = gr.Textbox(label="Age (years)", value="30")
104
- gender = gr.Dropdown(choices=["Male", "Female"], label="Gender", value="Male")
105
- height = gr.Textbox(label="Height (cm)", value="170")
106
- weight = gr.Textbox(label="Weight (kg)", value="65")
107
-
108
- output = gr.Textbox(label="AI Health Report", lines=30)
109
-
110
- btn = gr.Button("Generate Report")
111
- btn.click(
112
- respond,
113
- inputs=[
114
- albumin, creatinine, glucose, crp, mcv, rdw, alp, wbc,
115
- lymphocytes, hemoglobin, pv, age, gender, height, weight
116
- ],
117
- outputs=output
118
- )
119
-
120
  if __name__ == "__main__":
121
- demo.launch()
 
 
 
 
 
 
 
 
1
  import os
2
+ from dotenv import load_dotenv
3
+ import openai
4
+
5
+ # -----------------------------
6
+ # 1️⃣ Load Environment Variables
7
+ # -----------------------------
8
+ load_dotenv() # Load .env file if present
9
+
10
+ # Retrieve the XAI API key
11
+ XAI_API_KEY = os.getenv("XAI_API_KEY")
12
+
13
+ if not XAI_API_KEY:
14
+ raise ValueError("❌ XAI_API_KEY not found. Please set it in your .env file.")
15
+
16
+ # -----------------------------
17
+ # 2️⃣ Configure OpenAI Client (for Grok API)
18
+ # -----------------------------
19
+ client = openai.OpenAI(
20
+ base_url="https://api.x.ai/v1",
21
+ api_key=XAI_API_KEY
22
  )
23
 
24
+ # -----------------------------
25
+ # 3️⃣ Function to Query Grok
26
+ # -----------------------------
27
+ def query_grok(prompt: str):
28
+ try:
29
+ completion = client.chat.completions.create(
30
+ model="grok-beta", # or "grok-2" if available
31
+ messages=[
32
+ {"role": "system", "content": "You are a helpful AI assistant for testing Grok API."},
33
+ {"role": "user", "content": prompt},
34
+ ],
35
+ )
36
+ response = completion.choices[0].message.content
37
+ print(f"\n✅ Response:\n{response}\n")
38
+ return response
39
+ except Exception as e:
40
+ print(f"\n❌ Error occurred:\n{str(e)}\n")
41
+ return None
42
+
43
+
44
+ # -----------------------------
45
+ # 4️⃣ Main CLI Entry Point
46
+ # -----------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  if __name__ == "__main__":
48
+ print("🚀 GROK API Test Console")
49
+ while True:
50
+ user_input = input("\nEnter your query (or type 'exit'): ")
51
+ if user_input.lower() == "exit":
52
+ print("👋 Exiting Grok tester.")
53
+ break
54
+ query_grok(user_input)