Abdullahcoder54 commited on
Commit
ab28991
·
1 Parent(s): 467ccda

add chat bot

Browse files
Files changed (3) hide show
  1. app.py +10 -3
  2. chatbot.py +82 -0
  3. reportanalysis.py +3 -2
app.py CHANGED
@@ -1,9 +1,9 @@
1
- from fastapi import FastAPI, UploadFile , File
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from agents import Runner
4
- from reportanalysis import Report_Agent, extract_text
5
  from logging import getLogger
6
-
 
7
  app = FastAPI()
8
  log = getLogger()
9
 
@@ -19,6 +19,13 @@ app.add_middleware(
19
  async def root():
20
  return {"message": "Welcome to the Medical Report Analysis API"}
21
 
 
 
 
 
 
 
 
22
  @app.post("/upload")
23
  async def upload_file(file: UploadFile = File(...)):
24
  try:
 
1
+ from fastapi import FastAPI, UploadFile , File , Request
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from agents import Runner
 
4
  from logging import getLogger
5
+ from reportanalysis import Report_Agent, extract_text
6
+ from chatbot import get_health_response
7
  app = FastAPI()
8
  log = getLogger()
9
 
 
19
  async def root():
20
  return {"message": "Welcome to the Medical Report Analysis API"}
21
 
22
+ @app.post("/chatbot")
23
+ async def health_info(request: Request):
24
+ data = await request.json()
25
+ msg = data.get("message")
26
+ result = await get_health_response(msg) # <- await here
27
+ return {"response": result}
28
+
29
  @app.post("/upload")
30
  async def upload_file(file: UploadFile = File(...)):
31
  try:
chatbot.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # chatbot.py
2
+ from agents import Agent,RunConfig,Runner,OpenAIChatCompletionsModel,AsyncOpenAI,set_tracing_disabled
3
+ import asyncio
4
+ from dotenv import load_dotenv
5
+ import os
6
+
7
+ set_tracing_disabled(disabled=True)
8
+
9
+
10
+ load_dotenv()
11
+ api_key = os.getenv("GEM_API_KEY")
12
+
13
+ external_client = AsyncOpenAI(
14
+ api_key=api_key,
15
+ base_url="https://generativelanguage.googleapis.com/v1beta/openai/",
16
+ )
17
+
18
+ model = OpenAIChatCompletionsModel(
19
+ model="gemini-2.0-flash",
20
+ openai_client=external_client
21
+ )
22
+
23
+ config = RunConfig(
24
+ model=model,
25
+ model_provider=external_client,
26
+ tracing_disabled=True
27
+ )
28
+
29
+ agent: Agent = Agent(
30
+ name="Doctor",
31
+ instructions="""
32
+ You are **DrXpert**, an intelligent and reliable AI medical assistant designed to help users understand health symptoms and get general guidance.
33
+ Your job is to **analyze user symptoms**, explain possible causes, and suggest **safe, verified, and general health advice** — without diagnosing or prescribing prescription-only medicines.
34
+
35
+ 🧠 **Core Rules (Follow Strictly):**
36
+ 1. Always stay within **medical accuracy** and **safe general advice**.
37
+ 2. Never guess, make up, or invent diseases, symptoms, or medicines.
38
+ - If you are not 100% sure, respond:
39
+ “I’m not completely sure about that. It’s best to consult a real doctor for proper diagnosis.”
40
+ 3. Never give harmful or unverified advice, never recommend antibiotics or injections.
41
+ 4. If the question is unrelated to health, reply:
42
+ “I’m designed to discuss health-related topics only. Please ask something related to symptoms, medicines, or wellness.”
43
+
44
+ 💬 **Response Format (Always Follow This):**
45
+ When the user mentions symptoms (e.g., “I have a fever”, “I feel dizzy”, “I have chest pain”), respond with:
46
+ 1. **Possible Common Causes** (1–2 short lines, simple explanation only)
47
+ 2. **Safe Medicine Suggestion (Optional)**
48
+ - Only general medicines like *Paracetamol, ORS, Panadol, etc.*
49
+ - Never mention strong or prescription drugs.
50
+ 3. **Precautions (2–3 short, clear points)**
51
+ - E.g., “Rest well”, “Drink plenty of fluids”, “Avoid cold drinks”
52
+ 4. **Home Remedies (1–2 simple tips)** in **Urdu or English**
53
+ - E.g., “Take steam”, “Honey with lemon water”, “Use salt water gargle”
54
+ 5. End with a **kind, short line** such as:
55
+ - “Allah sehat de ❤️”
56
+ - “Khush raho, duaon mein yaad rakhna 😊”
57
+
58
+ 💡 **Tone & Style:**
59
+ - Be warm, calm, caring — like a friendly online doctor.
60
+ - Keep sentences short, simple, and free of medical jargon.
61
+ - Use a balance of Urdu & English when possible.
62
+ - Never repeat questions or unnecessary details.
63
+
64
+ 🚫 **Important Safety Rules:**
65
+ - Do NOT give specific diagnoses.
66
+ - Do NOT discuss suicide, sexual content, or emergencies — instead say:
67
+ “This seems serious, please visit a nearby hospital immediately.”
68
+ - Do NOT reveal private or personal information.
69
+
70
+ You are now ready to respond as **DrXpert**, a kind, factual, and safe virtual health guide.
71
+ """,
72
+
73
+ model=model
74
+ )
75
+
76
+
77
+ async def get_health_response(user_message: str) -> str:
78
+ print("Running agent with message:", user_message)
79
+ result = await Runner.run(agent, user_message, run_config=config)
80
+ print("Final output:", result.final_output)
81
+ return result.final_output
82
+
reportanalysis.py CHANGED
@@ -119,8 +119,9 @@ Your Main Task:
119
  - Green: Normal or safe
120
  4. Provide a clear summary of the findings.
121
  5. Offer relevant AI-driven health tips, highlight potential risks, and suggest dietary and lifestyle improvements.
122
-
123
- Return your final response STRICTLY in the JSON structure.
 
124
 
125
  """,
126
  model = agent_model,
 
119
  - Green: Normal or safe
120
  4. Provide a clear summary of the findings.
121
  5. Offer relevant AI-driven health tips, highlight potential risks, and suggest dietary and lifestyle improvements.
122
+ 6. Structure the output in the specified JSON format.
123
+ Response format: {'type': 'json_schema', 'json_schema': {'name': 'final_output', 'strict': True, 'schema': {'$defs': {'AiTipSection': {'properties': {'title': {'title': 'Title', 'type': 'string'}, 'risk': {'title': 'Risk', 'type': 'string'}, 'tips': {'title': 'Tips', 'type': 'string'}, 'action': {'title': 'Action', 'type': 'string'}, 'diet_suggestion': {'items': {'type': 'string'}, 'title': 'Diet Suggestion', 'type': 'array'}, 'life_style': {'items': {'type': 'string'}, 'title': 'Life Style', 'type': 'array'}}, 'required': ['title', 'risk', 'tips', 'action', 'diet_suggestion', 'life_style'], 'title':
124
+ 'AiTipSection', 'type': 'object', 'additionalProperties': False}, 'ReportSection': {'properties': {'title': {'title': 'Title', 'type': 'string'}, 'tests': {'items': {'$ref': '#/$defs/TestItem'}, 'title': 'Tests', 'type': 'array'}, 'section_summary': {'title': 'Section Summary', 'type': 'string'}}, 'required': ['title', 'tests', 'section_summary'], 'title': 'ReportSection', 'type': 'object', 'additionalProperties': False}, 'TestItem': {'properties': {'name': {'title': 'Name', 'type': 'string'}, 'user_value': {'title': 'User Value', 'type': 'string'}, 'normal_range': {'title': 'Normal Range', 'type': 'string'}, 'analysis': {'anyOf': [{'type': 'string'}, {'type': 'null'}], 'title': 'Analysis'}, 'flag': {'enum': ['Red', 'Yellow', 'Green'], 'title': 'Flag', 'type': 'string'}}, 'required': ['name', 'user_value', 'normal_range', 'analysis', 'flag'], 'title': 'TestItem', 'type': 'object', 'additionalProperties': False}}, 'properties': {'report_summary_title': {'title': 'Report Summary Title', 'type': 'string'}, 'ai_tip_title': {'title': 'Ai Tip Title', 'type': 'string'}, 'report_sections': {'items': {'$ref': '#/$defs/ReportSection'}, 'title': 'Report Sections', 'type': 'array'}, 'ai_tip_sections': {'items': {'$ref': '#/$defs/AiTipSection'}, 'title': 'Ai Tip Sections', 'type': 'array'}}, 'required': ['report_summary_title', 'ai_tip_title', 'report_sections', 'ai_tip_sections'], 'title': 'ReportSchema', 'type': 'object', 'additionalProperties': False}}}
125
 
126
  """,
127
  model = agent_model,