Skip to content

DevOpsOfChaos/personal-ai-platform

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

46 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

🤖 Personal AI Platform

License: MIT Python 3.12+ HACS Default PRs Welcome Version

Dein persönlicher KI-Agent — Telegram-Bot mit 70+ Tools, HACS-Integration & lokalem First-Ansatz.

📖 Deutsch | English


Deutsch

Was ist das?

Die Personal AI Platform ist ein KI-gestützter Telegram-Bot, der rund um die Uhr als persönlicher Assistent läuft. Er lernt deine Gewohnheiten, trackt deine Gesundheit, steuert dein Smart Home, erinnert dich an Aufgaben — und wird mit jeder Interaktion besser.

  • 🤖 Telegram-Bot — chatte natürlich, als würdest du mit einem Menschen schreiben
  • 🧠 70+ LLM-Tools — Produktivität, Gesundheit, Smart Home, Wissen, Kontakte, Pflanzen, Personalisierung
  • ☀️ Adaptives Briefing — lernt deine Aufwachzeiten und schickt dir jeden Morgen eine personalisierte Übersicht
  • 🏠 HACS-Integration — offizieller Home Assistant Community Store Support mit Sensoren & Services
  • 📊 20+ Intelligenz-Module — Insights, Routinen, Terminplanung, Schlaf-Coach, Workflow-Engine u.v.m.
  • 🧬 7 Lern-Module — Pattern Tracking, Knowledge Graph, Preference Learning, Prompt Rules
  • 🔧 21 Built-in Scripts — Daily Briefing, Habit Tracker, Mood Tracker, Travel Assistant u.v.m.
  • 27 Scheduler-Jobs — Check-ins, Erinnerungen, Kalender-Sync, Routinen, Pflanzen-Pflege

⚡ Quickstart

Option A: Standalone (5 Minuten)

git clone https://github.com/DevOpsOfChaos/personal-ai-platform.git
cd personal-ai-platform
pip install -r requirements.txt
python setup_wizard.py
python -m src.main

Option B: HACS (Home Assistant)

  1. HACS → Integrations → ⋮ (Menü) → Custom repositories
  2. URL: https://github.com/DevOpsOfChaos/personal-ai-platform
  3. Kategorie: Integration
  4. "Personal AI Agent" installieren
  5. Einstellungen → Geräte & Dienste → Integration hinzufügen → Personal AI Agent
  6. Agent-Code unter /config/pai_agent/ installieren:
    cd /config && git clone https://github.com/DevOpsOfChaos/personal-ai-platform.git pai_agent
    cd pai_agent && pip install -r requirements.txt

📖 Detaillierte HACS-Dokumentation: docs/HACS.md


🔌 APIs & Kosten

API Pflicht? Kosten Wofür
📡 Telegram Bot API ✅ Ja Kostenlos Nachrichten-Empfang & -Versand
🧠 OpenRouter ✅ Ja Pay-per-use LLM-Zugriff (kostenlose Modelle verfügbar)
🤖 OpenAI ⬜ Optional Pay-per-use Alternative zu OpenRouter
🌤️ OpenWeatherMap ⬜ Optional Kostenlos (1000 Calls/Tag) Wetter im Briefing & per Chat
🏠 Home Assistant ⬜ Optional Lokal & kostenlos Smart-Home-Steuerung & Sensor-Daten
📅 Google Kalender ⬜ Optional Kostenlos (via HA) Termine im Briefing
🌐 DuckDuckGo ⬜ Optional Kostenlos Web-Suche & Nachrichten
📖 Wikipedia ⬜ Optional Kostenlos Artikel-Suche & Zusammenfassung

💡 Mit kostenlosen OpenRouter-Modellen: 0€/Monat.
Einfach :free an den Modellnamen anhängen (z.B. meta-llama/llama-4-maverick:free).

📖 Anbieter wechseln: docs/API_PROVIDERS.md


🏠 HACS-Integration

Die Personal AI Agent Integration ist offiziell im HACS (Home Assistant Community Store) verfügbar.

Konfigurations-Flow

Nach der Installation über HACS erscheint die Integration unter Einstellungen → Geräte & Dienste → Integration hinzufügen. Der Konfigurations-Dialog fragt ab:

