Back to Projects

Project

Diabetes Risk Prediction Chatbot

An intelligent chatbot that predicts diabetes risk based on user inputs and provides health interventions.

healthcare-aimedical-chatbotflasklanggraphollamaqdrantmachine-learningrisk-predictionLogistic Regressionvector-databasepostgresqlpythonai-screeningInterventions
Diabetes Risk Prediction Chatbot preview

Diabetes Chatbot POC

This project is a Proof-of-Concept (POC) for a diabetes detection chatbot web application built using Flask REST API, LangGraph, and Ollama. The application assists users in understanding diabetes risk factors and provides relevant information through an interactive chatbot interface. The conversation flow is orchestrated entirely via LangGraph nodes.

Diabetes Questionnaire Sources

Curation of questions from diabetes-risk frameworks (FINDRISC, ADA, IDRS)

IDRS FINDRISC

Project Structure

diabetes-chatbot-poc
├── CODE
│   ├── app.py                  # Entry point for the Flask REST API
│   ├── chatbot
│   │   ├── __init__.py         # Marks the chatbot directory as a package
│   │   ├── graph_builder.py    # LangGraph graph construction
│   │   ├── graph_nodes.py      # Graph node implementations
│   │   ├── graph_state.py      # State definitions
│   │   ├── chat_session.py     # Chat session management
│   │   ├── llm.py              # LLM integration (Ollama)
│   │   ├── qdrant.py           # Qdrant vector database integration
│   │   ├── static_variables.py # Question definitions
│   │   ├── db_helpers.py       # Database helper functions
│   │   └── scoring.py          # Risk scoring functions
│   └── chatbot.ipynb           # Jupyter notebook for testing
├── requirements.txt             # List of dependencies
└── README.md                    # Project documentation

Requirements

To run this project, you need to install the following dependencies:

  • Flask
  • Flask-CORS
  • LangGraph
  • Ollama
  • PostgreSQL
  • Qdrant
  • Sentence-Transformers

You can install the required packages by running:

pip install -r requirements.txt

Running the Flask REST API

To start the Flask REST API server, navigate to the CODE directory and run:

cd CODE
python app.py

The API will be available at http://localhost:5000

API Endpoints

Health Check

  • GET /api/health
    • Returns API health status

Session Management

  • POST /api/sessions

    • Create a new chat session
    • Returns: session_id and first question
  • GET /api/sessions

    • List all active sessions
  • GET /api/sessions/<session_id>/question

    • Get the current question for a session
  • GET /api/sessions/<session_id>/history

    • Get chat history for a session
  • GET /api/sessions/<session_id>/state

    • Get the current state of a session
  • GET /api/sessions/<session_id>/assessment

    • Get risk assessment results for a session
  • DELETE /api/sessions/<session_id>

    • Delete a chat session

Chat Interaction

  • POST /api/sessions/<session_id>/message
    • Send a message/answer to the chatbot
    • Body: {"message": "your answer"}
    • Returns: Next question or risk assessment if completed

API Usage Examples

Create a Session

curl -X POST http://localhost:5000/api/sessions

Response:

{
  "session_id": "uuid-here",
  "message": "Session created successfully",
  "current_question": {
    "question": "What is your name?",
    "question_key": "name",
    "question_type": "text",
    "question_id": 0
  }
}

Send a Message

curl -X POST http://localhost:5000/api/sessions/<session_id>/message \
  -H "Content-Type: application/json" \
  -d '{"message": "John Doe"}'

Response:

{
  "message": "Answer processed successfully",
  "next_question": {
    "question": "How old are you? Options: ...",
    "question_key": "age",
    "question_type": "number",
    "question_id": 1
  },
  "history": [...],
  "completed": false
}

Get Risk Assessment

curl http://localhost:5000/api/sessions/<session_id>/assessment

Response:

{
  "risk_level": "Medium",
  "risk_score": 45,
  "interventions": "Detailed intervention recommendations...",
  "completed": true
}

Usage

Once the Flask API is running, you can interact with the chatbot by:

  1. Creating a session
  2. Sending answers to questions sequentially
  3. Receiving risk assessment after completing all questions

The chatbot uses LangGraph nodes for conversation flow management (router → prepare_question → process_answer → build_risk_assessment_prompt). Ollama powers LLM parsing/answers, and Qdrant provides medical knowledge retrieval.

Contributing

Contributions are welcome! Please feel free to submit a pull request or open an issue for any enhancements or bug fixes.


