Abdullahcoder54 commited on
Commit
842ea04
·
1 Parent(s): ca86376

Update accourding to new UI

Browse files
Files changed (3) hide show
  1. app.py +2 -1
  2. chatbot.py +25 -8
  3. reportanalysis.py +29 -33
app.py CHANGED
@@ -27,7 +27,7 @@ async def health_info(request: Request):
27
  result.replace("\n/", "<br>")
28
  return {"response": result}
29
 
30
- @app.post("/upload")
31
  async def upload_file(file: UploadFile = File(...)):
32
  try:
33
  pdf = file.filename.lower().endswith('.pdf')
@@ -48,6 +48,7 @@ Once the text is extracted, continue with step-by-step medical analysis and retu
48
  context=content,
49
 
50
  )
 
51
  print(result.final_output)
52
  return {"result": result.final_output.model_dump()}
53
  except Exception as e:
 
27
  result.replace("\n/", "<br>")
28
  return {"response": result}
29
 
30
+ @app.post("/report-analysis")
31
  async def upload_file(file: UploadFile = File(...)):
32
  try:
33
  pdf = file.filename.lower().endswith('.pdf')
 
48
  context=content,
49
 
50
  )
51
+
52
  print(result.final_output)
53
  return {"result": result.final_output.model_dump()}
54
  except Exception as e:
chatbot.py CHANGED
@@ -1,11 +1,20 @@
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")
@@ -26,6 +35,15 @@ config = RunConfig(
26
  tracing_disabled=True
27
  )
28
 
 
 
 
 
 
 
 
 
 
29
  agent: Agent = Agent(
30
  name="Doctor",
31
  instructions="""
@@ -118,14 +136,13 @@ Agar dard barhta hai toh please doctor ko dikhayein.\n
118
  Take care! ❤️
119
 
120
  """,
121
-
 
122
  model=model
123
  )
124
 
125
-
126
  async def get_health_response(user_message: str) -> str:
127
  print("Running agent with message:", user_message)
128
  result = await Runner.run(agent, user_message, run_config=config)
129
  print("Final output:", result)
130
- return result.final_output
131
-
 
1
  # chatbot.py
2
+ from agents import (Agent,
3
+ RunConfig,
4
+ Runner,
5
+ OpenAIChatCompletionsModel,
6
+ AsyncOpenAI,
7
+ model_settings,
8
+ function_tool,
9
+ set_tracing_disabled,
10
+ enable_verbose_stdout_logging)
11
  from dotenv import load_dotenv
12
  import os
13
+ import requests
14
+ import xmltodict
15
+ import json
16
  set_tracing_disabled(disabled=True)
17
+ enable_verbose_stdout_logging()
18
 
19
  load_dotenv()
20
  api_key = os.getenv("GEM_API_KEY")
 
35
  tracing_disabled=True
36
  )
37
 
38
+ @function_tool
39
+ async def get_info_about_health(query:str) -> str:
40
+ """Fetch health information from web based on the query.
41
+ That helps to provide accurate medical advice."""
42
+ url = f"https://wsearch.nlm.nih.gov/ws/query?db=healthTopics&term={query}"
43
+ responce = requests.get(url)
44
+
45
+ return responce.text
46
+
47
  agent: Agent = Agent(
48
  name="Doctor",
49
  instructions="""
 
136
  Take care! ❤️
137
 
138
  """,
139
+ tools=[get_info_about_health],
140
+ model_settings=model_settings.ModelSettings(tool_choice="required"),
141
  model=model
142
  )
143
 
 
144
  async def get_health_response(user_message: str) -> str:
145
  print("Running agent with message:", user_message)
146
  result = await Runner.run(agent, user_message, run_config=config)
147
  print("Final output:", result)
148
+ return result.final_output
 