Feld Typ Beschreibung
telegram_token Pflicht Bot-Token von @BotFather
openrouter_api_key Pflicht OpenRouter API-Key
agent_name Optional Name des Agenten (Standard: „Nutzer")
language Optional de oder en
timezone Optional Zeitzone (Standard: Europe/Berlin)

Nach der Ersteinrichtung stehen unter Optionen weitere Einstellungen zur Verfügung:

  • Wetter (OpenWeatherMap Key + Stadt)
  • Home Assistant URL + Long-Lived Token

Sensoren

Sensor Icon Typ Bedeutung
sensor.pai_agent_status 🤖 Diagnose Aktueller Status: running / stopped
sensor.pai_uptime Diagnose Laufzeit des Agenten (z. B. „12h 34m")
sensor.pai_last_briefing 🌅 Status Zeitstempel des letzten Morgen-Briefings
sensor.pai_messages_today 💬 Status Anzahl der heute verarbeiteten Nachrichten
sensor.pai_llm_cost 💰 Diagnose Kumulierte LLM-Kosten in USD (mit Tokens/Requests als Attribute)

Services

Service Beschreibung Parameter
pai_agent.send_message Sendet eine Nachricht über den Bot message (Pflicht)
pai_agent.restart_agent Startet den Agenten-Prozess neu
pai_agent.get_status Fragt aktuellen Agent-Status ab

Updates via HACS

Die Integration nutzt HACS' eingebauten Update-Mechanismus. Neue Versionen erscheinen automatisch im HACS-Dashboard unter Updates und können mit einem Klick installiert werden. Der Agent-Code unter /config/pai_agent/ muss separat per git pull aktualisiert werden.


🧭 Onboarding

Der Setup Wizard (setup_wizard.py) führt dich in 7 Schritten durch die Einrichtung:

Schritt Name Was passiert
1 Grundeinstellungen Name, Sprache, Zeitzone, Standort, Antwort-Stil, Emoji-Präferenz
2 Telegram Bot BotFather-Anleitung, Token-Eingabe, automatische User-ID-Erkennung
3 LLM / OpenRouter API-Key-Eingabe mit Live-Validierung, Modell-Auswahl (cheap/strong/reasoning)
4 Integrationen Home Assistant (URL + Token mit Verbindungstest), OpenWeatherMap, Google Kalender
5 Personalisierung Ziele, Gewohnheiten, Kontakte, Lebensphase, persönliche Infos
6 Kennenlerngespräch KI-geführter Chat — der Agent stellt 5–8 Fragen und lernt deine Vorlieben
7 Speichern Generiert config.yaml, .env, deploy/seed_data.sql + Kosten-Schätzung

Das Kennenlerngespräch (Schritt 6) nutzt das konfigurierte LLM, um einen echten Dialog zu führen. Der Agent fragt nach Tagesablauf, Schlafgewohnheiten, Hobbys und Kommunikationsstil. Die Antworten werden im Agent-Gedächtnis gespeichert und beeinflussen zukünftige Interaktionen.

📖 Detaillierte Walkthrough: docs/ONBOARDING.md


🎯 Feature-Matrix

Kernfunktionen

Feature Kategorie Status
📋 Telegram-Befehle (/today, /tasks, /reminders, /notes, /ziele, /status, /hilfe, /settings) Produktivität
✅ Aufgaben-Manager (Priorität, Deadline, Status-Tracking, Vorlagen) Produktivität
⏰ Erinnerungen (natürliche Sprache: „Erinnere mich morgen um 18:00 an…") Produktivität
📝 Notizen & Gedanken (Tags: #idee, #sorge, #erkenntnis, #frage) Produktivität
🌅 Morgen-Briefing (Wetter, Kalender, Tasks, Tipps) Intelligence
📅 Wochenplan (KI-generiert, Sonntags) Intelligence
🧠 LLM-Fallback (unerkannte Nachrichten → Intent-Parser mit 70+ Tools) LLM
💬 Proaktive Check-ins (Stimmung, Energie, Fortschritt) Intelligence
🌙 Tagesphasen-Tracking (Morgen → Aktiv → Abend → Schlaf) Intelligence
🔔 Inaktivitäts-Nudge (meldet sich bei längerer Funkstille) Intelligence
📊 Insight Engine (KI-generierte Korrelationen, Trends, Anomalien) Intelligence
🔄 Self-Improve (optimiert Verhalten basierend auf Feedback) Intelligence
📝 Summarizer (Tages- & Wochen-Zusammenfassungen) Intelligence
🔁 Workflow Engine (automatisiert wiederkehrende Abläufe) Intelligence 🧪
🌅 Morgen-Routine (KI-geführte Start-in-den-Tag) Intelligence
🌞 Tages-Assistent (proaktive Tagsüber-Nudges) Intelligence
🌇 Abend-Routine (Reflexion & morgige Vorbereitung) Intelligence

Gesundheit & Schlaf

Feature Kategorie Status
😴 Schlaf-Tracking („Gehe schlafen", „Bin aufgewacht") Gesundheit
📈 Schlaf-Analyse (Muster, Durchschnitt, Defizit-Warnungen) Gesundheit
🌡️ Temperatur/Schlaf-Korrelation (via HA-Sensoren) Gesundheit
🧠 Smart Sleep Flow (KI-geführte Einschlaf-/Aufwach-Begleitung) Gesundheit
💊 Gesundheits-Tracker (Symptome, Medikamente, Energie, Mahlzeiten) Gesundheit
💊 Medikamenten-Tracker (Einnahme-Erinnerungen & Compliance) Gesundheit
🏋️ Sport-Planer (Gym, Joggen, Radfahren — mit Intensität & Muskelgruppen) Gesundheit
🥗 Ernährungs-Tracker (Mahlzeiten loggen, Supplement-Reminder) Gesundheit 🧪
📊 Health Digest (wöchentlicher Gesundheitsbericht) Gesundheit
🍏 Apple Health Bridge (Sync von Apple Health-Daten) Gesundheit

Lernen & Anpassung

Feature Kategorie Status
🧩 Pattern Tracker (erkennt Verhaltensmuster aus Daten) Learning
❤️ Preference Learner (lernt Vorlieben aus Interaktionen) Learning
🎯 Prompt Optimizer (verbessert LLM-Prompts automatisch) Learning 🧪
🔗 Knowledge Graph (Wissensgraph über Nutzer & Kontext) Learning 🧪
📚 Dynamic Knowledge (kontinuierliche Wissens-Aktualisierung) Learning
📏 Prompt Rules (kontextbewusste Prompt-Anpassung) Learning
🔄 Reinforcement (verstärkendes Lernen aus Nutzer-Feedback) Learning 🧪

Integrationen

Feature Kategorie Status
🌤️ Wetter (aktuell + 5-Tage-Vorhersage, OpenWeatherMap) Integration
📅 Kalender (Google Calendar, iCal, HA-basiert) Integration
🏠 Home Assistant (Licht, Sensoren, Skripte, Media, Alexa, Buttons) Integration
🌐 Web Search (Internet-Recherche mit Quellenangabe) Integration
📖 Wikipedia (Artikel-Suche & Zusammenfassung) Integration
📰 Nachrichten (aktuelle Schlagzeilen nach Thema/Land) Integration
🌍 Übersetzung (Text in beliebige Sprachen) Integration
🍏 Apple Health (Gesundheitsdaten-Sync via Webhook) Integration
📧 Gmail (E-Mail-Lesen via OAuth) Integration
📱 WhatsApp (Nachrichten via WhatsApp Cloud API) Integration

Familie & Kontakte

Feature Kategorie Status
👨‍👩‍👧 Kontakt-Manager (Kontakte speichern, Geburtstage, Notizen) Sozial
💬 Kontakt-Erinnerungen („Wann hast du zuletzt X kontaktiert?") Sozial
📨 Nachrichten-Relay (Nachrichten an Kontakte via Agent senden) Sozial
🛡️ Kontakt-Filter (genehmigungspflichtige Kommunikation) Sicherheit

Pflanzen & Timer

Feature Kategorie Status
🌱 Pflanzen-Tracker (Gieß-Erinnerungen, Pflegetipps) Lifestyle
⏲️ Timer-Service (Countdown, Intervall-Timer, Pomodoro) Produktivität

System

Feature Kategorie Status
🛡️ Rate Limiter (Schutz vor API-Überlastung) System
🔧 Error Recovery (Graceful Degradation bei Teilausfällen) System
💾 LLM-Cache (Antwort-Caching für Kosteneffizienz) System
📊 Cost Tracker (Token-Verbrauch & Kosten-Übersicht) System
💿 Auto-Backup (tägliches DB-Backup via Cron) System
🗄️ Data Retention (automatische Datenbereinigung) System
🏠 HACS-Integration (Sensoren, Services, UI-Konfiguration) System

🔒 Sicherheit & Datenschutz (Security & Privacy)

Der Agent wurde mit einem Security-First-Ansatz entwickelt:

Eingabeschutz

  • Alle Nutzereingaben werden auf Kontrollzeichen bereinigt und auf 4000 Zeichen begrenzt
  • Prompt-Injection-Erkennung: 11 Regex-Patterns blocken Manipulationsversuche
  • URLs werden gegen SSRF-Angriffe validiert (keine internen IPs)

API & Token-Sicherheit

  • API-Keys werden niemals geloggt oder gespeichert (automatische Maskierung)
  • Rate-Limiting: 30 Nachrichten/min, 50 LLM-Calls/h, 10 Web-Suchen/h
  • Alle externen API-Calls haben Timeouts (max 30s)

Datenkontrolle

  • Feature Gates: 29 einzelne Features an-/abschaltbar
  • Data Boundaries: 4 Stufen kontrollieren was im LLM-Prompt landet
  • Audit Log: Jede externe Datenübertragung wird protokolliert
  • Local Mode: Alle externen APIs deaktivierbar
  • No-Logs Mode: Konversationen werden nicht gespeichert

Script-Sicherheit

  • Benutzer-Skripte laufen in einer Sandbox (30s Timeout, kein Netzwerk)
  • Nur explizit erlaubte Python-Module
  • Dateizugriffe nur im data/-Verzeichnis

💡 Privacy by Default: Der Agent läuft komplett lokal. Nur Telegram-Nachrichten und LLM-Anfragen verlassen dein System.


🧠 Architektur

┌──────────────────────────────────────────────────────────────────────────┐
│                           Telegram-Nutzer                                 │
└──────────────────────────────┬───────────────────────────────────────────┘
                                │
                                ▼
┌──────────────────────────────────────────────────────────────────────────┐
│  PRÄSENTATION (src/telegram/)            ◄── python-telegram-bot         │
│  ┌───────────┐  ┌──────────┐  ┌──────────────────────────────────────┐  │
│  │  auth.py   │  │  bot.py  │  │  handlers/ (23)                      │  │
│  │  User-Check│  │  PTB-App │  │  help, sleep, tasks, goals, health,  │  │
│  │            │  │          │  │  feedback, timer, workout, budget,    │  │
│  │ contact_   │  │ convers- │  │  settings, setup, checkin, gmail,    │  │
│  │ chat.py    │  │ ation.py │  │  image, voice, file, aliases, ...    │  │
│  └───────────┘  └──────────┘  └──────────────┬───────────────────────┘  │
│  ┌───────────────────────────────────────────┴────────────────────────┐  │
│  │  router.py  —  Regex-First Intent Router (~60% direkte Treffer)    │  │
│  └──────────────────────────────┬─────────────────────────────────────┘  │
└─────────────────────────────────┼────────────────────────────────────────┘
                                   │ ~40% unerkannt
               ┌───────────────────┴────────────────────┐
               ▼                                        ▼
┌──────────────────────────┐            ┌──────────────────────────────┐
│  LLM-SCHICHT (src/llm/)  │            │  SERVICES (src/services/)     │
│  ┌─────────────────────┐ │            │  ┌──────────────────────────┐│
│  │ client.py           │ │            │  │ briefing · sleep_tracker  ││
│  │ (OpenRouter/OpenAI) │ │            │  │ goal_manager · memory     ││
│  ├─────────────────────┤ │            │  │ health_tracker · meals    ││
│  │ tool_registry (70+) │ │            │  │ sport_planner · timer     ││
│  │ tool_executor       │ │            │  │ contact_service · plants  ││
│  │ intent_parser       │ │            │  │ appointment_coordinator   ││
│  │ cache.py · cost.py  │ │            │  │ decision_helper · streak  ││
│  └─────────────────────┘ │            │  │ mood_journal · bills      ││
└──────────┬───────────────┘            │  └──────────────────────────┘│
           │                            │                              │
           │                            │  src/tools/ (12 Module)       │
           │                            │  reminders · tasks · health   │
           │                            │  contacts · plants · alexa   │
           │                            │  settings · ha · workout     │
           │                            │  presence · buttons · cal    │
           │                            │                              │
┌──────────┴────────────────────────────┴──────────────────────────────┐
│  INTELLIGENZ (20+ Module)           │  LERNEN (7 Module)              │
│  ┌──────────────────────────────┐   │  ┌──────────────────────────┐  │
│  │ adaptive_briefing · routines │   │  │ pattern_tracker           │  │
│  │ insight_engine · proactive   │   │  │ knowledge_graph           │  │
│  │ summarizer · self_improve    │   │  │ preference_learner        │  │
│  │ workflow · sleep_analyzer    │   │  │ prompt_optimizer          │  │
│  │ sleep_conversation · context │   │  │ prompt_rules              │  │
│  │ daytime_assistant · vacation │   │  │ reinforcement             │  │
│  │ habit_stacker · presence     │   │  │ dynamic_knowledge         │  │
│  │ appointment · plant_conv     │   │  └──────────────────────────┘  │
│  │ tomorrow_prep · training     │   │                                │
│  │ workout_analyzer · ha_learn  │   │  src/webhooks/                 │
│  └──────────────────────────────┘   │  apple_health.py               │
└─────────────────────────────────────┴────────────────────────────────┘
           │                                       │
┌──────────┴───────────────────────────────────────┴──────────────────┐
│  HINTERGRUND (src/scheduler/)  │  SCRIPTS (src/scripts/)             │
│  APScheduler · 27 Jobs         │  Engine + 21 Built-in Scripts       │
│  morning_routine · reminders   │  daily_briefing · habit_tracker     │
│  evening_routine · daytime     │  mood_tracker · travel_assistant    │
│  sleep_assistant · plants      │  expense_analytics · goal_tracker   │
│  health_digest · timer · vac   │  morning_routine · data_export      │
└─────────────────────────────────────────────────────────────────────┘
                                │
┌───────────────────────────────┴─────────────────────────────────────┐
│  INFRASTRUKTUR                                                       │
│  ┌──────────────────┐  ┌───────────────┐  ┌────────────────────────┐ │
│  │ src/database/     │  │ src/system/   │  │ src/cache/             │ │
│  │ SQLAlchemy 2.0    │  │ rate_limiter  │  │ state_cache            │ │
│  │ SQLite · 15+      │  │ error_recov   │  │ entity_cache           │ │
│  │ Tabellen          │  │ health.py     │  │ llm_response_cache     │ │
│  └──────────────────┘  └───────────────┘  └────────────────────────┘ │
│  src/integrations/ (20 Module)                                       │
│  weather · home_assistant · calendar · web_search · wikipedia        │
│  apple_health · gmail · whatsapp · ha_events · ha_alexa · ha_buttons │
│  src/security/                                                       │
│  input_sanitizer · contact_filter                                    │
└──────────────────────────────────────────────────────────────────────┘

┌──────────────────────────────────────────────────────────────────────────┐ │ Telegram-Nutzer │ └──────────────────────────────┬───────────────────────────────────────────┘ │ ▼ ┌──────────────────────────────────────────────────────────────────────────┐ │ PRÄSENTATION (src/telegram/) ◄── python-telegram-bot │ │ ┌───────────┐ ┌──────────┐ ┌──────────────────────────────────────┐ │ │ │ auth.py │ │ bot.py │ │ handlers/ (16) │ │ │ │ User-Check│ │ PTB-App │ │ help, sleep, tasks, goals, health │ │ │ └───────────┘ └──────────┘ └──────────────┬───────────────────────┘ │ │ ┌───────────────────────────────────────────┴────────────────────────┐ │ │ │ router.py — Regex-First Intent Router (~60% direkte Treffer) │ │ │ └──────────────────────────────┬─────────────────────────────────────┘ │ └─────────────────────────────────┼────────────────────────────────────────┘ │ ~40% unerkannt ┌───────────────────┴────────────────────┐ ▼ ▼ ┌──────────────────────────┐ ┌──────────────────────────┐ │ LLM-SCHICHT (src/llm/) │ │ SERVICES (src/services/) │ │ ┌─────────────────────┐ │ │ ┌────────────────────┐ │ │ │ client.py │ │ │ │ briefing.py │ │ │ │ (OpenRouter/OpenAI) │ │ │ │ sleep_tracker.py │ │ │ ├─────────────────────┤ │ │ │ goal_manager.py │ │ │ │ tool_registry (60+) │ │ │ │ health_tracker.py │ │ │ │ tool_executor │ │ │ │ memory.py │ │ │ │ intent_parser │ │ │ └────────────────────┘ │ │ │ cache.py · cost.py │ │ │ │ │ └─────────────────────┘ │ │ src/integrations/ │ └──────────┬───────────────┘ │ weather · ha · calendar │ │ │ web_search · wikipedia │ │ └──────────┬───────────────┘ │ │ ┌──────────┴───────────────────────────────────────┴──────────────┐ │ INTELLIGENZ & LERNEN │ │ ┌────────────────────────────────┐ ┌────────────────────────┐ │ │ │ 7 Module (src/intelligence/) │ │ 5 Module (src/learning/)│ │ │ │ adaptive_briefing · insights │ │ pattern_tracker │ │ │ │ proactive · summarizer │ │ knowledge_graph │ │ │ │ self_improve · workflow │ │ preference_learner │ │ │ │ conversation_starter │ │ prompt_optimizer │ │ │ │ sleep_analyzer │ │ dynamic_knowledge │ │ │ └────────────────────────────────┘ └────────────────────────┘ │ └─────────────────────────────────────────────────────────────────┘ │ │ ┌──────────┴───────────────────────────────────────┴──────────────┐ │ HINTERGRUND (src/scheduler/) │ SCRIPTS (src/scripts/) │ │ APScheduler · 15 Jobs │ Engine + 16 Built-in Scripts │ │ morning · reminders · temps │ daily_briefing · habit_tracker │ │ checkins · calendar · backup │ mood_tracker · travel_assistant│ └─────────────────────────────────────────────────────────────────┘ │ ┌──────────────────────────────┴──────────────────────────────────┐ │ INFRASTRUKTUR │ │ ┌─────────────────┐ ┌──────────────┐ ┌────────────────────┐ │ │ │ src/database/ │ │ src/system/ │ │ src/cache/ │ │ │ │ SQLAlchemy 2.0 │ │ rate_limiter │ │ state_cache │ │ │ │ SQLite · 13+ │ │ error_recov │ │ entity_cache │ │ │ │ Tabellen │ │ health.py │ │ llm_response_cache │ │ │ └─────────────────┘ └──────────────┘ └────────────────────┘ │ └──────────────────────────────────────────────────────────────────┘


**Design-Prinzipien:**
- **Regex-First**: ~60% der Nachrichten per Regex erkannt → kein LLM-Aufruf → Kostenersparnis
- **Async-First**: Vollständig asynchron (`aiohttp`, `aiosqlite`, `apscheduler` AsyncIO)
- **Multi-Model**: cheap-Modell (~80% der Calls), strong-Modell (~15%), reasoning-Modell (~5%)
- **Export Pattern**: Jedes Modul exportiert saubere öffentliche API via `__init__.py`
- **Graceful Degradation**: Funktioniert auch bei Teilausfällen (HA offline, Wetter-API down, etc.)
- **Webhook-Support**: Apple Health-Daten per Webhook integrierbar
- **Family-Ready**: Kontakt-Management mit Genehmigungs-Flow für Kommunikation mit Dritten

---

### 🚀 Deployment

| Option | Aufwand | Geeignet für |
|---|---|---|
| **Standalone** | `pip install && python -m src.main` | Entwicklung, Test |
| **systemd Service** | `sudo cp deploy/pai-agent.service /etc/systemd/system/` | Linux Server, Raspberry Pi |

| **HA Add-on** | Via HACS installieren | Home Assistant OS/Supervised |

#### systemd (Produktion)

```bash
# Einrichtung
sudo useradd -r -s /bin/false agent
sudo mkdir -p /opt/pai-agent
sudo cp -r . /opt/pai-agent/
sudo chown -R agent:agent /opt/pai-agent/
sudo -u agent python3.12 -m venv /opt/pai-agent/.venv
sudo -u agent /opt/pai-agent/.venv/bin/pip install -r /opt/pai-agent/requirements.txt

# Service aktivieren
sudo cp deploy/pai-agent.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable --now pai-agent
sudo systemctl status pai-agent

System-Voraussetzungen

  • Python 3.12+
  • SQLite (keine externe DB nötig)
  • ~50 MB RAM
  • Läuft auf: Raspberry Pi, Mini-PC, VPS, NAS

📋 Befehle & Tools (70+)

Kategorie Tools
Produktivität create_reminder, list_reminders, create_task, list_tasks, complete_task, create_note, list_notes, get_status, get_today_summary, timer_start, timer_status
Gesundheit log_sleep, log_symptom, log_food, log_energy, log_workout, get_health_report, analyze_sleep_quality, suggest_sleep_improvements, get_health_digest, get_health_score
Budget log_expense, get_budget_status, get_expense_analytics, track_bill
Intelligenz get_insights, get_reflection, check_habits, get_productivity_stats, get_learning_status, get_social_reminders, analyze_decision
Wissen search_memory, add_memory, update_user_info, web_search, fetch_webpage, get_news, translate_text, wikipedia_search, wikipedia_article, on_this_day
Smart Home control_ha_light, get_ha_state, run_ha_script, discover_smart_home, get_room_temperature, get_optimal_sleep_conditions, alexa_speak, setup_button, goodnight_routine, wakeup_routine
Kontakte add_contact, list_contacts, send_to_contact, set_contact_approval
Pflanzen add_plant, water_plant, list_plants, watering_schedule, plant_tips
Personalisierung track_mood, save_thought, quick_action, set_phase, set_vacation_mode, get_settings, set_setting, get_briefing_time, get_help, get_locale_settings, set_personality, apply_behavior_profile
Termine get_todays_events, get_calendar_status, add_calendar, sync_calendars, schedule_appointment
Präsenz am_i_home, get_presence_summary

📖 Volle Tool-Referenz: docs/TOOLS.md


English

What is this?

The Personal AI Platform is an AI-powered Telegram bot that acts as your 24/7 personal assistant. It learns your habits, tracks your health, controls your smart home, reminds you of tasks — and gets better with every interaction.

  • 🤖 Telegram Bot — chat naturally, as if with a human
  • 🧠 70+ LLM Tools — productivity, health, smart home, contacts, plants, personalization
  • ☀️ Adaptive Briefing — learns your wake time, sends a personalized morning overview
  • 🏠 HACS Integration — official Home Assistant Community Store with sensors & services
  • 📊 20+ Intelligence Modules — insights, routines, sleep coach, scheduling, workflows
  • 🧬 7 Learning Modules — pattern tracking, knowledge graph, preference learning, prompt rules
  • 🔧 21 Built-in Scripts — daily briefing, habit tracker, mood tracker, travel assistant & more
  • 27 Scheduler Jobs — auto check-ins, reminders, calendar sync, routines, plant care

⚡ Quickstart

Option A: Standalone (5 minutes)

git clone https://github.com/DevOpsOfChaos/personal-ai-platform.git
cd personal-ai-platform
pip install -r requirements.txt
python setup_wizard.py
python -m src.main

Option B: HACS (Home Assistant)

  1. HACS → Integrations → ⋮ (Menu) → Custom repositories
  2. URL: https://github.com/DevOpsOfChaos/personal-ai-platform
  3. Category: Integration
  4. Install "Personal AI Agent"
  5. Settings → Devices & Services → Add Integration → Personal AI Agent
  6. Install agent code under /config/pai_agent/:
    cd /config && git clone https://github.com/DevOpsOfChaos/personal-ai-platform.git pai_agent
    cd pai_agent && pip install -r requirements.txt

🔌 APIs & Costs

API Required? Cost Purpose
📡 Telegram Bot API ✅ Yes Free Message receive & send
🧠 OpenRouter ✅ Yes Pay-per-use LLM access (free models available)
🤖 OpenAI ⬜ Optional Pay-per-use Alternative to OpenRouter
🌤️ OpenWeatherMap ⬜ Optional Free (1000 calls/day) Weather in briefings
🏠 Home Assistant ⬜ Optional Local & free Smart home control & sensors
📅 Google Calendar ⬜ Optional Free (via HA) Calendar events
🌐 DuckDuckGo ⬜ Optional Free Web search & news
📖 Wikipedia ⬜ Optional Free Article search & summaries

💡 With free OpenRouter models: $0/month.
Append :free to the model name (e.g., meta-llama/llama-4-maverick:free).

📖 Switching providers: docs/API_PROVIDERS.md

🎯 Feature Matrix

Core

Feature Category Status
📋 Telegram Commands (/today, /tasks, /reminders, /notes, /goals, /status, /help, /settings) Productivity
✅ Task Manager (priority, deadlines, status tracking, templates) Productivity
⏰ Reminders (natural language) Productivity
📝 Notes & Thoughts (tagged) Productivity
🌅 Morning Briefing (weather, calendar, tasks, insights) Intelligence
🌅 Morning Routine (AI-guided start to the day) Intelligence
🌞 Daytime Assistant (proactive daytime nudges) Intelligence
🌇 Evening Routine (reflection & tomorrow prep) Intelligence
🧠 LLM Fallback (70+ tools via intent parser) LLM
📊 Insight Engine (correlations, trends, anomalies) Intelligence
🔄 Self-Improve (optimizes based on feedback) Intelligence
🔄 Feedback Learning (learns from user feedback) Intelligence

Health & Sleep

Feature Category Status
😴 Sleep Tracking Health
🧠 Smart Sleep Flow (AI-guided sleep/wake) Health
📈 Sleep Analysis (patterns, averages, deficit alerts) Health
💊 Health Tracker (symptoms, medication, energy, meals) Health
💊 Medication Tracker (reminders & compliance) Health
🏋️ Workout Planner (gym, running, cycling) Health
🍏 Apple Health Bridge (health data sync) Health

Learning

Feature Category Status
🧩 Pattern Tracker (behavioral pattern detection) Learning
❤️ Preference Learner (learns from interactions) Learning
🔗 Knowledge Graph Learning 🧪
📚 Dynamic Knowledge (continuous updates) Learning
📏 Prompt Rules (context-aware prompt adjustment) Learning
🔄 Reinforcement (learning from user feedback) Learning 🧪

Integrations

Feature Category Status
🌤️ Weather (current + 5-day forecast) Integration
📅 Calendar (Google Calendar, iCal, HA-based) Integration
🏠 Home Assistant (lights, sensors, scripts, media, Alexa, buttons) Integration
🌐 Web Search (with source attribution) Integration
📖 Wikipedia (article search & summaries) Integration
📰 News (headlines by topic/country) Integration
🌍 Translation (any language) Integration
🍏 Apple Health (health data via webhook) Integration
📧 Gmail (email via OAuth) Integration
📱 WhatsApp (messages via Cloud API) Integration

Family & Contacts

Feature Category Status
👨‍👩‍👧 Contact Manager (save contacts, birthdays, notes) Social
💬 Contact Reminders ("When did you last contact X?") Social
📨 Message Relay (send messages to contacts via agent) Social
🛡️ Contact Filter (approval-based communication) Security

Plants & Timer

Feature Category Status
🌱 Plant Tracker (watering reminders, care tips) Lifestyle
⏲️ Timer Service (countdown, interval, pomodoro) Productivity

System

Feature Category Status
🛡️ Rate Limiter System
🔧 Error Recovery (graceful degradation) System
💾 LLM Cache (response caching) System
📊 Cost Tracker (token usage & costs) System
💿 Auto-Backup (daily DB backup) System
🗄️ Data Retention (auto cleanup) System
🏠 HACS Integration (sensors, services, UI config) System

🔒 Sicherheit & Datenschutz (Security & Privacy)

Der Agent wurde mit einem Security-First-Ansatz entwickelt:

Eingabeschutz

  • Alle Nutzereingaben werden auf Kontrollzeichen bereinigt und auf 4000 Zeichen begrenzt
  • Prompt-Injection-Erkennung: 11 Regex-Patterns blocken Manipulationsversuche
  • URLs werden gegen SSRF-Angriffe validiert (keine internen IPs)

API & Token-Sicherheit

  • API-Keys werden niemals geloggt oder gespeichert (automatische Maskierung)
  • Rate-Limiting: 30 Nachrichten/min, 50 LLM-Calls/h, 10 Web-Suchen/h
  • Alle externen API-Calls haben Timeouts (max 30s)

Datenkontrolle

  • Feature Gates: 29 einzelne Features an-/abschaltbar
  • Data Boundaries: 4 Stufen kontrollieren was im LLM-Prompt landet
  • Audit Log: Jede externe Datenübertragung wird protokolliert
  • Local Mode: Alle externen APIs deaktivierbar
  • No-Logs Mode: Konversationen werden nicht gespeichert

Script-Sicherheit

  • Benutzer-Skripte laufen in einer Sandbox (30s Timeout, kein Netzwerk)
  • Nur explizit erlaubte Python-Module
  • Dateizugriffe nur im data/-Verzeichnis

💡 Privacy by Default: Der Agent läuft komplett lokal. Nur Telegram-Nachrichten und LLM-Anfragen verlassen dein System.


🧠 Architecture

┌──────────────────────────────────────────────────────────────────┐
│                        Telegram User                              │
└─────────────────────────────┬────────────────────────────────────┘
                               │
                               ▼
┌──────────────────────────────────────────────────────────────────┐
│  PRESENTATION (src/telegram/)                                     │
│  auth · bot · router (Regex-First, ~60% direct) · 23 handlers    │
│  contact_chat · conversation · custom_messages                    │
└─────────────────────────────┬────────────────────────────────────┘
                               │ ~40% unrecognized
           ┌───────────────────┴──────────────────┐
           ▼                                      ▼
┌──────────────────────┐          ┌──────────────────────────────┐
│  LLM LAYER (src/llm/)│          │  SERVICES + TOOLS             │
│  client · 70+ tools  │          │  src/services/ (24 modules)   │
│  intent_parser       │          │  briefing · sleep · goals     │
│  cache · cost        │          │  health · memory · timer      │
└──────────┬───────────┘          │  contacts · plants · meals    │
           │                      │  appointments · decisions     │
           │                      │                              │
           │                      │  src/tools/ (12 modules)      │
           │                      │  reminders · tasks · health   │
           │                      │  contacts · plants · alexa    │
           │                      │  settings · ha · workout      │
           │                      │  presence · buttons · cal     │
           │                      │                              │
           │                      │  src/integrations/ (20 mods)  │
           │                      │  weather · ha · calendar      │
           │                      │  web_search · wikipedia       │
           │                      │  apple_health · gmail         │
           │                      │  whatsapp · ha_alexa          │
           │                      └──────────┬───────────────────┘
           │                                 │
┌──────────┴─────────────────────────────────┴────────────────────┐
│  INTELLIGENCE (20+ modules) │  LEARNING (7 modules)             │
│  insights · proactive       │  patterns · knowledge_graph       │
│  summarizer · workflow      │  preferences · prompt_opt         │
│  self_improve · adaptive    │  prompt_rules · reinforcement     │
│  routines · sleep_coach     │  dynamic_knowledge                │
│  daytime · evening · plants │                                  │
│  appointments · presence    │  src/webhooks/                    │
│  tomorrow · training · vac  │  apple_health.py                  │
│  workout_analyzer · ctx     │                                   │
└─────────────────────────────────────────────────────────────────┘
                               │
┌──────────────────────────────┴──────────────────────────────────┐
│  BACKGROUND (src/scheduler/) │  SCRIPTS (src/scripts/)           │
│  APScheduler · 27 jobs       │  Engine + 21 built-in scripts     │
│  morning_routine · evening   │  daily_briefing · habit_tracker   │
│  daytime · sleep · plants    │  mood · travel · expense_analytics│
│  timer · health_digest · vac │  goal · health · morning_routine  │
│  reminder_dispatch · cal     │  export · import · reflection     │
└──────────────────────────────┴──────────────────────────────────┘
                               │
┌──────────────────────────────┴──────────────────────────────────┐
│  INFRASTRUCTURE                                                  │
│  database/ (SQLAlchemy 2.0 · SQLite · 15+ tables)              │
│  system/ (rate_limiter · error_recovery · health)              │
│  cache/  (state_cache · entity_cache · llm_response_cache)      │
│  security/ (input_sanitizer · contact_filter)                   │
└──────────────────────────────────────────────────────────────────┘

Design Principles:

  • Regex-First: ~60% regex hits → no LLM call → cost savings
  • Async-First: Fully asynchronous (aiohttp, aiosqlite, apscheduler AsyncIO)
  • Multi-Model: cheap (~80% calls), strong (~15%), reasoning (~5%)
  • Export Pattern: Clean public API from each module via __init__.py
  • Graceful Degradation: Works through partial failures (HA offline, weather API down)
  • Webhook Support: Apple Health data via webhook integration
  • Family-Ready: Contact management with approval flow for third-party communication

🚀 Deployment

Option Effort Best for
Standalone pip install && python -m src.main Dev, testing
systemd Service sudo cp deploy/pai-agent.service /etc/systemd/system/ Linux server, RPi

| HA Add-on | Install via HACS | HA OS/Supervised |

System Requirements:

  • Python 3.12+
  • SQLite (no external DB needed)
  • ~50 MB RAM
  • Runs on: Raspberry Pi, Mini-PC, VPS, NAS

📚 Documentation

Dokument Inhalt
Setup Guide Schritt-für-Schritt Einrichtung
Onboarding Setup Wizard Walkthrough
HACS Integration HACS-Installation & -Konfiguration
API Providers LLM-Provider wechseln & konfigurieren
API Reference Verwendete APIs & Datenflüsse
Tools Reference Alle 70+ LLM-Tools mit Beispielen
Architecture Technische Architektur
Home Assistant Setup HA-Integration einrichten
Apple Health Setup Apple Health Webhook einrichten
WhatsApp Setup WhatsApp Cloud API einrichten
Security Features Sicherheits-Features im Detail
Contributing Mitmachen & Code-Style
Security Security Policy
Changelog Versions-Historie

📄 License

MIT License — see LICENSE.


Built with ❤️ using Python, SQLAlchemy, python-telegram-bot, OpenRouter, and more.

About

Dein persönlicher KI-Agent. Telegram-Bot mit 50+ Tools, natürlicher Sprache & optionaler Home-Assistant-Integration

Topics

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors