diff --git a/README.md b/README.md index f549275..efc1f5e 100644 --- a/README.md +++ b/README.md @@ -247,6 +247,15 @@ percentage, missing keywords, and profile summary. - **Risk Assessment:** The risk management agent evaluates potential risks associated with the trading strategy and suggests mitigation measures. - **Execution Planning:** The execution agent develops a detailed plan for executing the trading strategy, considering the assessed risks. +### 26. Agent Doc + +- **Route:** `/agent_doc` +- **Description:** This API endpoint coordinates a team of AI agents to perform comprehensive healthcare diagnosis and treatment recommendations. +- **Feature:** + - **Input Data:** Users can provide input data including gender, age, symptoms, and medical history. + - **Diagnosis:** The diagnostician agent analyzes the input data to provide a preliminary diagnosis with possible conditions. + - **Treatment Recommendations:** The treatment advisor agent formulates a suitable treatment plan based on the diagnosis and user-provided information. + ## Usage Each endpoint accepts specific parameters as described in the respective endpoint documentation. Users can make POST requests to these endpoints with the required parameters to perform the desired tasks. diff --git a/agent_doc/agents.py b/agent_doc/agents.py new file mode 100644 index 0000000..8c9e18f --- /dev/null +++ b/agent_doc/agents.py @@ -0,0 +1,31 @@ +from crewai import Agent +from .tools import scrape_tool, search_tool +from langchain_google_genai import ChatGoogleGenerativeAI +import os +import settings + +llm=ChatGoogleGenerativeAI(model=settings.GEMINI_FLASH, + verbose=True, + temperature=0.7, + google_api_key=os.getenv("GOOGLE_API_KEY")) + + +diagnostician = Agent( + role="Medical Diagnostician", + goal="Analyze patient symptoms and medical history to provide a preliminary diagnosis.", + backstory="This agent specializes in diagnosing medical conditions based on patient-reported symptoms and medical history. It uses advanced algorithms and medical knowledge to identify potential health issues.", + verbose=True, + allow_delegation=False, + tools=[search_tool, scrape_tool], + llm=llm +) + +treatment_advisor = Agent( + role="Treatment Advisor", + goal="Recommend appropriate treatment plans based on the diagnosis provided by the Medical Diagnostician.", + backstory="This agent specializes in creating treatment plans tailored to individual patient needs. It considers the diagnosis, patient history, and current best practices in medicine to recommend effective treatments.", + verbose=True, + allow_delegation=False, + tools=[search_tool, scrape_tool], + llm=llm +) \ No newline at end of file diff --git a/agent_doc/crew.py b/agent_doc/crew.py new file mode 100644 index 0000000..fa22a6b --- /dev/null +++ b/agent_doc/crew.py @@ -0,0 +1,23 @@ +from crewai import Crew +from .agents import treatment_advisor, diagnostician +from .tasks import diagnose_task, treatment_task + + +doc_crew = Crew( + agents=[diagnostician, treatment_advisor], + tasks=[diagnose_task, treatment_task], + verbose=2 +) + +def run_doc_crew(input_data): + result = doc_crew.kickoff(inputs=input_data) + return result + +if __name__=='__main__': + doc_agent_input ={ + 'gender': 'Male', + 'age': '28', + 'symptoms': 'fever, cough, headache', + 'medical_history': 'diabetes, hypertension' + } + print(run_doc_crew(input_data=doc_agent_input)) \ No newline at end of file diff --git a/agent_doc/tasks.py b/agent_doc/tasks.py new file mode 100644 index 0000000..43ce936 --- /dev/null +++ b/agent_doc/tasks.py @@ -0,0 +1,23 @@ +from crewai import Task +from .agents import diagnostician, treatment_advisor + + +diagnose_task = Task( + description=( + "1. Analyze the patient's symptoms ({symptoms}) and medical history ({medical_history}).\n" + "2. Provide a preliminary diagnosis with possible conditions based on the provided information.\n" + "3. Limit the diagnosis to the most likely conditions." + ), + expected_output="A preliminary diagnosis with a list of possible conditions.", + agent=diagnostician +) + +treatment_task = Task( + description=( + "1. Based on the diagnosis, recommend appropriate treatment plans step by step.\n" + "2. Consider the patient's medical history ({medical_history}) and current symptoms ({symptoms}).\n" + "3. Provide detailed treatment recommendations, including medications, lifestyle changes, and follow-up care." + ), + expected_output="A comprehensive treatment plan tailored to the patient's needs.", + agent=treatment_advisor +) \ No newline at end of file diff --git a/agent_doc/tools.py b/agent_doc/tools.py new file mode 100644 index 0000000..bf1d57d --- /dev/null +++ b/agent_doc/tools.py @@ -0,0 +1,9 @@ +from crewai_tools import ScrapeWebsiteTool, SerperDevTool +import os +from dotenv import load_dotenv +load_dotenv() + +os.environ['SERPER_API_KEY'] = os.getenv('SERPER_API_KEY') + +search_tool = SerperDevTool() +scrape_tool = ScrapeWebsiteTool() \ No newline at end of file diff --git a/api.py b/api.py index 16473a2..84faba7 100644 --- a/api.py +++ b/api.py @@ -31,6 +31,7 @@ from uuid import uuid4 from tech_news_agent.crew import run_crew from investment_risk_analyst_agent.crew import run_investment_crew +from agent_doc.crew import run_doc_crew from langchain.agents import AgentExecutor from langchain_core.prompts import ChatPromptTemplate from langchain_cohere.react_multi_hop.agent import create_cohere_react_agent @@ -843,6 +844,60 @@ async def run_risk_investment_agent(request:Request,stock_selection: str = Form( return ResponseText(response=report) except Exception as e: return {"error": str(e)} + +@app.post("/agent_doc",description=""" + This route leverages AI agents to assist doctors in diagnosing medical conditions and + recommending treatment plans based on patient-reported symptoms and medical history. + + NOTE : Output will take some time as multiple agents are working together. + """) +@limiter.limit("2/30minute") +async def run_doc_agent(request:Request,gender: str = Form("Male"), + age : int = Form("28"), + symptoms: str = Form("fever, cough, headache"), + medical_history : str = Form("diabetes, hypertension"), + token: str = Depends(oauth2_scheme)): + try: + payload = jwt.decode(token, os.getenv("TOKEN_SECRET_KEY"), algorithms=[settings.ALGORITHM]) + email = payload.get("sub") + if email is None: + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token") + user = users_collection.find_one({"email": email}) + if user is None: + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found") + except JWTError: + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token") + + try: + input_data = {"gender": gender, + "risk_tolerance": age, + "symptoms": symptoms, + "medical_history": medical_history + } + print(input_data) + cache_key = f"agent_doc:{input_data}" + cached_response = redis.get(cache_key) + if cached_response: + print("Retrieving response from Redis cache") + return ResponseText(response=cached_response.decode("utf-8")) + + report = run_doc_crew(input_data) + redis.set(cache_key, report, ex=10) + db = MongoDB() + payload = { + "endpoint": "/agent_doc", + "Gender" : gender, + "Age" : age, + "Symptoms" : symptoms, + "Medical History" : medical_history, + "Medical Report": report + } + mongo_data = {"Document": payload} + result = db.insert_data(mongo_data) + print(result) + return ResponseText(response=report) + except Exception as e: + return {"error": str(e)} if __name__ == '__main__': import uvicorn