Healthy Diet AI Agent is a Bun + TypeScript backend for nutrition and healthy diet support. It features chat, food image analysis, RAG document knowledge retrieval, knowledge graph, and MOHW (Ministry of Health and Welfare) data synchronization.
This repository now supports two deployment modes:
- Standalone mode: uses SQLite, runs independently via Docker, HTTP API, or terminal CLI
- Integration mode: uses Supabase, maintaining the ability to integrate with the existing
health-diet-apiecosystem
- Runtime:
Bun - Language:
TypeScript - HTTP Server:
Express - Agent Framework:
LangChain,LangGraph,DeepAgents - Storage:
SQLiteorSupabase - AI Integration: OpenAI-compatible API routing, with optional Google Gemini routing
- Deployment:
Docker Compose
- Nutrition chat assistant for dietary advice, meal planning, and nutrition Q&A
- Food image analysis workflow supporting meal understanding and nutrition-guided interactions
- RAG document search and document management to organize and query nutrition knowledge documents
- Knowledge graph extraction and search to establish structured health and diet knowledge relations
- MOHW data sync pipeline for importing public clarification and reference content
- Flexible deployment modes supporting SQLite, Supabase, HTTP API, and CLI
- Personalized dietary suggestions based on user profiles, preferences, and historical records
- Enhanced multimodal meal analysis for richer food context understanding and grounded responses
- Expanded admin and ingestion tooling for knowledge curation, review, and operations
- Advanced multi-step agent workflows to improve retrieval, reasoning, and task automation
This project was originally built to complement the following two projects:
PU-Hub/healthy-dietas the API-side projectarchie0732/healthy-diet-webas the frontend Web project
As this repository started receiving more attention and views, the project's direction was adjusted. While keeping the ability to integrate with the original stack, we are gradually refactoring this repository into a standalone, independently deployable AI agent service.
- Switchable storage backend:
sqliteorsupabase - Directly deployable independently, without relying on
health-diet-api - Provides both HTTP API and terminal CLI
- Docker default is standalone SQLite mode
- Supports local knowledge base and uploaded document ingestion
- Retains Supabase integration, suitable for reconnecting to the original project
.
├── .agents/ # Custom agent behavior rules / agent configuration
├── agent_skills/ # Customized tool/skill modules for the agent
├── data/ # Local database files (SQLite DB stored here in Standalone mode)
├── docs/ # DB schemas and supplementary documents
│ ├── sqlite/ # SQLite database schema and sample data
│ └── supabase/ # Supabase database configuration and scripts
├── knowledge_base/ # Ingested documents and RAG data source directories
│ ├── ingested_markdown/ # Parsed markdown documents used for RAG
│ ├── mohw_clarifications/ # Sync target for MOHW (Ministry of Health and Welfare) data
│ ├── uploads/ # Temporary directory for uploaded source files
│ └── NUTRITION_RULES.md # Ground-truth guidelines for dietary analysis
├── raw_data/ # Raw data files or scripts
├── scripts/ # Utility scripts (e.g. data preprocessing, backup)
├── src/ # Main source code directory
│ ├── config/ # App configurations (logger, env validators)
│ ├── server/ # Business logic handlers and Agent implementation
│ │ ├── agentRuntime.ts # Core LangChain/LangGraph agent runtime setup
│ │ ├── httpRuntime.ts # HTTP server runtime bootstrap
│ │ ├── knowledgeGraph.ts # Knowledge Graph extraction and search engine
│ │ ├── knowledgeIngestion.ts # Handles files uploading, parsing and embedding ingestion
│ │ ├── mohwNews.ts # MOHW data synchronization task
│ │ └── ragDocuments.ts # Document database crud and indexer routes
│ ├── storage/ # Database abstraction layer (SQLite and Supabase adapters)
│ │ ├── sqlite/ # SQLite connection and adapter logic
│ │ └── supabase/ # Supabase client and database adapter logic
│ ├── cli.ts # Entry point for the Command Line Interface
│ ├── index.ts # Entry point for the HTTP Express Server
│ └── serverHandlers.ts # Router controller handlers for server endpoints
├── technical_docs/ # Architectural, design, and changelog documents
├── agent_config.json # Declarative behavior controls and default parameters for the agent
├── compose.yml # Docker Compose configuration file
└── package.json # Project dependencies and runner script configurations
Suitable for:
- Self-hosting locally
- Running directly with Docker
- Using terminal prompts
- Avoiding setting up Supabase upfront
Characteristics:
SUPABASE_URLandSUPABASE_SERVICE_KEYare not required- SQLite schema is automatically bootstrapped on startup
- Database path is configured via
SQLITE_DB_PATH
Suitable for:
- Having an existing Supabase schema
- Keeping the integration path with the original system
- Using this agent as a service inside the existing system
Characteristics:
- Preserves existing API routes
- Chat history, user profiles, and document metadata are stored in Supabase
- Bun 1.2+
- Node-compatible environment for Bun
- Optional: Docker / Docker Compose
- Optional: Supabase project for integration mode
- Model endpoint compatible with the current agent configuration
bun installcp .env.example .envCore runtime variables:
PORTAI_API_URLSTORAGE_BACKEND=sqlite|supabaseSQLITE_DB_PATHCLI_USER_IDCLI_THREAD_ID
Supabase variables for integration mode:
SUPABASE_URLSUPABASE_SERVICE_KEY
Google routing variables:
GEMINI_AI_APIGEMINI_API_KEYGOOGLE_CHAT_MODELGOOGLE_BASE_URL
Project-level agent behavior now lives in:
agent_config.json
Background sync variables:
MOHW_NEWS_SYNC_ENABLEDMOHW_NEWS_SYNC_INTERVAL_MINUTESMOHW_NEWS_SYNC_RUN_ON_START
Config precedence:
agent_config.jsonprovides the repository default behavior- Environment variables override those defaults for a specific deployment
MOHW_NEWS_SYNC_ENABLEDoverridesagent_config.jsonfeatures.mohw_enabledwhen explicitly set
Recommended .env configuration:
PORT=8001
AI_API_URL=http://127.0.0.1:8080/v1/
STORAGE_BACKEND=sqlite
SQLITE_DB_PATH=./data/healthy-diet-agent.db
CLI_USER_ID=local-user
CLI_THREAD_ID=local-threadStart the HTTP server:
bun run startDefault URLs:
http://localhost:8001- Chat endpoint:
POST /api/chat - Health check:
GET /ping
Send a prompt directly in the terminal:
bun run cli -- --message "Analyze my lunch"You can also specify user, thread, and model source:
bun run cli -- --message "Give me a low sugar dinner idea" --user-id demo-user --thread-id demo-thread --model-source autoIn general, manual schema setup is not required because the app automatically bootstraps the SQLite schema upon startup.
If you want to manually create the database or pre-seed local testing data, you can use:
- Schema:
docs/sqlite/schema.sql - Sample Seed:
docs/sqlite/seed.sample.sql
If you have sqlite3 installed in your environment:
sqlite3 ./data/healthy-diet-agent.db < docs/sqlite/schema.sql
sqlite3 ./data/healthy-diet-agent.db < docs/sqlite/seed.sample.sqlseed.sample.sql is only a local development example. You can modify the user, chatroom, and dialogue data inside it before importing.
The default Docker setup runs in standalone SQLite mode.
docker compose up --buildDefault behavior:
STORAGE_BACKEND=sqliteSQLITE_DB_PATH=/app/data/healthy-diet-agent.db- Persists SQLite data via
./data:/app/data
Common mounts:
./data./knowledge_base./users_images
For automated production deployment using GitHub Actions, GHCR, and a self-hosted runner, see:
To connect to an existing system, set:
STORAGE_BACKEND=supabase
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_SERVICE_KEY=your-service-role-keyNotes:
- Existing API routes are preserved
- Actual storage writes are routed through the shared storage layer
- Suitable for integration with the existing
health-diet-apior other Supabase-based architectures
For common customization of agent roles and retrieval behaviors, you can do so without modifying the core runtime code.
Recommended customization steps:
- Edit
agent_config.json - Replace
knowledge_base/AGENT.md - Replace or remove
knowledge_base/NUTRITION_RULES.md - Enable or disable
mohw_newsinagent_config.json - Add your own custom knowledge files
agent_config.json currently controls:
- Agent prompt file locations
- Default response styles
- Enabled RAG sources
- RAG search parameters
- Default enablement of MOHW sync features
Config precedence:
agent_config.jsonprovides the repository default behavior- Environment variables override those defaults for a specific deployment
MOHW_NEWS_SYNC_ENABLEDoverridesagent_config.jsonfeatures.mohw_enabledwhen explicitly set
POST /api/chatPOST /api/approvePOST /api/generate_titleGET /ping
GET /api/rag/searchPOST /api/rag/searchGET /api/rag/documentsPOST /api/rag/documentsGET /api/rag/documents/:document_idDELETE /api/rag/documents/:document_idPOST /api/rag/documents/:document_id/reindexGET /api/rag/documents/:document_id/fileGET /api/rag/documents/:document_id/previewGET /api/rag/sources/:document_id/fileGET /api/rag/sources/:document_id/preview
POST /api/admin/knowledge/uploadPOST /api/admin/knowledge/ingest/:idGET /api/admin/knowledge/jobs/:jobId
POST /api/graph/extract-allGET /api/graph/statusPOST /api/graph/documents/:document_id/extractGET /api/graph/documents/:document_idPOST /api/graph/searchGET /api/graph/nodesGET /api/graph/nodes/:node_idGET /api/graph/relations/:relation_id/evidence
POST /api/news/syncGET /api/newsGET /api/news/:idGET /api/news-files
- SQLite file:
data/healthy-diet-agent.dborSQLITE_DB_PATH - User uploaded images:
users_images/ - Uploaded source files:
knowledge_base/uploads/ - Parsed markdown:
knowledge_base/ingested_markdown/ - Nutrition rules:
knowledge_base/NUTRITION_RULES.md - MOHW data:
knowledge_base/mohw_clarifications/
Run focused tests:
bun test src/server/httpRuntime.test.ts src/storage/runtime.test.ts src/server/serverHandlers.test.ts src/server/dbTools.test.ts src/server/ragDocuments.test.ts src/cli.test.tsRun all tests:
bun test- SQLite mode is the recommended default for self-hosting.
- Supabase mode remains supported for integration scenarios.
- Standalone mode does not require
health-diet-api. - Regardless of the mode, the app still expects a working model endpoint through
AI_API_URLor the configured Google route.
- The RAG document management API now requires
X-Admin-User-IdandX-Admin-Role(adminornutritionist) headers. - A bare
Authorizationheader is no longer considered sufficient for administrator privileges. - If
/api/chatfails after creating the initial chat history row, the placeholder reply will be updated from__PENDING__to a[FAILED] ...marker.
- Chinese README: README_zh.md
- Japanese README: README_jp.md
- Technical Docs Directory: technical_docs/
- Change Log: technical_docs/CHANGELOG.md
- Daily Planning Log: technical_docs/DAILY_PLANNING_LOG.md
- RAG Analysis Document (ZH): technical_docs/RAG_AGENT_ANALYSIS_ZH.md
This project is licensed under the MIT license. See LICENSE for details.