diff --git a/python/agents/medical-pre-authorization/deployment/deploy.py b/python/agents/medical-pre-authorization/deployment/deploy.py index dc50785f4..fd3624c01 100644 --- a/python/agents/medical-pre-authorization/deployment/deploy.py +++ b/python/agents/medical-pre-authorization/deployment/deploy.py @@ -79,18 +79,10 @@ def main(argv: list[str]) -> None: load_dotenv() project_id = ( - FLAGS.project_id - if FLAGS.project_id - else os.getenv("GOOGLE_CLOUD_PROJECT") - ) - location = ( - FLAGS.location if FLAGS.location else os.getenv("GOOGLE_CLOUD_LOCATION") - ) - bucket = ( - FLAGS.bucket - if FLAGS.bucket - else os.getenv("GOOGLE_CLOUD_STORAGE_BUCKET") + FLAGS.project_id if FLAGS.project_id else os.getenv("GOOGLE_CLOUD_PROJECT") ) + location = FLAGS.location if FLAGS.location else os.getenv("GOOGLE_CLOUD_LOCATION") + bucket = FLAGS.bucket if FLAGS.bucket else os.getenv("GOOGLE_CLOUD_STORAGE_BUCKET") print(f"PROJECT: {project_id}") print(f"LOCATION: {location}") @@ -103,9 +95,7 @@ def main(argv: list[str]) -> None: print("Missing required environment variable: GOOGLE_CLOUD_LOCATION") return elif not bucket: - print( - "Missing required environment variable: GOOGLE_CLOUD_STORAGE_BUCKET" - ) + print("Missing required environment variable: GOOGLE_CLOUD_STORAGE_BUCKET") return vertexai.init( diff --git a/python/agents/medical-pre-authorization/deployment/test_deployment.py b/python/agents/medical-pre-authorization/deployment/test_deployment.py index cc0dd2ddc..3291ccb6c 100644 --- a/python/agents/medical-pre-authorization/deployment/test_deployment.py +++ b/python/agents/medical-pre-authorization/deployment/test_deployment.py @@ -41,18 +41,10 @@ def main(argv: list[str]) -> None: # pylint: disable=unused-argument load_dotenv() project_id = ( - FLAGS.project_id - if FLAGS.project_id - else os.getenv("GOOGLE_CLOUD_PROJECT") - ) - location = ( - FLAGS.location if FLAGS.location else os.getenv("GOOGLE_CLOUD_LOCATION") - ) - bucket = ( - FLAGS.bucket - if FLAGS.bucket - else os.getenv("GOOGLE_CLOUD_STORAGE_BUCKET") + FLAGS.project_id if FLAGS.project_id else os.getenv("GOOGLE_CLOUD_PROJECT") ) + location = FLAGS.location if FLAGS.location else os.getenv("GOOGLE_CLOUD_LOCATION") + bucket = FLAGS.bucket if FLAGS.bucket else os.getenv("GOOGLE_CLOUD_STORAGE_BUCKET") project_id = os.getenv("GOOGLE_CLOUD_PROJECT") location = os.getenv("GOOGLE_CLOUD_LOCATION") @@ -65,9 +57,7 @@ def main(argv: list[str]) -> None: # pylint: disable=unused-argument print("Missing required environment variable: GOOGLE_CLOUD_LOCATION") return elif not bucket: - print( - "Missing required environment variable: GOOGLE_CLOUD_STORAGE_BUCKET" - ) + print("Missing required environment variable: GOOGLE_CLOUD_STORAGE_BUCKET") return vertexai.init( diff --git a/python/agents/medical-pre-authorization/eval/test_eval.py b/python/agents/medical-pre-authorization/eval/test_eval.py index 35bf483f9..f51445bd4 100644 --- a/python/agents/medical-pre-authorization/eval/test_eval.py +++ b/python/agents/medical-pre-authorization/eval/test_eval.py @@ -36,4 +36,3 @@ async def test_all(): str(pathlib.Path(__file__).parent / "data"), num_runs=5, ) - \ No newline at end of file diff --git a/python/agents/medical-pre-authorization/medical_pre_authorization/agent.py b/python/agents/medical-pre-authorization/medical_pre_authorization/agent.py index 773a1fec3..812ecf808 100644 --- a/python/agents/medical-pre-authorization/medical_pre_authorization/agent.py +++ b/python/agents/medical-pre-authorization/medical_pre_authorization/agent.py @@ -13,25 +13,19 @@ # limitations under the License. from google.adk.agents import Agent -from google.genai import types from google.adk.tools.agent_tool import AgentTool +from google.genai import types +from .prompt import AGENT_INSTRUCTION from .subagents.data_analyst import data_analyst from .subagents.information_extractor import information_extractor -from .prompt import AGENT_INSTRUCTION root_agent = Agent( - model='gemini-2.5-flash', - name='root_agent', - description="""As a medical pre-authorization agent, you process user + model="gemini-2.5-flash", + name="root_agent", + description="""As a medical pre-authorization agent, you process user pre-auth request for a treatment.""", - - instruction= AGENT_INSTRUCTION, - - generate_content_config=types.GenerateContentConfig(temperature=0.2), - - tools=[ - AgentTool(agent=information_extractor), - AgentTool(agent=data_analyst) - ], + instruction=AGENT_INSTRUCTION, + generate_content_config=types.GenerateContentConfig(temperature=0.2), + tools=[AgentTool(agent=information_extractor), AgentTool(agent=data_analyst)], ) diff --git a/python/agents/medical-pre-authorization/medical_pre_authorization/prompt.py b/python/agents/medical-pre-authorization/medical_pre_authorization/prompt.py index b0936282b..30ca2e8d6 100644 --- a/python/agents/medical-pre-authorization/medical_pre_authorization/prompt.py +++ b/python/agents/medical-pre-authorization/medical_pre_authorization/prompt.py @@ -14,52 +14,52 @@ AGENT_INSTRUCTION = """ As a medical pre-authorization agent, you process user pre-auth request for - a treatment. + a treatment. Here's a breakdown of your responsibilities: - 1. You will extract relevant insurance details and medical details from - respective documents, specifically for the treatment user is seeking + 1. You will extract relevant insurance details and medical details from + respective documents, specifically for the treatment user is seeking pre-authorization for. - 2. You will analyze the necessity of the treatment based on the extracted - information, then verify user eligibility and coverage under their insurance + 2. You will analyze the necessity of the treatment based on the extracted + information, then verify user eligibility and coverage under their insurance plan. - 3. Finally, you will create a report detailing the decision to accept or + 3. Finally, you will create a report detailing the decision to accept or reject your pre-authorization request. Here's how you should operate: - 1. Start by greeting the user and asking how I can help, providing a quick + 1. Start by greeting the user and asking how I can help, providing a quick overview of what you do. - 2. If the request isn't clear, you will ask some questions to understand + 2. If the request isn't clear, you will ask some questions to understand user needs better. - 3. You will need treatment name and two documents from the user to process - the pre-authorization request: one for their medical records related to the - treatment, and one for their health insurance policy. If these are not - promptly provided, you will explicitly ask the user to provide them, - clarifying which document is which. - 4. Extract the treatment name that user is seeking pre-authorisation for + 3. You will need treatment name and two documents from the user to process + the pre-authorization request: one for their medical records related to the + treatment, and one for their health insurance policy. If these are not + promptly provided, you will explicitly ask the user to provide them, + clarifying which document is which. + 4. Extract the treatment name that user is seeking pre-authorisation for from the user's request using corresponding subagent. - 5. Extract medical details and insurance policy details correspondidng to - the treatment name from the documents provided by the user using + 5. Extract medical details and insurance policy details correspondidng to + the treatment name from the documents provided by the user using corresponding subagent. 6. Next you will require to analyse the extracted content of the documents - and provide a report detailing your decision on pre authorisation request. + and provide a report detailing your decision on pre authorisation request. You will call the corresponding subagent for this task. - 7. Based on the user's intent, determine which sub-agent is best suited to + 7. Based on the user's intent, determine which sub-agent is best suited to handle the request. - Ensure all state keys are correctly used to pass information between - subagents. + Ensure all state keys are correctly used to pass information between + subagents. *************************************************************************** - - Invoke the information_extractor subagent to extract treatment name from - user's request, also to extract details on user's medical records and - insurance coverage for this treatment. The information_extractor subagent - MUST return a comprehensive medical and insurance policy data extracted for + - Invoke the information_extractor subagent to extract treatment name from + user's request, also to extract details on user's medical records and + insurance coverage for this treatment. The information_extractor subagent + MUST return a comprehensive medical and insurance policy data extracted for the specified pre auth request. - Invoke the data_analyst subagent to analyse data provided by information_extractor subagent and create a report detailing your decision on user's pre-authorization - request for the treatment. The data_analyst_agent MUST have decision on - passing or rejecting the pre-auth request, create a report and store it in + request for the treatment. The data_analyst_agent MUST have decision on + passing or rejecting the pre-auth request, create a report and store it in designated path. Invoke the data_analyst subagent only after information_extractor has completed all its tasks. ********************************************************************************** diff --git a/python/agents/medical-pre-authorization/medical_pre_authorization/subagents/data_analyst/__init__.py b/python/agents/medical-pre-authorization/medical_pre_authorization/subagents/data_analyst/__init__.py index b97e06814..b591f60bc 100644 --- a/python/agents/medical-pre-authorization/medical_pre_authorization/subagents/data_analyst/__init__.py +++ b/python/agents/medical-pre-authorization/medical_pre_authorization/subagents/data_analyst/__init__.py @@ -12,4 +12,4 @@ # See the License for the specific language governing permissions and # limitations under the License. -from .agent import data_analyst +from .agent import data_analyst # noqa: F401 diff --git a/python/agents/medical-pre-authorization/medical_pre_authorization/subagents/data_analyst/agent.py b/python/agents/medical-pre-authorization/medical_pre_authorization/subagents/data_analyst/agent.py index 3bf04061b..9c0dcb292 100644 --- a/python/agents/medical-pre-authorization/medical_pre_authorization/subagents/data_analyst/agent.py +++ b/python/agents/medical-pre-authorization/medical_pre_authorization/subagents/data_analyst/agent.py @@ -12,19 +12,19 @@ # See the License for the specific language governing permissions and # limitations under the License. -from google.genai import types from google.adk import Agent +from google.genai import types from .prompt import DATA_ANALYST_INSTRUCTION from .tools.tools import store_pdf data_analyst = Agent( - model='gemini-2.5-flash', - name="data_analyst", - description="""Agent that analyzes the details on user insurance policy and + model="gemini-2.5-flash", + name="data_analyst", + description="""Agent that analyzes the details on user insurance policy and medical necessity for a pre-authorization request and creates a report on the same.""", - instruction= DATA_ANALYST_INSTRUCTION, - generate_content_config=types.GenerateContentConfig(temperature=0.2), - tools=[store_pdf], + instruction=DATA_ANALYST_INSTRUCTION, + generate_content_config=types.GenerateContentConfig(temperature=0.2), + tools=[store_pdf], ) diff --git a/python/agents/medical-pre-authorization/medical_pre_authorization/subagents/data_analyst/prompt.py b/python/agents/medical-pre-authorization/medical_pre_authorization/subagents/data_analyst/prompt.py index 0ea56c0fb..1221f296f 100644 --- a/python/agents/medical-pre-authorization/medical_pre_authorization/subagents/data_analyst/prompt.py +++ b/python/agents/medical-pre-authorization/medical_pre_authorization/subagents/data_analyst/prompt.py @@ -11,87 +11,72 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - -SAMPLE_REPORT=""" +SAMPLE_REPORT = """ *****************************Sample Report Document Template*********** Medical Pre-Authorization Request Report Date of Report: July 19, 2025 - Pre-Authorization for Elective LASIK Surgery (Rejection) Patient Name: Mark Johnson - Treatment Name: Bilateral LASIK Eye Surgery - Insurance Provider: OptiCare Health Plans - Summary of Medical Records: -Patient Mark Johnson seeks LASIK surgery for refractive error correction to -reduce dependence on eyeglasses. Corrected visual acuity is 20/25 in both eyes. -No medical contraindications to continued use of corrective lenses or severe +Patient Mark Johnson seeks LASIK surgery for refractive error correction to +reduce dependence on eyeglasses. Corrected visual acuity is 20/25 in both eyes. +No medical contraindications to continued use of corrective lenses or severe uncorrectable refractive error are noted. - Summary of Insurance Coverage: OptiCare Health Plans policy (Policy ID: LASIK-ELEC-MJ-2024) was reviewed. The policy explicitly categorizes LASIK as an elective/cosmetic procedure. Coverage -is provided only in cases of severe refractive error (e.g., >7.5 diopters) or -documented medical intolerance to traditional corrective lenses +is provided only in cases of severe refractive error (e.g., >7.5 diopters) or +documented medical intolerance to traditional corrective lenses (glasses/contacts). Neither of these criteria is met. - Pre-Authorization Claim Decision: REJECTED -Reason for Rejection: The requested procedure (Bilateral LASIK Eye Surgery) is -categorized as an elective cosmetic procedure under the patient's OptiCare +Reason for Rejection: The requested procedure (Bilateral LASIK Eye Surgery) is +categorized as an elective cosmetic procedure under the patient's OptiCare Health Plans policy and does not meet the strict medical necessity criteria for coverage. """ - DATA_ANALYST_INSTRUCTION = f""" - As an **Information Analysis and Report Generator Agent**, your primary role + As an **Information Analysis and Report Generator Agent**, your primary role is to evaluate pre-authorization requests for medical treatments. - **Here's the process you will follow:** - - 1. **Receive Information:** You will be provided with two sets of crucial + 1. **Receive Information:** You will be provided with two sets of crucial information: - * **User's Insurance Coverage Details:** Information pertaining to the + * **User's Insurance Coverage Details:** Information pertaining to the user's insurance policy and its coverage for the requested treatment. - * **User's Medical Records:** Relevant medical history and details + * **User's Medical Records:** Relevant medical history and details concerning the treatment for which pre-authorization is sought. - 2. **Analyze and Decide:** - * Thoroughly **review and analyze** both the insurance coverage details + * Thoroughly **review and analyze** both the insurance coverage details and the user's medical records. - * Based on this analysis, make a **clear decision** to either **"Pass" + * Based on this analysis, make a **clear decision** to either **"Pass" or "Reject"** the pre-authorization request. - * Formulate a **reason for the decision**, explicitly referencing - relevant information from the patient's medical records and the + * Formulate a **reason for the decision**, explicitly referencing + relevant information from the patient's medical records and the insurance policy eligibility criteria. - 3. **Generate Report Content:** - * Create the **content for a pre-authorization decision report** that + * Create the **content for a pre-authorization decision report** that will be compiled into a PDF file. * The report must include: * **Patient Details:** Essential identifying information about the patient. - * **Treatment Details:** A description of the treatment for which + * **Treatment Details:** A description of the treatment for which pre-authorization was requested. * **Pre-authorization Decision:** Clearly state "Pass" or "Reject." - * **Reason for Decision:** Provide the specific justification for + * **Reason for Decision:** Provide the specific justification for the decision, as determined in the previous step. * **Reference:** Use the provided sample report content as a **structural and formatting reference** for generating this report. - 4. **Upload Document:** - * Once the PDF content is generated, use the `store_pdf` tool to **upload + * Once the PDF content is generated, use the `store_pdf` tool to **upload the content as a PDF file** to the designated Cloud Storage Bucket. - 5. **Confirm to User:** - * After the proposal report document's PDF content has been successfully - created and uploaded to the Cloud Storage Bucket, send a confirmation - message to the user, stating that "The pre-authorization decision report - has been created and uploaded to the Cloud Storage Bucket." Provide the - path of the GCS report location to the user. Prepend - "https://storage.cloud.google.com/" to the path instead of "gs:". + * After the proposal report document's PDF content has been successfully + created and uploaded to the Cloud Storage Bucket, send a confirmation + message to the user, stating that "The pre-authorization decision report + has been created and uploaded to the Cloud Storage Bucket." Provide the + path of the GCS report location to the user. Prepend + "https://storage.cloud.google.com/" to the path instead of "gs:". *Also provide a brief summary of the decision to the user. - 6. Here is a sample report {SAMPLE_REPORT} """ diff --git a/python/agents/medical-pre-authorization/medical_pre_authorization/subagents/data_analyst/tools/tools.py b/python/agents/medical-pre-authorization/medical_pre_authorization/subagents/data_analyst/tools/tools.py index 5906ac737..a0dc19d9f 100644 --- a/python/agents/medical-pre-authorization/medical_pre_authorization/subagents/data_analyst/tools/tools.py +++ b/python/agents/medical-pre-authorization/medical_pre_authorization/subagents/data_analyst/tools/tools.py @@ -12,19 +12,20 @@ # See the License for the specific language governing permissions and # limitations under the License. +import io +import logging +import os +import warnings +from datetime import datetime +from pathlib import Path + +from dotenv import load_dotenv from google.cloud import storage from reportlab.lib.pagesizes import letter from reportlab.lib.styles import getSampleStyleSheet from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer -from datetime import datetime -from dotenv import load_dotenv -from pathlib import Path -import io -import logging -import warnings -import os -env_path = Path(__file__).parent.parent.parent.parent / '.env' +env_path = Path(__file__).parent.parent.parent.parent / ".env" load_dotenv(dotenv_path=env_path) @@ -33,7 +34,8 @@ logger = logging.getLogger(__name__) timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") -REPORT_DOCUMENT_FILE_NAME = f"pre_authorization_report_{timestamp}.pdf" +REPORT_DOCUMENT_FILE_NAME = f"pre_authorization_report_{timestamp}.pdf" + def store_pdf(pdf_text: str) -> str: """Writes text to a PDF file, then uploads it to Google Cloud Storage. @@ -52,9 +54,11 @@ def store_pdf(pdf_text: str) -> str: # Add the text to the story, handling paragraphs and line breaks # We'll split the text by double newlines to treat them as separate paragraphs # and then add each paragraph to the story. - for paragraph_text in pdf_text.split('\n\n'): - if paragraph_text.strip(): - p = Paragraph(paragraph_text.strip().replace('\n', '
'), styles['Normal']) + for paragraph_text in pdf_text.split("\n\n"): + if paragraph_text.strip(): + p = Paragraph( + paragraph_text.strip().replace("\n", "
"), styles["Normal"] + ) story.append(p) # The explicit Spacer line below was removed to reduce excessive blank lines. story.append(Spacer(1, 0.05 * letter[1])) @@ -70,13 +74,14 @@ def store_pdf(pdf_text: str) -> str: blob.upload_from_file(pdf_buffer, content_type="application/pdf") - logger.info(f"Successfully uploaded PDF to gs://{STORAGE_BUCKET}/{REPORT_DOCUMENT_FILE_NAME}") - return (f"Successfully uploaded PDF to gs://{STORAGE_BUCKET}/{REPORT_DOCUMENT_FILE_NAME}") + logger.info( + f"Successfully uploaded PDF to gs://{STORAGE_BUCKET}/{REPORT_DOCUMENT_FILE_NAME}" + ) + return f"Successfully uploaded PDF to gs://{STORAGE_BUCKET}/{REPORT_DOCUMENT_FILE_NAME}" except Exception as e: logger.error(f"Error writing text to PDF and uploading: {e}") raise finally: if pdf_buffer: - pdf_buffer.close() - \ No newline at end of file + pdf_buffer.close() diff --git a/python/agents/medical-pre-authorization/medical_pre_authorization/subagents/information_extractor/__init__.py b/python/agents/medical-pre-authorization/medical_pre_authorization/subagents/information_extractor/__init__.py index 3e260c85a..338be0c47 100644 --- a/python/agents/medical-pre-authorization/medical_pre_authorization/subagents/information_extractor/__init__.py +++ b/python/agents/medical-pre-authorization/medical_pre_authorization/subagents/information_extractor/__init__.py @@ -12,4 +12,4 @@ # See the License for the specific language governing permissions and # limitations under the License. -from .agent import information_extractor +from .agent import information_extractor # noqa: F401 diff --git a/python/agents/medical-pre-authorization/medical_pre_authorization/subagents/information_extractor/agent.py b/python/agents/medical-pre-authorization/medical_pre_authorization/subagents/information_extractor/agent.py index 9066e5a22..8d8592388 100644 --- a/python/agents/medical-pre-authorization/medical_pre_authorization/subagents/information_extractor/agent.py +++ b/python/agents/medical-pre-authorization/medical_pre_authorization/subagents/information_extractor/agent.py @@ -12,25 +12,23 @@ # See the License for the specific language governing permissions and # limitations under the License. -from google import genai from google.adk.agents import Agent from google.genai import types from .prompt import INFORMATION_EXTRACTOR_INSTRUCTION from .tools.tools import ( - extract_treatment_name, - extract_policy_information, extract_medical_details, + extract_policy_information, + extract_treatment_name, ) - -information_extractor= Agent( - model='gemini-2.5-flash', - name="information_extractor", - description="""Agent that extracts the details on user insurance policy and - medical necessity for a pre-authorization request from documents provided +information_extractor = Agent( + model="gemini-2.5-flash", + name="information_extractor", + description="""Agent that extracts the details on user insurance policy and + medical necessity for a pre-authorization request from documents provided by the user.""", - instruction= INFORMATION_EXTRACTOR_INSTRUCTION, - generate_content_config=types.GenerateContentConfig(temperature=0.2), - tools=[extract_treatment_name, extract_policy_information, extract_medical_details], + instruction=INFORMATION_EXTRACTOR_INSTRUCTION, + generate_content_config=types.GenerateContentConfig(temperature=0.2), + tools=[extract_treatment_name, extract_policy_information, extract_medical_details], ) diff --git a/python/agents/medical-pre-authorization/medical_pre_authorization/subagents/information_extractor/prompt.py b/python/agents/medical-pre-authorization/medical_pre_authorization/subagents/information_extractor/prompt.py index 2630e1459..cdbe00ff5 100644 --- a/python/agents/medical-pre-authorization/medical_pre_authorization/subagents/information_extractor/prompt.py +++ b/python/agents/medical-pre-authorization/medical_pre_authorization/subagents/information_extractor/prompt.py @@ -13,7 +13,7 @@ # limitations under the License. INFORMATION_EXTRACTOR_INSTRUCTION = """ - You are a information extractor agent that helps with extracting + You are a information extractor agent that helps with extracting details on treatment name from user request. You also extract policy details and medical test details on that treatment from respective documents provided by the user. You will have below information: diff --git a/python/agents/medical-pre-authorization/medical_pre_authorization/subagents/information_extractor/tools/tools.py b/python/agents/medical-pre-authorization/medical_pre_authorization/subagents/information_extractor/tools/tools.py index 7975e9a5d..5bab484ce 100644 --- a/python/agents/medical-pre-authorization/medical_pre_authorization/subagents/information_extractor/tools/tools.py +++ b/python/agents/medical-pre-authorization/medical_pre_authorization/subagents/information_extractor/tools/tools.py @@ -11,22 +11,17 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +import logging +import os +import warnings +from pathlib import Path -import google.cloud.aiplatform as aiplatform +from dotenv import load_dotenv from google import genai from google.genai import types -from typing import Optional -from dotenv import load_dotenv -from pathlib import Path -import warnings -import os -import logging -import base64 -import fitz -env_path = Path(__file__).parent.parent.parent.parent / '.env' +env_path = Path(__file__).parent.parent.parent.parent / ".env" load_dotenv(dotenv_path=env_path) - warnings.filterwarnings("ignore") GOOGLE_CLOUD_PROJECT = os.getenv("GOOGLE_CLOUD_PROJECT") GOOGLE_CLOUD_LOCATION = os.getenv("GOOGLE_CLOUD_LOCATION") @@ -36,76 +31,60 @@ def extract_treatment_name(user_query: str) -> str: """ Extracts the treatment name from a user query using the Gemini model. - Args: user_query: The user's input query. - Returns: The extracted treatment name, or an empty string if not found. """ # Initialize the Gemini model client = genai.Client( - vertexai=True, - project=GOOGLE_CLOUD_PROJECT, - location=GOOGLE_CLOUD_LOCATION, - ) - + vertexai=True, + project=GOOGLE_CLOUD_PROJECT, + location=GOOGLE_CLOUD_LOCATION, + ) model = "gemini-2.5-flash" - # Construct a prompt for the Gemini model to extract the treatment name si_text = f""" From the following user query, extract only the name of the medical treatment. If no specific treatment is mentioned, respond with "None". - User Query: "{user_query}" - Treatment Name: """ - contents = [ - types.Content( - role="user", - parts=[ - types.Part.from_text(text=user_query) - ] - ), + types.Content(role="user", parts=[types.Part.from_text(text=user_query)]), ] - generate_content_config = types.GenerateContentConfig( - temperature = 1, - top_p = 1, - seed = 0, - max_output_tokens = 65535, - system_instruction=[types.Part.from_text(text=si_text)], - thinking_config=types.ThinkingConfig( - thinking_budget=-1, - ), + temperature=1, + top_p=1, + seed=0, + max_output_tokens=65535, + system_instruction=[types.Part.from_text(text=si_text)], + thinking_config=types.ThinkingConfig( + thinking_budget=-1, + ), ) - generated_text = "" try: # Stream the content generation and concatenate chunks for chunk in client.models.generate_content_stream( - model = model, - contents = contents, - config = generate_content_config, + model=model, + contents=contents, + config=generate_content_config, ): generated_text += chunk.text except Exception as e: print(f"An error occurred during content generation: {e}") return "Error generating response." - return generated_text.strip() + def extract_policy_information(policy_file: str, treatment_name: str) -> str: """ Extracts all information related to a specific treatment from insurance policy pdf using the Gemini model. - Args: policy_file: The full text of the insurance policy. treatment_name: The name of the treatment to find information about. - Returns: Relevant information about the treatment, or a message indicating it's not found. """ @@ -114,51 +93,38 @@ def extract_policy_information(policy_file: str, treatment_name: str) -> str: project=GOOGLE_CLOUD_PROJECT, location=GOOGLE_CLOUD_LOCATION, ) - - # with open(policy_file_path, 'rb') as pdf_file: # pdf_bytes = pdf_file.read() - - - # Define the text part of the prompt - prompt_text = types.Part.from_text(text=f""" + prompt_text = types.Part.from_text( + text=f""" You are an AI assistant specialized in analyzing insurance policy documents. Given the following insurance policy text, extract all details and clauses - specifically related to the medical treatment named \"{treatment_name}"\. + specifically related to the medical treatment named "{treatment_name}". Include information about coverage, exclusions, limits, conditions, and any other relevant terms. - - If \"{treatment_name}"\ is not explicitly mentioned or no information - is found regarding it, state \\\"No specific information found for {treatment_name}. - - Insurance policy text: {policy_file}""") - + If "{treatment_name}" is not explicitly mentioned or no information + is found regarding it, state "No specific information found for {treatment_name}." + Insurance policy text: {policy_file}""" + ) model = "gemini-2.5-flash" contents = [ - types.Content( - role="user", - parts=[ - prompt_text - ] - ), + types.Content(role="user", parts=[prompt_text]), ] - generate_content_config = types.GenerateContentConfig( - temperature = 1, - top_p = 0.95, - max_output_tokens = 65535, + temperature=1, + top_p=0.95, + max_output_tokens=65535, thinking_config=types.ThinkingConfig( thinking_budget=0, ), ) - summary_output = "" # Stream the content generation for chunk in client.models.generate_content_stream( - model = model, - contents = contents, - config = generate_content_config, + model=model, + contents=contents, + config=generate_content_config, ): summary_output += chunk.text return summary_output @@ -168,11 +134,9 @@ def extract_medical_details(medical_report_file: str, treatment_name: str) -> st """ Extracts all information related to a specific treatment from medical report pdf using the Gemini model - Args: medical_report_file (str): The full text of the medical report. treatment_name: The name of the treatment to find information about. - Returns: A summary of the relevant medical details """ client = genai.Client( @@ -180,43 +144,33 @@ def extract_medical_details(medical_report_file: str, treatment_name: str) -> st project=GOOGLE_CLOUD_PROJECT, location=GOOGLE_CLOUD_LOCATION, ) - - # Define the text part of the prompt - prompt_text = types.Part.from_text(text="""You are an AI assistant specialized in analyzing medical reports. - Given the following medical report txt, extract and summarize all relevant medical details specifically - related to the treatment named \"{treatment_name}\". Include information about diagnosis, treatment plans, + prompt_text = types.Part.from_text( + text="""You are an AI assistant specialized in analyzing medical reports. + Given the following medical report txt, extract and summarize all relevant medical details specifically + related to the treatment named \"{treatment_name}\". Include information about diagnosis, treatment plans, medications, procedures, and patient outcomes. If \"{treatment_name}\" is not explicitly mentioned or no information is found regarding it, state \\\"No specific information found for {treatment_name}. - - Medical report text {medical_report_file}""") - - + Medical report text {medical_report_file}""" + ) model = "gemini-2.5-flash" contents = [ - types.Content( - role="user", - parts=[ - prompt_text - ] - ), + types.Content(role="user", parts=[prompt_text]), ] - generate_content_config = types.GenerateContentConfig( - temperature = 1, - top_p = 0.95, - max_output_tokens = 65535, + temperature=1, + top_p=0.95, + max_output_tokens=65535, thinking_config=types.ThinkingConfig( thinking_budget=0, ), ) - summary_output = "" # Stream the content generation for chunk in client.models.generate_content_stream( - model = model, - contents = contents, - config = generate_content_config, + model=model, + contents=contents, + config=generate_content_config, ): summary_output += chunk.text return summary_output diff --git a/python/agents/medical-pre-authorization/tests/test_agents.py b/python/agents/medical-pre-authorization/tests/test_agents.py index 870b5c934..55553f9b6 100644 --- a/python/agents/medical-pre-authorization/tests/test_agents.py +++ b/python/agents/medical-pre-authorization/tests/test_agents.py @@ -18,9 +18,9 @@ import dotenv import pytest -from medical_pre_authorization.agent import root_agent from google.adk.runners import InMemoryRunner from google.genai.types import Part, UserContent +from medical_pre_authorization.agent import root_agent pytest_plugins = ("pytest_asyncio",) @@ -59,4 +59,3 @@ async def test_happy_path(): # The answer in the input is wrong, so we expect the agent to provided a # revised answer, and the correct answer should mention research. assert "pre-authorization agent" in response.lower() - \ No newline at end of file