Skip to content

Wellysa AI Worker

API Status

AI-powered medical chat assistant for Wellysa/OnkoRadar applications, providing conversational health guidance, RAG-based knowledge retrieval, and oncology package recommendations.

ResourceURL
API Endpointhttps://wellysa-ai-chat.helpdesk-efd.workers.dev
API DocumentationSwagger UI
Health Check/health
Readiness Check/ready
Metrics/metrics
Logs UI/logs
Admin Panel/admin
AI Research Report/medical-ai-research
⚠️ Credentials (sensitive - verify with team)

Docs, Logs, Admin:

  • Login: wellysa
  • Password: HX3KiQ+y6arz03NTcWQVqkhY

Medical AI Research:

  • Login: wellysa
  • Password: wellysa2026

Tech Stack

Runtime & Infrastructure:

  • Cloudflare Workers (serverless edge compute)
  • Cloudflare D1 (SQLite logging database)
  • Cloudflare R2 (object storage for knowledge base PDFs)
  • Cloudflare AutoRAG (vector search for document retrieval)

AI & OCR:

  • Google Gemini API (conversational AI)
  • OpenCV service (Python/Django - document OCR processing)

Development:

  • ES Modules (type: "module")
  • Vitest (unit testing with coverage)
  • Wrangler 4.x (deployment CLI)

Architecture