reportanalysis.py CHANGED
@@ -15,7 +15,8 @@ from typing import List, Literal
15
  from agents import (
16
  Agent,
17
  AsyncOpenAI,
18
- OpenAIChatCompletionsModel,
 
19
  AgentOutputSchemaBase,
20
  enable_verbose_stdout_logging,
21
  set_tracing_disabled
@@ -30,31 +31,30 @@ anonymizer = AnonymizerEngine()
30
 
31
  API = os.getenv("GEM_API_KEY")
32
 
33
- class TestItem(BaseModel):
34
- name: str
35
- user_value: str
36
- normal_range: str
37
- analysis: str | None = None
38
- flag: Literal["Red", "Yellow", "Green"]
39
-
40
- class ReportSection(BaseModel):
41
- title: str
42
- tests: List[TestItem]
43
- section_summary: str
44
-
45
- class AiTipSection(BaseModel):
46
- title: str
47
- risk: str
48
- tips: str
49
- action: str
50
- diet_suggestion: List[str] = Field(default_factory=list)
51
- life_style: List[str] = Field(default_factory=list)
52
-
53
- class ReportSchema(BaseModel):
54
- report_summary_title: str
55
- ai_tip_title: str
56
- report_sections: List[ReportSection]
57
- ai_tip_sections: List[AiTipSection]
58
 
59
  client = AsyncOpenAI(
60
  api_key = API,
@@ -120,14 +120,10 @@ Your Main Task:
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,
128
- output_type= ReportSchema,
129
  )
130
 
131
-
132
-
133
-
 
15
  from agents import (
16
  Agent,
17
  AsyncOpenAI,
18
+ OpenAIChatCompletionsModel,
19
+ AgentOutputSchema,
20
  AgentOutputSchemaBase,
21
  enable_verbose_stdout_logging,
22
  set_tracing_disabled
 
31
 
32
  API = os.getenv("GEM_API_KEY")
33
 
34
+ class AiInsights(BaseModel):
35
+ overallAssessment: str
36
+ keyHighlights: List[dict[str, str]]
37
+ dietaryRecommendations: List[str]
38
+ lifestyleAdvice: List[str]
39
+ precautions: List[str]
40
+ risks: List[str]
41
+ actions: List[dict[str, str]]
42
+ tips: List[str]
43
+
44
+ class KeyFinding(BaseModel):
45
+ test: str
46
+ value: int
47
+ unit: str
48
+ range: str
49
+ shortExplaination: str
50
+ status: Literal["Red", "Yellow", "Green"]
51
+
52
+ class AnalysisResult(BaseModel):
53
+ fileName: str
54
+ reportType: str
55
+ summary: str
56
+ keyFindings: List[KeyFinding]
57
+ aiInsights: AiInsights
 
58
 
59
  client = AsyncOpenAI(
60
  api_key = API,
 
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': False, 'schema': {'$defs': {'AiInsights': {'properties': {'overallAssessment': {'title': 'Overallassessment', 'type': 'string'}, 'keyHighlights': {'items': {'additionalProperties': {'type': 'string'}, 'type': 'object'}, 'title': 'Keyhighlights', 'type': 'array'}, 'dietaryRecommendations': {'items': {'type': 'string'}, 'title': 'Dietaryrecommendations', 'type': 'array'}, 'lifestyleAdvice': {'items': {'type': 'string'}, 'title': 'Lifestyleadvice', 'type': 'array'}, 'precautions': {'items': {'type': 'string'}, 'title': 'Precautions', 'type': 'array'}, 'risks': {'items': {'type': 'string'}, 'title': 'Risks', 'type': 'array'}, 'actions': {'items': {'additionalProperties': {'type': 'string'}, 'type': 'object'}, 'title': 'Actions', 'type': 'array'}, 'tips': {'items': {'type': 'string'}, 'title': 'Tips', 'type': 'array'}}, 'required': ['overallAssessment', 'keyHighlights', 'dietaryRecommendations', 'lifestyleAdvice', 'precautions', 'risks', 'actions', 'tips'], 'title': 'AiInsights', 'type': 'object'}, 'KeyFinding': {'properties': {'test': {'title': 'Test', 'type': 'string'}, 'value': {'title': 'Value', 'type': 'integer'}, 'unit': {'title': 'Unit', 'type': 'string'}, 'range': {'title': 'Range', 'type': 'string'}, 'status': {'enum': ['Red', 'Yellow', 'Green'], 'title': 'Status', 'type': 'string'}}, 'required': ['test', 'value', 'unit', 'range', 'status'], 'title': 'KeyFinding', 'type': 'object'}}, 'properties': {'fileName': {'title': 'Filename', 'type': 'string'}, 'reportType': {'title': 'Reporttype', 'type': 'string'}, 'summary': {'title': 'Summary', 'type': 'string'}, 'keyFindings': {'items': {'$ref': '#/$defs/KeyFinding'}, 'title': 'Keyfindings', 'type': 'array'}, 'aiInsights': {'$ref': '#/$defs/AiInsights'}},
124
+ 'required': ['fileName', 'reportType', 'summary', 'keyFindings', 'aiInsights'], 'title': 'AnalysisResult', 'type': 'object'}}}
 
125
  """,
126
  model = agent_model,
127
+ output_type= AgentOutputSchema(AnalysisResult, strict_json_schema=False)
128
  )
129