On this tutorial, we devise tips on how to orchestrate a completely practical, tool-using medical prior-authorization agent powered by Gemini. We stroll by every element step-by-step, from securely configuring the mannequin to constructing real looking exterior instruments and at last establishing an clever agent loop that causes, acts, and responds totally by structured JSON. As we progress, we see how the system thinks, retrieves proof, and interacts with simulated medical techniques to finish a posh workflow. Try the FULL CODES right here.
!pip set up -q -U google-generative-ai
import google.generativeai as genai
from google.colab import userdata
import os
import getpass
import json
import time
attempt:
GOOGLE_API_KEY = userdata.get('GOOGLE_API_KEY')
besides:
print("Please enter your Google API Key:")
GOOGLE_API_KEY = getpass.getpass("API Key: ")
genai.configure(api_key=GOOGLE_API_KEY)
print("n🔍 Scanning for out there fashions...")
available_models = [m.name for m in genai.list_models()]
target_model = ""
if 'fashions/gemini-1.5-flash' in available_models:
target_model="gemini-1.5-flash"
elif 'fashions/gemini-1.5-flash-001' in available_models:
target_model="gemini-1.5-flash-001"
elif 'fashions/gemini-pro' in available_models:
target_model="gemini-pro"
else:
for m in available_models:
if 'generateContent' in genai.get_model(m).supported_generation_methods:
target_model = m
break
if not target_model:
elevate ValueError("❌ No textual content era fashions discovered for this API key.")
print(f"✅ Chosen Mannequin: {target_model}")
mannequin = genai.GenerativeModel(target_model)
We arrange our surroundings and routinely detect the perfect out there Gemini mannequin. We configure the API key securely and let the system select essentially the most succesful mannequin with out hardcoding something. This ensures that we begin the tutorial with a clear, versatile, and dependable basis. Try the FULL CODES right here.
class MedicalTools:
def __init__(self):
self.ehr_docs = [
"Patient: John Doe | DOB: 1980-05-12",
"Visit 2023-01-10: Diagnosed with Type 2 Diabetes. Prescribed Metformin.",
"Visit 2023-04-15: Patient reports severe GI distress with Metformin. Discontinued.",
"Visit 2023-04-20: BMI recorded at 32.5. A1C is 8.4%.",
"Visit 2023-05-01: Doctor recommends starting Ozempic (Semaglutide)."
]
def search_ehr(self, question):
print(f" 🔎 [Tool] Looking EHR for: '{question}'...")
outcomes = [doc for doc in self.ehr_docs if any(q.lower() in doc.lower() for q in query.split())]
if not outcomes:
return "No data discovered."
return "n".be a part of(outcomes)
def submit_prior_auth(self, drug_name, justification):
print(f" 📤 [Tool] Submitting declare for {drug_name}...")
justification_lower = justification.decrease()
if "metformin" in justification_lower and ("discontinued" in justification_lower or "intolerance" in justification_lower):
if "bmi" in justification_lower and "32" in justification_lower:
return "SUCCESS: Authorization Accepted. Auth ID: #998877"
return "DENIED: Coverage requires proof of (1) Metformin failure and (2) BMI > 30."
We outline the medical instruments that our agent can use through the workflow. We simulate an EHR search and a prior-authorization submission system so the agent has actual actions to carry out. By doing this, we floor the agent’s reasoning in tool-enabled interactions fairly than plain textual content era. Try the FULL CODES right here.
class AgenticSystem:
def __init__(self, mannequin, instruments):
self.mannequin = mannequin
self.instruments = instruments
self.historical past = []
self.max_steps = 6
self.system_prompt = """
You're an skilled Medical Prior Authorization Agent.
Your aim is to get approval for a medical process/drug.
You've got entry to those instruments:
1. search_ehr(question)
2. submit_prior_auth(drug_name, justification)
RULES:
1. ALWAYS suppose earlier than you act.
2. You MUST output your response in STRICT JSON format:
{
"thought": "Your reasoning right here",
"motion": "tool_name_or_finish",
"action_input": "argument_string_or_dict"
}
3. Don't guess affected person information. Use 'search_ehr'.
4. When you've got the proof, use 'submit_prior_auth'.
5. If the duty is completed, use motion "end".
"""
We initialize the agent and supply its full system immediate. We outline the principles, the JSON response format, and the expectation that the agent should suppose earlier than appearing. This offers us a managed, deterministic construction for constructing a secure and traceable agent loop. Try the FULL CODES right here.
def execute_tool(self, action_name, action_input):
if action_name == "search_ehr":
return self.instruments.search_ehr(action_input)
elif action_name == "submit_prior_auth":
if isinstance(action_input, str):
return "Error: submit_prior_auth requires a dictionary."
return self.instruments.submit_prior_auth(**action_input)
else:
return "Error: Unknown device."
def run(self, goal):
print(f"🤖 AGENT STARTING. Goal: {goal}n" + "-"*50)
self.historical past.append(f"Person: {goal}")
for i in vary(self.max_steps):
print(f"n🔄 STEP {i+1}")
immediate = self.system_prompt + "nnHistory:n" + "n".be a part of(self.historical past) + "nnNext JSON:"
attempt:
response = self.mannequin.generate_content(immediate)
text_response = response.textual content.strip().exchange("```json", "").exchange("```", "")
agent_decision = json.hundreds(text_response)
besides Exception as e:
print(f" ⚠️ Error parsing AI response. Retrying... ({e})")
proceed
print(f" 🧠 THOUGHT: {agent_decision['thought']}")
print(f" 👉 ACTION: {agent_decision['action']}")
if agent_decision['action'] == "end":
print(f"n✅ TASK COMPLETED: {agent_decision['action_input']}")
break
tool_result = self.execute_tool(agent_decision['action'], agent_decision['action_input'])
print(f" 👁️ OBSERVATION: {tool_result}")
self.historical past.append(f"Assistant: {text_response}")
self.historical past.append(f"System: {tool_result}")
if "SUCCESS" in str(tool_result):
print("n🎉 SUCCESS! The Agent efficiently navigated the insurance coverage portal.")
break
We implement the core agent loop the place reasoning, device execution, and observations occur step-by-step. We watch the agent resolve its subsequent motion, execute instruments, replace historical past, and consider success circumstances. That is the place the agent actually comes alive and performs iterative reasoning. Try the FULL CODES right here.
tools_instance = MedicalTools()
agent = AgenticSystem(mannequin, tools_instance)
agent.run("Please get prior authorization for Ozempic for affected person John Doe.")
We instantiate the instruments and agent, then run all the system end-to-end with an actual goal. We see the complete workflow unfold because the agent navigates by medical historical past, validates proof, and makes an attempt prior authorization. This remaining snippet demonstrates the whole pipeline working seamlessly.
In conclusion, we mirror on how this compact but highly effective framework allows us to design real-world agentic behaviors that transcend easy textual content responses. We watch our agent plan, seek the advice of instruments, collect proof, and in the end full a structured insurance coverage authorization process, totally by autonomous reasoning. It gives confidence that we will now develop the system with extra instruments, stronger insurance policies, domain-specific logic, and even multi-agent collaboration.
Try the FULL CODES right here. Be happy to take a look at our GitHub Web page for Tutorials, Codes and Notebooks. Additionally, be at liberty to comply with us on Twitter and don’t overlook to affix our 100k+ ML SubReddit and Subscribe to our Publication.
Asif Razzaq is the CEO of Marktechpost Media Inc.. As a visionary entrepreneur and engineer, Asif is dedicated to harnessing the potential of Synthetic Intelligence for social good. His most up-to-date endeavor is the launch of an Synthetic Intelligence Media Platform, Marktechpost, which stands out for its in-depth protection of machine studying and deep studying information that’s each technically sound and simply comprehensible by a large viewers. The platform boasts of over 2 million month-to-month views, illustrating its recognition amongst audiences.