┌─────────────────────────────────────────────────────────────┐
│  Wellysa AI Worker (Cloudflare Worker - JavaScript)         │
│  ├── worker.js              HTTP routing                     │
│  ├── lib/chat.js            Main conversation logic          │
│  ├── lib/rag.js             AutoRAG integration              │
│  ├── lib/medical-assistant  Conversation flow detection      │
│  ├── lib/profile.js         User context extraction          │
│  ├── lib/logger.js          D1 logging                       │
│  └── lib/validators.js      Input sanitization               │
└─────────────────────────────────────────────────────────────┘
                        ↓                     ↓
              ┌─────────────────┐   ┌──────────────────┐
              │  Gemini API     │   │  Cloudflare D1   │
              │  (AI responses) │   │  (logs)          │
              └─────────────────┘   └──────────────────┘

              ┌─────────────────┐
              │  AutoRAG        │ ← R2 bucket (knowledge-files/)
              │  (vector search)│    - team/*.txt (doctor profiles)
              └─────────────────┘    - wellysa/*.txt (medical guides)

┌─────────────────────────────────────────────────────────────┐
│  OpenCV Service (Python/Django) - opencv-main/               │
│  ├── documents/              OCR document processing         │
│  ├── manage.py               Django management               │
│  └── Procfile                Deployment config               │
└─────────────────────────────────────────────────────────────┘

Project Structure

lib/
├── admin.js              # RAG files management UI
├── chat.js               # Main chat handler + Gemini orchestration
├── docs.js               # Swagger UI endpoint
├── health.js             # Health, readiness, metrics endpoints
├── logger.js             # D1 logging utilities
├── logs.js               # Logs UI and cleanup cron
├── medical-assistant.js  # Conversation stage detection
├── medical-prompts.js    # AI system prompts & safety guardrails
├── openapi.js            # OpenAPI 3.0 specification
├── profile.js            # User profile extraction from context
├── rag.js                # AutoRAG search utilities
└── validators.js         # Input validation & sanitization

opencv-main/              # Python/Django OCR service
├── documents/            # Django app for document processing
├── manage.py             # Django CLI
└── Procfile              # Deployment config

knowledge-files/          # RAG knowledge base
├── team/                 # Doctor profiles (dr-ciesluk.txt, etc.)
└── wellysa/              # Medical content (triage, procedures)

tests/                    # Vitest unit tests
worker.js                 # HTTP routing entrypoint

API

Chat Endpoint

http
POST /
Content-Type: application/json
X-API-Key: <API_KEY>

Request:

json
{
  "message": "Mam pytanie o badania",
  "history": [
    { "role": "user", "content": "Cześć" },
    { "role": "assistant", "content": "Dzień dobry! W czym mogę pomóc?" }
  ],
  "userContext": {
    "name": "Jan",
    "age": 55,
    "gender": "male",
    "isSmoking": true
  },
  "ocrText": "PSA 2.1 ng/mL (0-4.0)"
}
FieldRequiredDescription
messageyes*User's current message (*or imageBase64)
historynoPrevious conversation (max 30 messages)
userContextnoUser profile from onboarding flow
ocrTextnoPre-extracted OCR text from medical documents
imageBase64noBase64-encoded image for server-side OCR (PNG/JPEG/PDF, max 5MB)

Response:

json
{
  "text": "Ze względu na historię rodzinną zalecam badania genetyczne.",
  "recommendedPackage": "OnkoRadar Omni"
}

System Endpoints

EndpointAuthDescription
GET /healthNoQuick health check (200 OK if worker running)
GET /readyNoDeep readiness check - tests D1 and AutoRAG connectivity (503 if dependency unavailable)
GET /metricsNoPrometheus-compatible metrics (test coverage gauge)
GET /status-badgeNoShields.io badge JSON for README status badge
GET /docsYesSwagger UI (interactive API documentation)
GET /debug?q=...NoTest RAG search without AI processing
GET /logsYesLogs UI and management dashboard
GET /adminYesAdmin panel for RAG files management
GET /medical-ai-researchYes*Static AI research report (*separate credentials)

Error Handling

  • Retry logic: 3 attempts for transient Gemini API errors
  • Request limits: 8MB max payload (accommodates 5MB base64 images)
  • OCR truncation: Documents >4KB are shortened with user notification
  • Sanitized errors: No stack traces exposed to clients
API Keys (verify current keys with team)
ClientAPI Key
iOSios_cf46a5898e717c34dbe0c09856f3abd9
Webweb_7b23a693d7e8f165d82e95102c7ca221
Androidandroid_df2e666789304f0da91bced638a00458

AI Behavior

Conversation Flow

  1. Information gathering - 2-3 contextual questions about health concerns, family history, lifestyle factors
  2. RAG search - Query knowledge base with user profile and symptom context
  3. Recommendation - Suggest relevant tests, lifestyle modifications, and Wellysa packages

Package Matching Logic

(Implemented in lib/medical-assistant.js - confirm exact mapping with team)

User ProfileRecommended Package
Family cancer history + genetic testing indicationOnkoRadar Max Risk
Family oncological historyOnkoRadar Omni
Basic prevention screeningOnkoRadar Basic
Trace element focus (Selen, Cynk)OnkoRadar Pierwiastki

Safety Guardrails

  • Language: Polish primary - graceful fallback for other languages
  • Topic filtering: Blocks off-topic queries (weather, politics, sports) defined in knowledge-files/wellysa/tematy-zakazane.txt
  • Prompt injection protection: Validates and sanitizes inputs to prevent manipulation
  • RAG-grounded responses: Medical information sourced from verified knowledge base

Logging

All API requests and errors are logged to Cloudflare D1 database.

Auto-cleanup: Logs older than 30 days are deleted weekly (Sunday 3:00 UTC via cron trigger).

EventLevel
Gemini API errorerror
Unauthorized requestwarn
OCR extraction failureerror
Uncaught exceptionserror

Setup

Prerequisites

  • Node.js 18+ with npm
  • Cloudflare account with Workers/R2/D1/AutoRAG enabled
  • Google Gemini API key

1. Install Dependencies

bash
npm install

2. Create R2 Bucket & Upload Knowledge Base

bash
npx wrangler r2 bucket create wellysa-knowledge
./upload-to-r2.sh

3. Create AI Search Index

  1. Open Cloudflare Dashboard → AI → AI Search
  2. Click "Create" → Name: wellysa-ai-rag
  3. Source: R2 bucket wellysa-knowledge

4. Configure D1 Database

bash
npx wrangler d1 create wellysa-logs
# Update wrangler.toml with database ID

5. Set Secrets

bash
npx wrangler secret put GEMINI_API_KEY
npx wrangler secret put API_KEYS        # Comma-separated: ios_xxx,web_xxx,android_xxx
npx wrangler secret put DOCS_PASSWORD   # For /docs, /logs, /admin endpoints

6. Deploy

bash
npm run deploy
# or
npx wrangler deploy

Development

Run Tests

bash
npm test                # Single run
npm run test:watch      # Watch mode
npm run test:coverage   # With coverage report

Local Development

bash
npx wrangler dev        # Start local worker

Upload PDFs to R2

bash
npm run upload-pdfs     # Sync pdfs/ directory to R2 bucket

OpenCV Service (unverified - confirm with team)

The opencv-main/ directory contains a Python/Django service for OCR document processing. Deployment details:

  • Framework: Django
  • Management: manage.py CLI
  • Deployment: Configured via Procfile
  • API: REST endpoints for document upload and text extraction

(Verify if this service is actively deployed and document its endpoints if in use)

Status

Production: Deployed at wellysa-ai-chat.helpdesk-efd.workers.dev
Test Coverage: Check /metrics endpoint for current gauge
CI/CD: GitHub Actions workflow (.github/workflows/deploy.yml)


Repository: Wellysa/wellysa-ai-worker
Default Branch: main
Maintainer: Wellysa team (verify contact with [email protected])

Wellysa Consigliere — internal use only.