|
| 1 | +<!-- |
| 2 | + SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 3 | + SPDX-License-Identifier: Apache-2.0 |
| 4 | +
|
| 5 | + Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | + you may not use this file except in compliance with the License. |
| 7 | + You may obtain a copy of the License at |
| 8 | +
|
| 9 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +
|
| 11 | + Unless required by applicable law or agreed to in writing, software |
| 12 | + distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + See the License for the specific language governing permissions and |
| 15 | + limitations under the License. |
| 16 | +--> |
| 17 | + |
| 18 | +# Smart Health Agent |
| 19 | + |
| 20 | +A comprehensive application that uses multi agent workflow to get real-time health metrics, weather, and Retrieval Augmented Generation (RAG) that can process multimodal documents to provide personalized health recommendations, powered by Gemma 3 on Ollama and LangGraph. |
| 21 | + |
| 22 | + |
| 23 | + |
| 24 | + |
| 25 | +## Overview |
| 26 | + |
| 27 | +This repository demonstrates a complete workflow for health data analysis and personalized recommendations: |
| 28 | + |
| 29 | +1. **Health data integration**: Analyze health metrics from synthetic data or Google Fit API. |
| 30 | +2. **Document processing**: Extract information from health-related documents (PDFs) |
| 31 | +3. **Weather integration**: Incorporate local weather data for context-aware recommendations |
| 32 | +4. **Personalized guidance**: Generate health recommendations based on all available data |
| 33 | + |
| 34 | +The implementation leverages Ollama for powerful RAG-enhanced conversational AI capabilities and LangGraph for agent orchestration. |
| 35 | + |
| 36 | +## Features |
| 37 | + |
| 38 | +- **Multimodal Processing**: Extract and analyze text, tables, images, and charts from health documents |
| 39 | +- **Intelligent Document Analysis**: Automatically detects and processes charts/graphs with specialized description |
| 40 | +- **Personalized Recommendations**: Combines health metrics with document knowledge |
| 41 | +- **Interactive Chat Interface**: Ask follow-up questions about your health data and received recommendations |
| 42 | +- **Weather Integration**: Incorporates local weather data for context-aware health recommendations |
| 43 | +- **Agent-Based Architecture**: Uses LangGraph for orchestrated agent workflows |
| 44 | + |
| 45 | +## System Architecture |
| 46 | + |
| 47 | +The Smart Health Agent operates through a team of specialized AI agents working together: |
| 48 | + |
| 49 | +1. **Health Metrics Analyst Agent**: Examines fitness data, vitals, and activity levels |
| 50 | +2. **Environmental Context Agent**: Evaluates local weather to customize recommendations |
| 51 | +3. **Medical Knowledge Agent**: Processes medical records to find relevant health insights |
| 52 | +4. **Personalized Recommendation Agent**: Combines all insights to create a tailored health plan |
| 53 | + |
| 54 | +All agents communicate through a LangGraph orchestration system running on Cloud Run. |
| 55 | + |
| 56 | +## Requirements |
| 57 | + |
| 58 | +- Python 3.10+ |
| 59 | +- Ollama installed and running (see [Ollama Setup](#ollama-setup) section) |
| 60 | +- Google Fit API access (optional, see [Google Fitness API Setup](#google-fitness-api-setup)) |
| 61 | +- Required Python packages (see requirements.txt) |
| 62 | + |
| 63 | +## Repository Contents |
| 64 | + |
| 65 | +- `smart_health_ollama.py`: Main application with Gradio UI and agent workflows |
| 66 | +- `document_processor.py`: Helper module for multimodal document processing |
| 67 | +- `google_fit_utils.py`: Integration with Google Fit API for health data retrieval |
| 68 | + |
| 69 | +## Installation |
| 70 | + |
| 71 | +1. Clone the NVIDIA GenerativeAIExamples repository: |
| 72 | + ```bash |
| 73 | + git clone https://github.com/NVIDIA/GenerativeAIExamples.git |
| 74 | + cd GenerativeAIExamples/community/smart-health-agent |
| 75 | + ``` |
| 76 | + |
| 77 | +2. Install dependencies: |
| 78 | + ```bash |
| 79 | + pip install -r requirements.txt |
| 80 | + ``` |
| 81 | + |
| 82 | +3. Set up Ollama (see [Google Cloud Run Deployment](#google-cloud-run-deployment) or [Local Ollama Setup](#local-ollama-setup-(alternative))) |
| 83 | + |
| 84 | +4. Run the application: |
| 85 | + ```bash |
| 86 | + python smart_health_ollama.py |
| 87 | + ``` |
| 88 | + |
| 89 | +## Google Cloud Run Deployment |
| 90 | + |
| 91 | +To deploy the Gemma 3 models on Google Cloud Run with Ollama and GPU support: |
| 92 | + |
| 93 | +1. Follow the [Google Cloud Run GPU with Ollama tutorial](https://cloud.google.com/run/docs/tutorials/gpu-gemma-with-ollama) |
| 94 | +2. Set up the necessary Cloud Run service with GPU acceleration |
| 95 | +3. Configure the Ollama container with the required Gemma 3 models |
| 96 | +4. Once deployed, copy the Cloud Run service URL |
| 97 | +5. Set this URL as the `OLLAMA_HOST` environment variable in your application |
| 98 | +6. Update the `smart_health_ollama.py` file with your Ollama host: |
| 99 | + ```python |
| 100 | + OLLAMA_HOST = "https://your-ollama-service-url.run.app" # Replace with your actual Cloud Run service URL |
| 101 | + ``` |
| 102 | + |
| 103 | +Note: Ensure your Cloud Run service has sufficient GPU resources allocated for optimal performance with the Gemma 3 models. |
| 104 | + |
| 105 | +## Local Ollama Setup (Alternative) |
| 106 | + |
| 107 | +If you prefer to run Ollama locally for development: |
| 108 | + |
| 109 | +1. Install Ollama: |
| 110 | + - Visit [Ollama's official website](https://ollama.ai) and follow the installation instructions for your platform |
| 111 | + |
| 112 | +2. Pull the required model: |
| 113 | + ```bash |
| 114 | + ollama pull gemma3:4b-it-q4_K_M |
| 115 | + ``` |
| 116 | + |
| 117 | +3. Configure the application: |
| 118 | + - Set the `OLLAMA_HOST` environment variable to `http://localhost:11434` |
| 119 | + |
| 120 | +## Using the Application |
| 121 | + |
| 122 | +1. In the UI: |
| 123 | + - Select data source (Synthetic Data or Google Fit (Deprecated)) |
| 124 | + - Enter your city name for weather data |
| 125 | + - Provide a folder path containing medical PDF documents |
| 126 | + - Click "Activate Agent System" |
| 127 | + - Interact with the Smart Health Agent Chat to ask health-related questions |
| 128 | + |
| 129 | +2. The application will: |
| 130 | + - Process your health data |
| 131 | + - Analyze weather conditions |
| 132 | + - Index your health documents for RAG |
| 133 | + - Generate personalized health recommendations |
| 134 | + - Allow follow-up questions via chat |
| 135 | + |
| 136 | +## Document Processing Capabilities |
| 137 | + |
| 138 | +The document processor (`document_processor.py`) handles health-related PDF documents: |
| 139 | + - Extracts text content with intelligent block grouping |
| 140 | + - Identifies and processes tables with structure analysis |
| 141 | + - Extracts and analyzes embedded images |
| 142 | + - Detects charts/graphs and provides detailed descriptions |
| 143 | + |
| 144 | +## Google Fitness API Setup |
| 145 | + |
| 146 | +### Important Notice: API Deprecation |
| 147 | +The Google Fit APIs, including the Google Fit REST API, will be deprecated in 2026. As of May 1, 2024, developers cannot sign up to use these APIs. For more information, visit the [official Google Fit REST API documentation](https://developers.google.com/fit/rest). |
| 148 | + |
| 149 | +### Access Conditions |
| 150 | +- If you already have access to the Google Fit API (created before May 1, 2024), you can continue using it by following the setup guide below. |
| 151 | +- If you don't have existing access, please use the "Synthetic Data" option in the application instead. |
| 152 | + |
| 153 | +### A. Project & API Setup (For Existing API Users Only) |
| 154 | +1. Visit [console.cloud.google.com](https://console.cloud.google.com) |
| 155 | +2. Create a new project or select an existing one |
| 156 | +3. Enable the Fitness API: |
| 157 | + - Search for "Fitness API" in the search bar at the top |
| 158 | + - Click on the Fitness API result |
| 159 | + - Click "Enable" |
| 160 | + |
| 161 | +### B. Configure OAuth Consent Screen |
| 162 | +1. In the left sidebar, navigate to "APIs & Services" > "OAuth consent screen" |
| 163 | +2. Click the "Get Started" button |
| 164 | +3. For User Type, select "External" (for personal Gmail accounts) |
| 165 | +4. Fill in the required App Information: |
| 166 | + - App name (e.g., "Health Companion") |
| 167 | + - User support email |
| 168 | + - Developer contact information |
| 169 | +5. Click "Save and Continue" |
| 170 | +6. You'll be taken to the "Scopes" page, but we'll add these later through the Data Access tab |
| 171 | +7. Click "Save and Continue" to proceed to the next step |
| 172 | + |
| 173 | +### C. Add Test Users (CRITICAL STEP) |
| 174 | +1. After the Scopes page, you'll reach the "Test users" section |
| 175 | +2. Click "ADD USERS" |
| 176 | +3. Enter your own Google account email (the one you'll use to test the application) |
| 177 | +4. Click "ADD" |
| 178 | +5. Click "Save and Continue" to complete the OAuth consent screen setup |
| 179 | +6. **IMPORTANT:** Without completing this step, you'll get an "Access blocked" or "has not completed the Google verification process" error! |
| 180 | + |
| 181 | +### D. Configure Data Access Scopes |
| 182 | +1. After completing the consent screen setup, go to "Google Auth Platform" in the left sidebar |
| 183 | +2. Select "Data Access" |
| 184 | +3. Click "Add or remove scopes" |
| 185 | +4. In the dialog that appears, filter by "Fitness API" |
| 186 | +5. Select the read permissions you need: |
| 187 | + - `.../auth/fitness.activity.read` |
| 188 | + - `.../auth/fitness.heart_rate.read` |
| 189 | + - `.../auth/fitness.sleep.read` |
| 190 | +6. Click "Save" to confirm your scope selections |
| 191 | + |
| 192 | +### E. Verify Test User in Audience Section |
| 193 | +1. In the left sidebar of Google Auth Platform, click on "Audience" |
| 194 | +2. Confirm your app is in "Testing" status |
| 195 | +3. Scroll down to "Test users" section |
| 196 | +4. Verify your email appears in the list |
| 197 | +5. If not, click "Add users" and add your email |
| 198 | + |
| 199 | +### F. Create OAuth Client ID |
| 200 | +1. In the left sidebar, go to "Google Auth Platform" > "Clients" (or "APIs & Services" > "Credentials") |
| 201 | +2. Click "Create Credentials" and select "OAuth Client ID" |
| 202 | +3. Application type: Choose "Desktop Application" |
| 203 | +4. Name: Give your client a descriptive name |
| 204 | +5. Click "Create" |
| 205 | +6. Download the JSON file containing your client credentials |
| 206 | +7. Save the file to a secure location on your system |
| 207 | +8. Set an environment variable to tell the application where to find your credentials: |
| 208 | + ```bash |
| 209 | + export GOOGLE_FIT_CLIENT_SECRETS=/path/to/your/client_secrets.json |
| 210 | + ``` |
| 211 | + |
| 212 | +### G. Use in Your Application |
| 213 | +1. Ensure the environment variable is set before running the application |
| 214 | +2. The first time your app runs with Google Fit as the data source, it will prompt you to authorize via a browser |
| 215 | +3. Make sure to log in with the same account you added as a test user |
| 216 | +4. You will see a warning that "This app isn't verified" - this is normal for apps in testing mode |
| 217 | +5. Since you added yourself as a test user, you can proceed by clicking on your email address |
| 218 | + |
| 219 | +### H. Required Google Fit Data (IMPORTANT) |
| 220 | +1. **The Health Companion app expects certain fitness data to be available in your Google Fit account.** |
| 221 | +2. If you choose "Google Fit" as your data source, your Google account should have: |
| 222 | + - Step count data (derived:com.google.step_count.delta) |
| 223 | + - Heart rate data (derived:com.google.heart_rate.bpm) |
| 224 | + - Sleep data (derived:com.google.sleep.segment) |
| 225 | +3. To ensure you have data before using the app: |
| 226 | + - Install the Google Fit app on your mobile device |
| 227 | + - Log some activity data (take walks with your phone) |
| 228 | + - Record heart rate data (if you have a compatible device) |
| 229 | + - Record sleep data (if you have a compatible device) |
| 230 | +4. **Alternative:** Use the "Synthetic Data" option in the app if you don't have real Google Fit data. |
| 231 | + |
| 232 | +### Troubleshooting Google Fit Integration |
| 233 | +- If you see "Access blocked: [app name] has not completed the Google verification process": |
| 234 | + - Make sure you added your email as a test user in the Audience section |
| 235 | + - Make sure you're signing in with the exact same email you added as a test user |
| 236 | + - Try deleting any existing token.json file from your project and reauthorizing |
| 237 | + - After adding yourself as a test user, wait a few minutes for changes to propagate |
| 238 | +- If you encounter an "invalid_grant" error, it usually means: |
| 239 | + - Your refresh token has expired |
| 240 | + - Access has been revoked |
| 241 | + - You're not using an authorized test user email |
| 242 | + - Solution: Delete the token.json file (if it exists) and re-authorize the application |
| 243 | +- If you get `HttpError 403` about missing data sources: |
| 244 | + - Switch to "Synthetic Data" rather than "Google Fit" in the app |
| 245 | + - Ensure your Google Fit account has recorded activity/fitness data |
| 246 | + - Use a Google account that actively uses fitness tracking devices |
| 247 | + |
| 248 | +## Model Details |
| 249 | + |
| 250 | +The application uses: |
| 251 | +- **Ollama**: For LLM capabilities and text generation |
| 252 | +- **LangGraph**: For agent orchestration and workflow management |
| 253 | +- **Sentence Transformers**: For document embeddings |
| 254 | +- **Milvus**: For vector database storage |
| 255 | + |
| 256 | +## Required APIs and Dependencies |
| 257 | + |
| 258 | +- Ollama (for LLM capabilities) |
| 259 | +- Open-Meteo (for weather data) |
| 260 | +- Google Fit API (optional, for health data) |
| 261 | +- PyMuPDF (for PDF processing) |
| 262 | +- Milvus (for vector database) |
| 263 | +- LangGraph (for agent orchestration) |
| 264 | + |
| 265 | +## Technical Notes |
| 266 | + |
| 267 | +- The application creates a local Milvus database for vector storage |
| 268 | +- Image and table references are stored in the `vectorstore` directory |
| 269 | +- For optimal performance, ensure you have at least 8GB of RAM available |
| 270 | +- The application uses a multi-agent architecture with LangGraph for orchestration |
| 271 | +- For Cloud Run deployment, ensure proper GPU configuration and concurrency settings |
| 272 | + |
| 273 | +## Acknowledgments |
| 274 | + |
| 275 | +- Ollama team for providing the LLM capabilities |
| 276 | +- Open-Meteo for weather data API |
| 277 | +- Google for Fitness API integration |
| 278 | +- LangGraph team for the agent orchestration framework |
| 279 | + |
| 280 | +## Contact |
| 281 | + |
| 282 | +For questions, feedback, or collaboration opportunities, please open an issue in the [NVIDIA GenerativeAIExamples repository](https://github.com/NVIDIA/GenerativeAIExamples). |
| 283 | + |
| 284 | +## Contributing |
| 285 | + |
| 286 | +This example is part of the NVIDIA GenerativeAIExamples community contributions. To contribute to this project or other community examples, please refer to the [main repository](https://github.com/NVIDIA/GenerativeAIExamples) for contribution guidelines. |
0 commit comments