A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.
feat: add Offline Medical Agent
cyberholicsa82e4f445324
diff --git a/README.md b/README.mdindex 5fdefa4..a0bc967 100644--- a/README.md+++ b/README.md@@ -70,6 +70,7 @@ Intelligent ai agents for various automation tasks.- [**LangChain Data Agent**](./ai_agents/langchain_data_agent) - Query the Chinook SQLite database in plain English through a conversational Streamlit chat interface.- [**Travel Planner Agent**](./ai_agents/travel_planner_agent) - AI trip planning assistant covering weather, budget, packing lists, and day-by-day itineraries from a single request.- [**Personal Finance Agent**](./ai_agents/personal_finance_agent) - Upload a bank statement CSV, auto-categorize transactions, and ask natural language questions about your spending. Powered by a LangChain tool-calling agent backed by Orq.ai with SQLite persistence.+- [**Offline Medical Agent**](./ai_agents/offline_medical_agent) - Fully offline agentic RAG system for clinical protocol lookup at remote clinics and field hospitals.### 📸 OCRdiff --git a/ai_agents/offline_medical_agent/.env.example b/ai_agents/offline_medical_agent/.env.examplenew file mode 100644index 0000000..e09ccfa--- /dev/null+++ b/ai_agents/offline_medical_agent/.env.example@@ -0,0 +1,3 @@+# Optional: HuggingFace token for downloading models+# Not required for public models like Ministral 3B GGUF+# HF_TOKEN=your_token_herediff --git a/ai_agents/offline_medical_agent/.python-version b/ai_agents/offline_medical_agent/.python-versionnew file mode 100644index 0000000..2c07333--- /dev/null+++ b/ai_agents/offline_medical_agent/.python-version@@ -0,0 +1 @@+3.11diff --git a/ai_agents/offline_medical_agent/README.md b/ai_agents/offline_medical_agent/README.mdnew file mode 100644index 0000000..d395f11--- /dev/null+++ b/ai_agents/offline_medical_agent/README.md@@ -0,0 +1,135 @@+# Offline Medical Agent++> A fully offline agentic RAG system for clinical protocol lookup at remote clinics, field hospitals, and disaster response units. No internet required at runtime.++## Demo++++## Overview++Offline Medical Agent is a two-agent pipeline built for medical personnel operating at edge sites with no internet access. A local vector database is pre-loaded with facility-specific clinical protocols covering drug dosages, emergency procedures, and treatment guidelines.++When a clinician describes a patient situation, a **Retrieval Agent** queries the local database using semantic search to find the single most relevant protocol. A **Protocol Agent** then feeds that grounded context to the local language model and generates a concise, actionable response based strictly on the retrieved protocol, without hallucinating outside it.++All inference and retrieval happen entirely on-device.++## Features++- Fully offline after first-run model download+- Two-agent pipeline: semantic retrieval followed by grounded generation+- Ministral 3 3B (Q4_K_M GGUF) via llama-cpp-python, auto-detects GPU (CUDA, Metal) and falls back to CPU+- SentenceTransformers all-MiniLM-L6-v2 for fast local embeddings+- Qdrant local vector database, no server process required+- Five pre-loaded clinical protocols: pediatric fever, anaphylaxis, oral rehydration, wound care, malaria+- Add your own protocols by dropping `.md` or `.txt` files into the `protocols/` folder+- Gradio web UI with example queries++## Prerequisites++- Python 3.9 or higher+- [UV](https://docs.astral.sh/uv/) package manager+- Internet access on first run only (to download the model and embedding weights)++### Platform-specific install for llama-cpp-python++llama-cpp-python must be built with the right backend for your hardware.++**CPU only (any machine)**+```bash+pip install llama-cpp-python+```++**NVIDIA GPU (CUDA)**+```bash+CMAKE_ARGS="-DGGML_CUDA=on" pip install llama-cpp-python+```++**Apple Silicon (Metal)**+```bash+CMAKE_ARGS="-DGGML_METAL=on" pip install llama-cpp-python+```++**AMD GPU (ROCm)**+```bash+CMAKE_ARGS="-DGGML_HIPBLAS=on" pip install llama-cpp-python+```++## Setup++```bash+# Clone the repo+git clone https://github.com/Sumanth077/Hands-On-AI-Engineering.git+cd Hands-On-AI-Engineering/ai_agents/offline_medical_agent++# Install llama-cpp-python first using the command above for your hardware, then install the rest+pip install -r requirements.txt++# Run+python app.py+```++On first run the app will:+1. Download Ministral 3 3B Q4_K_M GGUF from HuggingFace (~2 GB) and cache it locally.+2. Download the all-MiniLM-L6-v2 embedding model (~90 MB) and cache it locally.+3. Ingest the five bundled clinical protocols into a local Qdrant database.++Subsequent runs are fully offline.++## Usage++Open the Gradio interface at `http://localhost:7860` and describe a patient situation in plain language. The agent will retrieve the most relevant protocol and generate a grounded clinical response.++To add your own protocols, place `.md` or `.txt` files in the `protocols/` folder and click **Re-load Protocols** in the UI.++## Protocols Directory++The `protocols/` folder is the agent's knowledge base. Every `.md` or `.txt` file in it gets loaded, embedded, and stored in the local Qdrant database when the app starts. When a clinician submits a query, the Retrieval Agent searches this database semantically to find the most relevant protocol, which the Protocol Agent then uses as its sole source of truth.++Five protocols are bundled out of the box:++| File | Contents |+|---|---|+| `pediatric_fever.md` | Fever assessment and antipyretic dosing for children under 5 |+| `anaphylaxis.md` | Adrenaline dosing, airway management, and monitoring for anaphylaxis |+| `oral_rehydration.md` | WHO ORT Plans A, B, and C for dehydration from diarrhoea |+| `wound_care.md` | Wound irrigation, closure, tetanus prophylaxis, and antibiotic guidance |+| `malaria_rdt_treatment.md` | RDT interpretation, AL dosing, and severe malaria emergency management |++### Extending the Agent++The quickest way to make this agent more capable is to add more protocol files. Drop any `.md` or `.txt` file into `protocols/` and click **Re-load Protocols** in the UI. The new content is embedded and searchable immediately, no code changes needed.++Some ideas for what to add:++- Obstetric emergencies (postpartum haemorrhage, eclampsia)+- Neonatal resuscitation+- Burn management+- Snakebite and envenomation+- Sepsis and shock recognition+- Facility-specific drug formulary++The agent has no hardcoded topic limit. The more protocols you add, the better its retrieval coverage. For best results, write each protocol as a single focused document covering one condition or procedure. Mixing multiple unrelated topics in one file will reduce retrieval precision since the entire file gets embedded as a single vector.++## Model++**Ministral 3 3B** (lmstudio-community/Ministral-3-3B-Instruct-2512-GGUF, Q4_K_M)+- 3.4B parameters, ~2 GB on disk+- Native function calling and JSON output+- 256K context window+- Apache 2.0 license+- Runs on any hardware: NVIDIA, Apple Silicon, or CPU-only++## Tech Stack++| Component | Library |+|---|---|+| Local inference | llama-cpp-python |+| Language model | Ministral 3 3B (Q4_K_M GGUF) |+| Embeddings | SentenceTransformers all-MiniLM-L6-v2 |+| Vector database | Qdrant (local file mode) |+| UI | Gradio |++## Disclaimer++This tool is intended to support, not replace, qualified clinical judgment. Always verify responses against official clinical guidelines and apply professional discretion, especially in emergencies.diff --git a/ai_agents/offline_medical_agent/app.py b/ai_agents/offline_medical_agent/app.pynew file mode 100644index 0000000..2c6d0a2--- /dev/null+++ b/ai_agents/offline_medical_agent/app.py@@ -0,0 +1,118 @@+"""+Offline Medical Agent - Gradio UI.+All inference and retrieval happen locally. No internet required after first setup.+"""++import gradio as gr++from offline_medical_agent.agents import OfflineMedicalAgent+from offline_medical_agent.retriever import ProtocolRetriever++PROTOCOLS_DIR = "./protocols"+DB_PATH = "./qdrant_data"++# ---------------------------------------------------------------------------+# Initialise agent (loads model + auto-ingests protocols on first run)+# ---------------------------------------------------------------------------++print("Initialising Offline Medical Agent...")+agent = OfflineMedicalAgent(db_path=DB_PATH, protocols_dir=PROTOCOLS_DIR)+++# ---------------------------------------------------------------------------+# Handlers+# ---------------------------------------------------------------------------++def query_agent(situation: str):+ if not situation.strip():+ return "", "", "", ""++ result = agent.run(situation)++ response = result["response"]+ protocol_info = (+ f"**{result['protocol_title']}** "+ f"(source: `{result['source']}` | relevance score: `{result['score']}`)\n\n"+ f"{result['protocol_content']}"+ if result["protocol_title"]+ else "No protocol retrieved."+ )+ return response, protocol_info+++def reload_protocols():+ retriever = ProtocolRetriever(db_path=DB_PATH)+ n = retriever.ingest(PROTOCOLS_DIR)+ return f"Loaded {n} protocol(s) from `{PROTOCOLS_DIR}`."+++# ---------------------------------------------------------------------------+# UI+# ---------------------------------------------------------------------------++with gr.Blocks(title="Offline Medical Agent", theme=gr.themes.Soft()) as demo:++ gr.Markdown("# Offline Medical Agent")+ gr.Markdown(+ "> **Clinical decision support for resource-limited, offline environments.** \n"+ "> Responses are grounded strictly in the retrieved protocol. "+ "Always apply professional clinical judgment. This tool does not replace it."+ )++ gr.Markdown("---")++ with gr.Row():+ with gr.Column(scale=2):+ situation_input = gr.Textbox(+ label="Patient Situation",+ placeholder="e.g. 8-year-old child with fever of 39.2°C, drinking well, no danger signs...",+ lines=5,+ )+ submit_btn = gr.Button("Get Clinical Guidance", variant="primary")++ with gr.Column(scale=1):+ gr.Markdown("### Protocol Library")+ reload_btn = gr.Button("Re-load Protocols", variant="secondary")+ reload_status = gr.Markdown("")++ gr.Markdown("---")++ gr.Markdown("### Clinical Guidance")+ response_output = gr.Markdown()++ with gr.Accordion("Retrieved Protocol", open=False):+ protocol_output = gr.Markdown("")++ # ------------------------------------------------------------------+ # Example queries+ # ------------------------------------------------------------------+ gr.Markdown("### Example Queries")+ gr.Examples(+ examples=[+ ["Child 4 years old, temperature 38.8°C, crying but alert, drinking fluids, no rash or stiff neck. What antipyretic and dose?"],+ ["Adult patient collapsed, hives across chest and arms, wheezing, BP 80/50 after eating peanuts. What do I do immediately?"],+ ["3-year-old with 3 days of watery diarrhoea, sunken eyes, drinking eagerly, skin pinch returns in 1 second. Plan?"],+ ["Machete laceration to forearm, 4 cm long, occurred 2 hours ago, bleeding controlled, clean wound. How do I manage this?"],+ ["Adult male, fever for 3 days, chills, headache, in malaria-endemic region, RDT Pf positive. Treatment?"],+ ],+ inputs=[situation_input],+ )++ # ------------------------------------------------------------------+ # Events+ # ------------------------------------------------------------------+ submit_btn.click(+ fn=query_agent,+ inputs=[situation_input],+ outputs=[response_output, protocol_output],+ )+ situation_input.submit(+ fn=query_agent,+ inputs=[situation_input],+ outputs=[response_output, protocol_output],+ )+ reload_btn.click(fn=reload_protocols, outputs=[reload_status])+++if __name__ == "__main__":+ demo.launch()diff --git a/ai_agents/offline_medical_agent/assets/demo.gif b/ai_agents/offline_medical_agent/assets/demo.gifnew file mode 100644index 0000000..d27844cBinary files /dev/null and b/ai_agents/offline_medical_agent/assets/demo.gif differdiff --git a/ai_agents/offline_medical_agent/offline_medical_agent/__init__.py b/ai_agents/offline_medical_agent/offline_medical_agent/__init__.pynew file mode 100644index 0000000..6df2a10--- /dev/null+++ b/ai_agents/offline_medical_agent/offline_medical_agent/__init__.py@@ -0,0 +1,4 @@+from .agents import OfflineMedicalAgent+from .retriever import ProtocolRetriever++__all__ = ["OfflineMedicalAgent", "ProtocolRetriever"]diff --git a/ai_agents/offline_medical_agent/offline_medical_agent/agents.py b/ai_agents/offline_medical_agent/offline_medical_agent/agents.pynew file mode 100644index 0000000..2709c79--- /dev/null+++ b/ai_agents/offline_medical_agent/offline_medical_agent/agents.py@@ -0,0 +1,134 @@+"""+Two-agent pipeline.++Retrieval Agent - semantic search over local Qdrant to find the single+ most relevant clinical protocol.+Protocol Agent - feeds the retrieved protocol as grounded context to the+ local LLM and generates a concise, actionable response.+ Strictly forbidden from hallucinating outside the protocol.+"""++from __future__ import annotations++from llama_cpp import Llama++from offline_medical_agent.retriever import ProtocolRetriever++MODEL_REPO_ID = "lmstudio-community/Ministral-3-3B-Instruct-2512-GGUF"+MODEL_FILENAME = "Ministral-3-3B-Instruct-2512-Q4_K_M.gguf"++PROTOCOL_AGENT_SYSTEM = """You are a clinical decision support assistant deployed at a remote, \+offline medical facility.++STRICT RULES - read carefully before responding:+1. Base your answer EXCLUSIVELY on the protocol text provided in the user message.+2. Do NOT add drug dosages, procedures, or recommendations not present in the protocol.+3. If the protocol does not fully address the situation, say so explicitly and quote the \+relevant section instead of guessing.+4. Be concise and actionable. Clinicians need clear guidance, not lengthy disclaimers.+5. Structure your response as: Assessment, Immediate Actions, and Follow-up (when applicable).+"""+++class OfflineMedicalAgent:+ def __init__(+ self,+ db_path: str = "./qdrant_data",+ protocols_dir: str = "./protocols",+ repo_id: str = MODEL_REPO_ID,+ filename: str = MODEL_FILENAME,+ ):+ self.retriever = ProtocolRetriever(db_path=db_path)+ if not self.retriever.is_populated():+ print("Ingesting protocols...")+ n = self.retriever.ingest(protocols_dir)+ print(f"Loaded {n} protocol(s) into local database.")++ print("Loading language model, this may take a moment on first run...")+ self.llm = Llama.from_pretrained(+ repo_id=repo_id,+ filename=filename,+ n_ctx=4096,+ n_gpu_layers=-1,+ verbose=False,+ )+ print("Model ready.")++ # ------------------------------------------------------------------+ # Retrieval Agent+ # ------------------------------------------------------------------++ def retrieval_agent(self, query: str) -> dict | None:+ """Return the single most relevant protocol or None if DB is empty."""+ results = self.retriever.retrieve(query, top_k=1)+ if not results:+ return None+ hit = results[0]+ return {+ "title": hit.payload["title"],+ "content": hit.payload["content"],+ "source": hit.payload["source"],+ "score": round(hit.score, 3),+ }++ # ------------------------------------------------------------------+ # Protocol Agent+ # ------------------------------------------------------------------++ def protocol_agent(self, query: str, protocol: dict) -> str:+ """Generate a grounded response from the retrieved protocol."""+ user_message = (+ f"Patient situation: {query}\n\n"+ f"Retrieved protocol: {protocol['title']}\n"+ f"{'=' * 60}\n"+ f"{protocol['content']}\n"+ f"{'=' * 60}\n\n"+ "Based strictly on the protocol above, provide a concise clinical response."+ )+ result = self.llm.create_chat_completion(+ messages=[+ {"role": "system", "content": PROTOCOL_AGENT_SYSTEM},+ {"role": "user", "content": user_message},+ ],+ max_tokens=600,+ temperature=0.1,+ repeat_penalty=1.1,+ )+ return result["choices"][0]["message"]["content"].strip()++ # ------------------------------------------------------------------+ # Full pipeline+ # ------------------------------------------------------------------++ def run(self, query: str) -> dict:+ """+ Run both agents and return a result dict with keys:+ response, protocol_title, protocol_content, source, score+ """+ if not query.strip():+ return {+ "response": "Please describe the patient situation.",+ "protocol_title": "",+ "protocol_content": "",+ "source": "",+ "score": 0.0,+ }++ protocol = self.retrieval_agent(query)+ if protocol is None:+ return {+ "response": "No protocols loaded. Use the 'Load Protocols' button first.",+ "protocol_title": "",+ "protocol_content": "",+ "source": "",+ "score": 0.0,+ }++ response = self.protocol_agent(query, protocol)+ return {+ "response": response,+ "protocol_title": protocol["title"],+ "protocol_content": protocol["content"],+ "source": protocol["source"],+ "score": protocol["score"],+ }diff --git a/ai_agents/offline_medical_agent/offline_medical_agent/retriever.py b/ai_agents/offline_medical_agent/offline_medical_agent/retriever.pynew file mode 100644index 0000000..ae5d708--- /dev/null+++ b/ai_agents/offline_medical_agent/offline_medical_agent/retriever.py@@ -0,0 +1,85 @@+"""+Protocol retriever.+Embeds clinical protocol documents with SentenceTransformers+and stores / queries them in a local Qdrant collection.+"""++import glob+import os++from qdrant_client import QdrantClient+from qdrant_client.models import Distance, PointStruct, VectorParams+from sentence_transformers import SentenceTransformer++COLLECTION_NAME = "clinical_protocols"+EMBEDDING_MODEL = "all-MiniLM-L6-v2"+VECTOR_DIM = 384+++class ProtocolRetriever:+ def __init__(self, db_path: str = "./qdrant_data"):+ self.client = QdrantClient(path=db_path)+ self.embedder = SentenceTransformer(EMBEDDING_MODEL)+ self._ensure_collection()++ def _ensure_collection(self):+ existing = [c.name for c in self.client.get_collections().collections]+ if COLLECTION_NAME not in existing:+ self.client.create_collection(+ collection_name=COLLECTION_NAME,+ vectors_config=VectorParams(size=VECTOR_DIM, distance=Distance.COSINE),+ )++ def ingest(self, protocols_dir: str = "./protocols") -> int:+ """+ Load every .md and .txt file in protocols_dir into Qdrant.+ Wipes any existing entries first so re-ingestion is idempotent.+ """+ files = sorted(+ glob.glob(os.path.join(protocols_dir, "*.md"))+ + glob.glob(os.path.join(protocols_dir, "*.txt"))+ )+ if not files:+ return 0++ self.client.delete_collection(COLLECTION_NAME)+ self._ensure_collection()++ points = []+ for idx, filepath in enumerate(files):+ with open(filepath, "r", encoding="utf-8") as f:+ content = f.read().strip()++ title = (+ os.path.splitext(os.path.basename(filepath))[0]+ .replace("_", " ")+ .title()+ )+ vector = self.embedder.encode(content, show_progress_bar=False).tolist()+ points.append(+ PointStruct(+ id=idx,+ vector=vector,+ payload={+ "title": title,+ "content": content,+ "source": os.path.basename(filepath),+ },+ )+ )++ self.client.upsert(collection_name=COLLECTION_NAME, points=points)+ return len(points)++ def retrieve(self, query: str, top_k: int = 1) -> list:+ """Return the top_k most semantically similar protocols."""+ vector = self.embedder.encode(query, show_progress_bar=False).tolist()+ result = self.client.query_points(+ collection_name=COLLECTION_NAME,+ query=vector,+ limit=top_k,+ )+ return result.points++ def is_populated(self) -> bool:+ return self.client.count(collection_name=COLLECTION_NAME).count > 0diff --git a/ai_agents/offline_medical_agent/protocols/anaphylaxis.md b/ai_agents/offline_medical_agent/protocols/anaphylaxis.mdnew file mode 100644index 0000000..b56ba59--- /dev/null+++ b/ai_agents/offline_medical_agent/protocols/anaphylaxis.md@@ -0,0 +1,67 @@+# Anaphylaxis Emergency Protocol++## Definition+Anaphylaxis is a severe, life-threatening systemic hypersensitivity reaction. Onset is typically within minutes of exposure to a trigger (medications, insect stings, food, latex).++## Recognition — Suspect Anaphylaxis If:+Sudden onset (minutes to 2 hours) involving skin/mucosa PLUS at least one of:+- Respiratory compromise (wheeze, stridor, dyspnoea, SpO2 < 92%)+- Cardiovascular collapse (hypotension, syncope, tachycardia)++OR two or more of the following after exposure to a likely allergen:+- Urticaria, pruritis, flushing, or angioedema+- Vomiting, abdominal cramps, diarrhoea+- Bronchospasm or upper airway obstruction+- Hypotension or end-organ dysfunction++## Immediate Actions (perform simultaneously)++### 1. Call for help+Alert all available clinical staff immediately.++### 2. Adrenaline (Epinephrine) — FIRST-LINE, give immediately+- Route: Intramuscular (IM) injection into the anterolateral mid-thigh.+- Adult dose: 0.5 mg (0.5 ml of 1:1000 adrenaline).+- Child dose: 0.01 mg/kg IM (max 0.5 mg). Practical guide:+ - < 6 years: 0.15 mg (0.15 ml of 1:1000)+ - 6-12 years: 0.3 mg (0.3 ml of 1:1000)+ - > 12 years: 0.5 mg (0.5 ml of 1:1000)+- Repeat every 5 minutes if no improvement. Most patients require 1-2 doses.++### 3. Position+- Lay patient flat with legs elevated (unless breathing is compromised — then sit up).+- Do NOT allow patient to stand or walk.++### 4. High-flow oxygen+- Apply 10-15 L/min via non-rebreather mask immediately.++### 5. IV access+- Establish large-bore IV access (two lines if possible).+- IV fluid bolus: 500-1000 ml 0.9% sodium chloride (adult); 10-20 ml/kg (child). Repeat if hypotension persists.++## Secondary Treatments (after adrenaline)++### Antihistamine (H1 blocker) — adjunct only, do NOT give instead of adrenaline+- Chlorphenamine: Adult 10 mg IV/IM; Child 0.1 mg/kg IV/IM.+- Relieves urticaria and pruritus but does NOT prevent or treat airway obstruction or shock.++### Hydrocortisone — adjunct to prevent biphasic reaction+- Adult: 200 mg IV/IM.+- Child: 50-100 mg IV/IM (2.5 mg/kg up to 100 mg).+- Onset is delayed (4-6 hours); give after adrenaline.++### Bronchodilator (for persistent bronchospasm)+- Salbutamol nebulised: 2.5-5 mg (adult), 2.5 mg (child < 25 kg) via nebuliser.++## Monitoring+- Continuous: pulse, BP, respiratory rate, SpO2, level of consciousness.+- Monitor for minimum 6 hours after adrenaline (biphasic reactions can occur 1-72 hours later).+- 12-24 hours observation if severe reaction or biphasic history.++## Referral / Transfer+Transfer to a higher-level facility if:+- More than 2 doses of adrenaline required.+- Refractory hypotension or bronchospasm.+- Airway compromise requiring intubation.+- Biphasic reaction.+- All children with anaphylaxis should be transferred after stabilisation.diff --git a/ai_agents/offline_medical_agent/protocols/malaria_rdt_treatment.md b/ai_agents/offline_medical_agent/protocols/malaria_rdt_treatment.mdnew file mode 100644index 0000000..3c293a6--- /dev/null+++ b/ai_agents/offline_medical_agent/protocols/malaria_rdt_treatment.md@@ -0,0 +1,79 @@+# Malaria RDT Testing and Treatment Protocol++## Indications for Testing+Test all patients with fever (>= 37.5°C) or history of fever in the past 48 hours in a malaria-endemic area. Do not treat empirically without a confirmed test result.++## Rapid Diagnostic Test (RDT) Procedure+1. Collect 5 µl finger-prick capillary blood using provided lancet.+2. Apply blood to the sample well using the provided loop or pipette.+3. Add 5 drops of assay buffer to the buffer well.+4. Read result at 15-20 minutes. Do NOT read after 30 minutes.+5. Interpreting results:+ - Negative: Only control line (C) visible.+ - Pf positive (P. falciparum): Control line + Pf test line visible.+ - Pan positive (non-falciparum): Control line + Pan test line visible.+ - Invalid: No control line — repeat with new RDT.++## Treatment by Species++### Uncomplicated P. falciparum malaria (RDT Pf positive)+First-line: Artemether-lumefantrine (AL)+- Weight-based dosing — give twice daily for 3 days:+ - 5-14 kg: 1 tablet (20 mg / 120 mg) per dose.+ - 15-24 kg: 2 tablets per dose.+ - 25-34 kg: 3 tablets per dose.+ - >= 35 kg: 4 tablets per dose.+- Give with food or full-fat milk to ensure absorption.+- If vomiting within 30 minutes of dose, repeat dose.++### Non-falciparum malaria (RDT Pan positive)+First-line (P. vivax or P. ovale): Chloroquine+- Day 1: 10 mg/kg base (max 600 mg).+- Day 2: 10 mg/kg base (max 600 mg).+- Day 3: 5 mg/kg base (max 300 mg).+- Primaquine for radical cure (P. vivax relapse prevention): 0.25 mg/kg/day for 14 days.+ - Do NOT give primaquine without G6PD screening — causes haemolysis in G6PD-deficient patients.+ - Do NOT give primaquine in pregnancy.++### RDT Negative with strong clinical suspicion+- If RDT negative but patient has high fever, chills, headache, and epidemiological exposure:+ - Treat for uncomplicated falciparum malaria while arranging blood film microscopy.+ - Document reason for treating RDT-negative patient.++## Severe Malaria — Recognition and Emergency Management++### Suspect severe malaria if any of:+- Impaired consciousness or coma (Blantyre/GCS < 11).+- Respiratory distress (deep breathing / acidosis).+- Severe anaemia (Hb < 7 g/dl or severe pallor).+- Hypoglycaemia (blood glucose < 2.2 mmol/L or < 40 mg/dL).+- Haemoglobinuria (dark/black urine).+- Repeated convulsions (> 2 in 24 hours).+- Prostration (unable to sit/stand unaided).+- Jaundice with evidence of vital organ dysfunction.++### Immediate actions for severe malaria+1. Establish IV/IO access.+2. Check blood glucose: if < 2.2 mmol/L, give 10% dextrose 5 ml/kg IV (child) or 50 ml of 50% dextrose IV (adult) and recheck.+3. Initiate artesunate IV/IM (first-line for severe malaria):+ - 2.4 mg/kg IV/IM at 0, 12, and 24 hours, then every 24 hours.+ - If IV artesunate not available: artesunate rectal capsule (10 mg/kg) as pre-referral treatment in children < 6 years.+4. Treat convulsions: diazepam 0.3 mg/kg IV slowly (max 10 mg) or rectal (0.5 mg/kg).+5. Transfer to higher facility urgently after initiating treatment.+6. Do NOT give fluid bolus routinely in severe malaria — risk of pulmonary oedema.+ - Give maintenance fluids only unless clear evidence of hypovolaemia.++## Special Populations++### Pregnancy+- First trimester: Quinine + clindamycin for 7 days (avoid artemisinin in 1st trimester if possible).+- Second and third trimester: Artemether-lumefantrine (AL) is safe.+- Do NOT give primaquine in pregnancy.++### Infants < 5 kg+- AL not licensed below 5 kg; use quinine in infants under 5 kg.++## Follow-up+- Review all patients at 48-72 hours.+- If fever persists at 72 hours: obtain blood film microscopy if available and consider treatment failure or alternative diagnosis.+- Repeat RDT at day 3 and day 28 for treatment failure assessment where resources permit.diff --git a/ai_agents/offline_medical_agent/protocols/oral_rehydration.md b/ai_agents/offline_medical_agent/protocols/oral_rehydration.mdnew file mode 100644index 0000000..bc5cef2--- /dev/null+++ b/ai_agents/offline_medical_agent/protocols/oral_rehydration.md@@ -0,0 +1,70 @@+# Oral Rehydration Therapy (ORT) Protocol++## Indications+ORT is first-line treatment for mild to moderate dehydration caused by diarrhoea or vomiting in all age groups. Do NOT use in severe dehydration, altered consciousness, or ileus.++## Assessing Dehydration Severity++### No Dehydration+- Alert, drinking normally.+- Normal skin turgor, moist mouth, normal eyes.+- Normal urine output.+- Action: Home treatment with ORS and continued feeding.++### Mild to Moderate Dehydration (2 or more of the following)+- Restless or irritable.+- Sunken eyes.+- Drinks eagerly, thirsty.+- Skin pinch returns slowly (1-2 seconds).+- Action: ORT in facility as per Plan B below.++### Severe Dehydration (2 or more of the following)+- Lethargic, unconscious, or very weak.+- Sunken eyes.+- Unable to drink or drinks poorly.+- Skin pinch returns very slowly (> 2 seconds).+- Action: IV rehydration (Plan C) — see below.++## Plan A — Home Treatment (No Dehydration)+- Give extra ORS after each loose stool:+ - Children < 2 years: 50-100 ml after each stool.+ - Children 2-10 years: 100-200 ml after each stool.+ - Adults: as much as tolerated (250-500 ml after each stool).+- Continue breastfeeding and normal feeding throughout illness.+- Return immediately if: frequent watery stools, repeated vomiting, high fever, or blood in stool.++## Plan B — ORT in Facility (Mild to Moderate Dehydration)+- Give ORS 75 ml/kg over 4 hours.+- Example: 10 kg child = 750 ml ORS over 4 hours.+- Give small sips frequently (use a spoon for infants).+- Reassess every hour.+- If vomiting, wait 10 minutes then resume more slowly (5 ml every 1-2 minutes).+- After 4 hours reassess: if improved, transition to Plan A; if worsening, switch to Plan C.++## ORS Preparation (WHO Standard Formula)+Per 1 litre of clean water:+- Sodium chloride (table salt): 3.5 g (approximately 1 level teaspoon).+- Trisodium citrate: 2.9 g (or sodium bicarbonate 2.5 g).+- Potassium chloride: 1.5 g.+- Glucose: 20 g (or sucrose 40 g, approximately 8 teaspoons).+- Use pre-packaged WHO ORS sachets when available; mix one sachet in 1 litre of clean water.+- Do NOT add extra sugar or salt.+- Use within 24 hours; discard remainder.++## Plan C — IV Rehydration (Severe Dehydration)+- Establish IV access immediately.+- Adults and children >= 5 years: Ringers Lactate (or 0.9% NaCl) 100 ml/kg over 3 hours.+- Children < 5 years: 100 ml/kg over 3 hours (30 ml/kg fast in first 30 minutes, then 70 ml/kg over 2.5 hours).+- Reassess every 30 minutes; repeat bolus if radial pulse remains weak.+- Start ORS (5 ml/kg/hour) as soon as patient can drink.+- Transfer to higher facility if IV access cannot be established or no improvement.++## Zinc Supplementation (for children 2 months to 5 years with diarrhoea)+- 20 mg/day oral zinc for 10-14 days.+- Infants 2-6 months: 10 mg/day.+- Reduces duration and severity of diarrhoea and prevents recurrence for 2-3 months.++## Feeding During Illness+- Do NOT withhold food. Continue age-appropriate feeds throughout.+- Breastfeeding must continue without interruption.+- Avoid high-sugar drinks (sodas, fruit juice) as they worsen diarrhoea.diff --git a/ai_agents/offline_medical_agent/protocols/pediatric_fever.md b/ai_agents/offline_medical_agent/protocols/pediatric_fever.mdnew file mode 100644index 0000000..ba9ea33--- /dev/null+++ b/ai_agents/offline_medical_agent/protocols/pediatric_fever.md@@ -0,0 +1,39 @@+# Pediatric Fever Management Protocol++## Definition+Fever is defined as a body temperature >= 38.0°C (100.4°F) measured rectally, or >= 37.5°C (99.5°F) axillary in children under 5 years.++## Assessment+- Measure temperature using a calibrated thermometer.+- Assess hydration status: check skin turgor, mucous membranes, urine output, and capillary refill time.+- Check for danger signs: convulsions, altered consciousness, inability to drink, persistent vomiting, severe respiratory distress, stiff neck, bulging fontanelle (infants), petechial or purpuric rash.++## Antipyretic Treatment++### Paracetamol (first-line)+- Dose: 15 mg/kg per dose, every 4-6 hours as needed.+- Maximum: 4 doses in 24 hours (do not exceed 60 mg/kg/day).+- Route: oral or rectal suppository.+- Available preparations: 120 mg/5 ml syrup, 250 mg suppository.++### Ibuprofen (alternative, children >= 3 months and >= 5 kg)+- Dose: 5-10 mg/kg per dose, every 6-8 hours.+- Maximum: 3 doses in 24 hours.+- Route: oral only.+- Do NOT use in children with dehydration, renal impairment, or suspected dengue.++## Supportive Care+- Encourage oral fluids (breastmilk, water, ORS) to prevent dehydration.+- Dress the child in light clothing; avoid over-bundling.+- Do NOT use cold water sponging — it causes shivering and raises core temperature.+- Do NOT use aspirin in children under 16 years (risk of Reye's syndrome).++## Referral Criteria (transfer immediately if any of the following)+- Temperature >= 39.5°C not responding to two doses of antipyretic.+- Age < 3 months with any fever.+- Convulsions — current or within the last 24 hours.+- Signs of severe dehydration.+- Altered mental status or inability to be roused.+- Petechial or purpuric rash (possible meningococcal disease).+- Stiff neck or bulging fontanelle.+- Respiratory rate > 50 breaths/minute (1-12 months) or > 40 breaths/minute (1-5 years).diff --git a/ai_agents/offline_medical_agent/protocols/wound_care.md b/ai_agents/offline_medical_agent/protocols/wound_care.mdnew file mode 100644index 0000000..2bae037--- /dev/null+++ b/ai_agents/offline_medical_agent/protocols/wound_care.md@@ -0,0 +1,83 @@+# Wound Care and Management Protocol++## Initial Assessment+- Time since injury (wounds > 6 hours old have higher infection risk).+- Mechanism: clean cut, crush injury, bite, puncture, contaminated.+- Location: proximity to joints, tendons, nerves, vessels, face.+- Tetanus immunisation status.+- Signs of active bleeding or vascular injury (pulsatile bleeding, expanding haematoma, distal pallor/coldness).++## Control of Bleeding+1. Apply direct firm pressure with a clean cloth or gauze for 10-15 minutes continuously.+2. Do NOT remove dressing to inspect — add more layers if blood soaks through.+3. Elevate the limb above heart level.+4. If pressure fails and limb wound: apply tourniquet 5-7 cm above wound, note time applied.+5. Do NOT use tourniquets on neck, groin, or axilla.+6. For deep scalp wounds: apply pressure and suture or staple promptly — scalp bleeds heavily.++## Wound Irrigation (reduces infection risk significantly)+- Irrigate all open wounds copiously with clean running water or 0.9% saline.+- Volume: at least 100-200 ml per centimetre of wound length using a syringe and 18-gauge cannula for high pressure.+- Remove visible debris with gloved hand or forceps.+- Do NOT irrigate puncture wounds (drives contamination deeper).+- Antiseptic solutions (iodine, hydrogen peroxide, alcohol) damage tissue — use saline or clean water only.++## Wound Closure++### Primary Closure (immediate) — suitable for:+- Clean wounds < 6 hours old (< 12 hours on face).+- No signs of infection.+- Adequate wound edges for approximation.++### Suturing technique+- Use interrupted sutures with non-absorbable monofilament (2-0 or 3-0 nylon) for skin.+- Approximate edges without tension; evert wound edges slightly.+- Removal: face 3-5 days; scalp 7 days; extremities 10-14 days; over joints 14 days.++### Delayed Primary Closure (48-72 hours) — use for:+- Wounds > 6 hours old (> 12 hours on face).+- Bite wounds (human or animal).+- Heavily contaminated or crush injuries.+- Pack wound open with moist saline gauze; reassess in 48 hours.++### Do NOT close:+- Puncture wounds.+- Infected wounds (erythema, pus, warmth, swelling).+- Animal or human bites on hands or feet.++## Wound Dressing+- Apply non-adherent dressing covered with absorbent gauze and secure with bandage.+- Change dressing daily or when saturated.+- Instruct patient to keep wound dry for 24-48 hours after closure.++## Tetanus Prophylaxis++| Immunisation status | Clean wound | Dirty/tetanus-prone wound |+|---|---|---|+| Fully immunised (3+ doses, booster < 5 years) | Nothing | Nothing |+| Fully immunised, last booster 5-10 years ago | Nothing | Booster (0.5 ml Td) |+| Fully immunised, last booster > 10 years ago | Booster | Booster |+| Incompletely immunised or unknown | Full course + TIG | Full course + TIG |++TIG = Tetanus Immunoglobulin 250 IU IM (give in opposite limb to vaccine).++## Antibiotic Prophylaxis+- Routine antibiotics are NOT indicated for clean simple wounds.+- Give prophylactic antibiotics for:+ - All bite wounds (human or animal): Amoxicillin-clavulanate 875/125 mg twice daily for 5 days.+ - Contaminated wounds with signs of infection: same regimen.+ - Penicillin allergy: Doxycycline 100 mg twice daily (not in children < 8 years or pregnancy).++## Signs of Wound Infection (review at 48-72 hours)+- Increasing pain, swelling, warmth, erythema spreading beyond wound.+- Purulent discharge.+- Fever > 38°C.+- Red streaking (lymphangitis).+- Action: open wound if closed, irrigate, prescribe antibiotics, refer if systemic features.++## Referral Criteria+- Wounds involving tendons, joints, nerves, or vessels.+- Compartment syndrome (tense swelling, severe pain on passive stretch, paraesthesia).+- Facial wounds requiring specialist closure.+- Deep contaminated wounds with systemic infection.+- Wounds in immunocompromised patients (diabetes, HIV) that fail to improve.diff --git a/ai_agents/offline_medical_agent/pyproject.toml b/ai_agents/offline_medical_agent/pyproject.tomlnew file mode 100644index 0000000..0b3aee6--- /dev/null+++ b/ai_agents/offline_medical_agent/pyproject.toml@@ -0,0 +1,16 @@+[project]+name = "offline-medical-agent"+version = "0.1.0"+description = "Fully offline agentic RAG system for clinical protocol lookup at edge sites"+requires-python = ">=3.9,<3.14"++dependencies = [+ "llama-cpp-python>=0.3.0",+ "huggingface-hub>=0.23.0",+ "sentence-transformers>=3.0.0",+ "qdrant-client>=1.9.0",+ "gradio>=5.0.0",+]++[tool.setuptools.packages.find]+include = ["offline_medical_agent*"]diff --git a/ai_agents/offline_medical_agent/qdrant_data/.lock b/ai_agents/offline_medical_agent/qdrant_data/.locknew file mode 100644index 0000000..a4b31f4--- /dev/null+++ b/ai_agents/offline_medical_agent/qdrant_data/.lock@@ -0,0 +1 @@+tmp lock file\ No newline at end of filediff --git a/ai_agents/offline_medical_agent/qdrant_data/collection/clinical_protocols/storage.sqlite b/ai_agents/offline_medical_agent/qdrant_data/collection/clinical_protocols/storage.sqlitenew file mode 100644index 0000000..576991dBinary files /dev/null and b/ai_agents/offline_medical_agent/qdrant_data/collection/clinical_protocols/storage.sqlite differdiff --git a/ai_agents/offline_medical_agent/qdrant_data/meta.json b/ai_agents/offline_medical_agent/qdrant_data/meta.jsonnew file mode 100644index 0000000..e31ff13--- /dev/null+++ b/ai_agents/offline_medical_agent/qdrant_data/meta.json@@ -0,0 +1 @@+{"collections": {"clinical_protocols": {"vectors": {"size": 384, "distance": "Cosine", "hnsw_config": null, "quantization_config": null, "on_disk": null, "datatype": null, "multivector_config": null}, "shard_number": null, "sharding_method": null, "replication_factor": null, "write_consistency_factor": null, "on_disk_payload": null, "hnsw_config": null, "wal_config": null, "optimizers_config": null, "quantization_config": null, "sparse_vectors": null, "strict_mode_config": null, "metadata": null}}, "aliases": {}}\ No newline at end of filediff --git a/ai_agents/offline_medical_agent/requirements.txt b/ai_agents/offline_medical_agent/requirements.txtnew file mode 100644index 0000000..dc63ddf--- /dev/null+++ b/ai_agents/offline_medical_agent/requirements.txt@@ -0,0 +1,5 @@+llama-cpp-python>=0.3.0+huggingface-hub>=0.23.0+sentence-transformers>=3.0.0+qdrant-client>=1.9.0+gradio>=5.0.0