Features

  • Chatbot UI with question bubbles, progress bar, fixed layout, and scrollable history
  • Questionnaire → Assessment flow with interventions and justification
  • User auth: signup/login with password hashing (no JWT)
  • Persistence: PostgreSQL via SQLAlchemy for users, questionnaire responses, and assessments
  • Vector search: Qdrant for knowledge retrieval; LLM via Ollama
  • Config via .env; can run on localhost or expose to LAN
  • Full LangGraph orchestration: all steps run via nodes (no procedural helpers in the request path)
  • ML training improvements: epoch progress and ETA printed during training
  • Config flag: TRAIN_MODEL_ENABLED to enable/disable background model training

Quick Start

  1. Create a virtual environment and install deps
python -m venv .venv
.venv\\Scripts\\activate   # Windows
pip install -r requirements.txt
  1. Configure .env in project root
# App
DEBUG=False
LOG_LEVEL=INFO
TRAIN_MODEL_ENABLED=true

# PostgreSQL
POSTGRES_USER=postgres
POSTGRES_PASSWORD=your_password
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_DB=diabetes-poc

# Qdrant
QDRANT_API_KEY=your_qdrant_key
QDRANT_URL=https://your-qdrant-url

# Ollama
OLLAMA_MODEL=qwen2.5:3b
OLLAMA_HOST=http://localhost:11434
  1. Ensure the database exists and schema is applied
  • Create the database diabetes-poc (or adjust POSTGRES_DB accordingly)
  • Optional: apply SQL in CODE/sql/schema.sql if desired; models also create tables automatically on first run
  1. Run the server
cd CODE
python app.py

By default, it runs on port 5000. It is configured with host='0.0.0.0' so it can be reachable on the LAN (see below).

Access from other devices on your LAN

  1. Allow inbound TCP 5000 in Windows Defender Firewall (Private profile)
  2. Find your LAN IP via ipconfig (e.g., 192.168.1.42)
  3. Open from another device: http://<YOUR_LAN_IP>:5000/

Keep debug=False for safety. Do not expose to the public internet without hardening and a production WSGI server.

Frontend Pages

  • / Chatbot home (requires login)
  • /login.html Login page
  • /signup.html Signup page

Authentication

  • Passwords are stored as hashes using Werkzeug
  • Local session only (no JWT). The frontend stores user_id in localStorage to gate access
  • Login/logout UI toggling is in the navbar and a Logout button on home

Auth API

  • POST /api/auth/signup

    • Body: { username, password, name?, dob?, gender?, place?, industry? }
    • 201 on success, 409 if username exists
  • POST /api/auth/login

    • Body: { username, password }
    • 200 on success returns { user_id }

Debug API

  • GET /api/debug/users returns a short list of users in the connected database

Core Chatbot API

  • GET /api/health
  • POST /api/sessions → creates session; accepts optional { user_id }
  • POST /api/sessions/<session_id>/message → send an answer
  • GET /api/sessions/<session_id>/question → current/next question
  • GET /api/sessions/<session_id>/history
  • GET /api/sessions/<session_id>/state
  • GET /api/sessions/<session_id>/assessment
  • DELETE /api/sessions/<session_id>

Database Schema

  • ORM models: CODE/chatbot/models.py
    • users: id, username (unique), password_hash, name, dob, gender, place, industry, created_at
    • questionnaire_responses: id, user_id?, session_id, responses (JSONB), created_at
    • assessments: id, user_id?, session_id, risk_level, risk_score, interventions, justification, created_at
  • SQL reference: CODE/sql/schema.sql

Test Script

  • CODE/test.py performs a basic end-to-end flow: health → signup/login → create session → fetch question → answer → assessment

Run:

cd CODE
python test.py

Notes:

  • Run while the server is up on port 5000
  • The script generates a unique username; on 409 it attempts login

Troubleshooting

  • 500 on signup: "'occupation' is an invalid keyword argument for User"

    • Ensure the signup route doesn’t pass occupation (model no longer has that column)
  • Users not appearing in DB

    • Confirm .env has POSTGRES_DB=diabetes-poc (or your intended DB)
    • Ensure no conflicting system env overrides; restart server after changes
    • Hit GET /api/debug/users to verify which DB the app is using
  • “Could not find platform independent libraries ” on Windows

    • Benign when invoking Python in a venv; safe to ignore
  • “Session not found” after questionnaire

    • Ensure use_reloader=False so in-memory sessions aren’t cleared by the reloader
  • Frontend not showing or stuck

    • Hard refresh, clear cache/localStorage
    • Ensure only one definition of API_BASE_URL (we use a single window.API_BASE_URL approach)

Deployment Notes

  • The built-in Flask server is for development. For production, use a WSGI server (e.g., gunicorn/uvicorn+ASGI wrappers) behind a reverse proxy
  • Keep secrets in environment variables and never commit real API keys

📜 License

MIT License — Copyright © 2025 Developers: Manideep & Rajeev


🙌 Contributors

  • Manideep

Disclaimer: This project is an educational prototype diabetes assessment with AI-assisted analysis. It is not intended for medical diagnosis or treatment.