Add adaptive learning and model rollback
This commit is contained in:
@@ -146,6 +146,14 @@ class DecisionFactor(BaseModel):
|
||||
evidence: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class AdaptiveWeightUpdate(BaseModel):
|
||||
entity_id: str
|
||||
previous_weight: float = Field(ge=0.0, le=1.0)
|
||||
new_weight: float = Field(ge=0.0, le=1.0)
|
||||
reason: str = Field(max_length=300)
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class SafetyRule(BaseModel):
|
||||
rule_id: str = Field(pattern=r"^[a-z0-9_-]{1,64}$")
|
||||
label: str = Field(min_length=1, max_length=160)
|
||||
@@ -196,6 +204,33 @@ class ExecutionEvent(BaseModel):
|
||||
executed_at: datetime
|
||||
|
||||
|
||||
class ModelSnapshot(BaseModel):
|
||||
version_id: str
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
sample_count: int = Field(default=0, ge=0)
|
||||
high_confidence_sample_count: int = Field(default=0, ge=0)
|
||||
average_confidence: float = Field(default=0.0, ge=0.0, le=1.0)
|
||||
incorrect_feedback_count: int = Field(default=0, ge=0)
|
||||
patterns: list[BehaviorPattern] = Field(default_factory=list)
|
||||
reason: str = Field(default="", max_length=500)
|
||||
|
||||
|
||||
class AutomationConflict(BaseModel):
|
||||
automation_entity_id: str = Field(pattern=r"^automation\.[a-z0-9_]+$")
|
||||
severity: str = Field(default="info", max_length=20)
|
||||
status: str = Field(default="open", max_length=40)
|
||||
reason: str = Field(max_length=500)
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|
||||
|
||||
|
||||
class TimeProfile(BaseModel):
|
||||
profile_id: str = Field(pattern=r"^[a-z0-9_-]{1,64}$")
|
||||
label: str = Field(min_length=1, max_length=80)
|
||||
sample_count: int = Field(default=0, ge=0)
|
||||
dominant_state: str | None = None
|
||||
confidence: float = Field(default=0.0, ge=0.0, le=1.0)
|
||||
|
||||
|
||||
class RelatedAutomation(BaseModel):
|
||||
entity_id: str = Field(pattern=r"^automation\.[a-z0-9_]+$")
|
||||
config_id: str = Field(min_length=1, max_length=120)
|
||||
@@ -230,6 +265,11 @@ class BehaviorState(BaseModel):
|
||||
confidence_trend: list[float] = Field(default_factory=list)
|
||||
correct_feedback_count: int = Field(default=0, ge=0)
|
||||
incorrect_feedback_count: int = Field(default=0, ge=0)
|
||||
model_snapshots: list[ModelSnapshot] = Field(default_factory=list)
|
||||
active_model_version: str | None = None
|
||||
adaptive_weight_updates: list[AdaptiveWeightUpdate] = Field(default_factory=list)
|
||||
automation_conflicts: list[AutomationConflict] = Field(default_factory=list)
|
||||
time_profiles: list[TimeProfile] = Field(default_factory=list)
|
||||
|
||||
|
||||
class ActuatorRecord(BaseModel):
|
||||
|
||||
@@ -60,6 +60,10 @@ class SafetyProfileRequest(BaseModel):
|
||||
safety: SafetyProfile
|
||||
|
||||
|
||||
class ModelRollbackRequest(BaseModel):
|
||||
version_id: str = Field(min_length=1, max_length=120)
|
||||
|
||||
|
||||
class ActuatorSuggestion(BaseModel):
|
||||
entity_id: str
|
||||
domain: str
|
||||
@@ -408,6 +412,20 @@ def set_safety_profile(
|
||||
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.post("/{actuator_entity_id}/model/rollback", response_model=ActuatorRecord)
|
||||
def rollback_model(
|
||||
actuator_entity_id: str,
|
||||
payload: ModelRollbackRequest,
|
||||
request: Request,
|
||||
) -> ActuatorRecord:
|
||||
try:
|
||||
return _behavior(request).rollback_model(actuator_entity_id, version_id=payload.version_id)
|
||||
except KeyError as exc:
|
||||
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
||||
|
||||
|
||||
@router.post("/{actuator_entity_id}/activation", response_model=ActuatorRecord)
|
||||
def set_activation(
|
||||
actuator_entity_id: str,
|
||||
|
||||
@@ -7,6 +7,8 @@ from zoneinfo import ZoneInfo
|
||||
|
||||
from app.actuators.models import (
|
||||
ActuatorRecord,
|
||||
AdaptiveWeightUpdate,
|
||||
AutomationConflict,
|
||||
BehaviorMode,
|
||||
BehaviorPattern,
|
||||
BehaviorPrediction,
|
||||
@@ -14,9 +16,12 @@ from app.actuators.models import (
|
||||
BehaviorStatus,
|
||||
DecisionFactor,
|
||||
ExecutionEvent,
|
||||
ManualOverride,
|
||||
ModelSnapshot,
|
||||
RelatedAutomation,
|
||||
SafetyProfile,
|
||||
SafetyStage,
|
||||
TimeProfile,
|
||||
)
|
||||
from app.actuators.store import ActuatorStore
|
||||
from app.config import Settings
|
||||
@@ -168,6 +173,7 @@ class BehaviorEngine:
|
||||
"eindeutig zugeordnete Handlungen fehlen."
|
||||
)
|
||||
)
|
||||
model_version_id = f"model-{now.strftime('%Y%m%d%H%M%S')}"
|
||||
behavior = record.behavior.model_copy(
|
||||
update={
|
||||
"status": status,
|
||||
@@ -182,6 +188,18 @@ class BehaviorEngine:
|
||||
"knowledge": _knowledge_lines(record, len(patterns), trusted_actions),
|
||||
"assumptions": _assumption_lines(record),
|
||||
"uncertainties": _uncertainty_lines(record, len(patterns), trusted_actions),
|
||||
"time_profiles": _time_profiles(patterns),
|
||||
"model_snapshots": _next_model_snapshots(
|
||||
record.behavior.model_snapshots,
|
||||
model_version_id,
|
||||
patterns[-_MAX_PATTERNS:],
|
||||
len(patterns),
|
||||
trusted_actions,
|
||||
_average(record.behavior.confidence_trend),
|
||||
record.behavior.incorrect_feedback_count,
|
||||
reason,
|
||||
),
|
||||
"active_model_version": model_version_id,
|
||||
}
|
||||
)
|
||||
return self._save_behavior(record, behavior)
|
||||
@@ -454,6 +472,11 @@ class BehaviorEngine:
|
||||
reason = "Vorhersage wurde vom Nutzer als falsch markiert."
|
||||
correct_count = record.behavior.correct_feedback_count
|
||||
incorrect_count = record.behavior.incorrect_feedback_count + 1
|
||||
adaptive_updates, manual_override = _adapt_sensor_weights(
|
||||
record,
|
||||
current_context,
|
||||
correct=correct,
|
||||
)
|
||||
behavior = record.behavior.model_copy(
|
||||
update={
|
||||
"patterns": patterns[-_MAX_PATTERNS:],
|
||||
@@ -466,6 +489,39 @@ class BehaviorEngine:
|
||||
"last_trained_at": now,
|
||||
"correct_feedback_count": correct_count,
|
||||
"incorrect_feedback_count": incorrect_count,
|
||||
"adaptive_weight_updates": [
|
||||
*record.behavior.adaptive_weight_updates,
|
||||
*adaptive_updates,
|
||||
][-50:],
|
||||
}
|
||||
)
|
||||
record_for_save = (
|
||||
record.model_copy(update={"manual_override": manual_override})
|
||||
if manual_override is not None
|
||||
else record
|
||||
)
|
||||
return self._save_behavior(record_for_save, behavior)
|
||||
|
||||
def rollback_model(
|
||||
self,
|
||||
actuator_entity_id: str,
|
||||
*,
|
||||
version_id: str,
|
||||
) -> ActuatorRecord:
|
||||
record = self._store.get(actuator_entity_id)
|
||||
snapshot = next(
|
||||
(item for item in record.behavior.model_snapshots if item.version_id == version_id),
|
||||
None,
|
||||
)
|
||||
if snapshot is None:
|
||||
raise ValueError("Modell-Snapshot nicht gefunden.")
|
||||
behavior = record.behavior.model_copy(
|
||||
update={
|
||||
"patterns": snapshot.patterns,
|
||||
"sample_count": snapshot.sample_count,
|
||||
"high_confidence_sample_count": snapshot.high_confidence_sample_count,
|
||||
"active_model_version": snapshot.version_id,
|
||||
"reason": f"Rollback auf Modell-Snapshot {snapshot.version_id}.",
|
||||
}
|
||||
)
|
||||
return self._save_behavior(record, behavior)
|
||||
@@ -499,7 +555,10 @@ class BehaviorEngine:
|
||||
)
|
||||
]
|
||||
behavior = record.behavior.model_copy(
|
||||
update={"related_automations": related}
|
||||
update={
|
||||
"related_automations": related,
|
||||
"automation_conflicts": _automation_conflicts(record, related),
|
||||
}
|
||||
)
|
||||
return self._save_behavior(record, behavior)
|
||||
|
||||
@@ -990,6 +1049,165 @@ def _uncertainty_lines(
|
||||
return lines or ["Keine kritische Unsicherheit aus den lokalen Daten erkannt."]
|
||||
|
||||
|
||||
def _next_model_snapshots(
|
||||
existing: list[ModelSnapshot],
|
||||
version_id: str,
|
||||
patterns: list[BehaviorPattern],
|
||||
sample_count: int,
|
||||
trusted_actions: int,
|
||||
average_confidence: float,
|
||||
incorrect_feedback_count: int,
|
||||
reason: str,
|
||||
) -> list[ModelSnapshot]:
|
||||
snapshot = ModelSnapshot(
|
||||
version_id=version_id,
|
||||
sample_count=sample_count,
|
||||
high_confidence_sample_count=trusted_actions,
|
||||
average_confidence=round(average_confidence, 4),
|
||||
incorrect_feedback_count=incorrect_feedback_count,
|
||||
patterns=patterns,
|
||||
reason=reason,
|
||||
)
|
||||
return [*existing, snapshot][-10:]
|
||||
|
||||
|
||||
def _average(values: list[float]) -> float:
|
||||
return sum(values) / len(values) if values else 0.0
|
||||
|
||||
|
||||
def _time_profiles(patterns: list[BehaviorPattern]) -> list[TimeProfile]:
|
||||
buckets = {
|
||||
"night": ("Nacht", range(0, 360)),
|
||||
"morning": ("Morgen", range(360, 720)),
|
||||
"day": ("Tag", range(720, 1080)),
|
||||
"evening": ("Abend", range(1080, 1440)),
|
||||
}
|
||||
profiles: list[TimeProfile] = []
|
||||
for profile_id, (label, minutes) in buckets.items():
|
||||
selected = [pattern for pattern in patterns if pattern.minute_of_day in minutes]
|
||||
if not selected:
|
||||
profiles.append(TimeProfile(profile_id=profile_id, label=label))
|
||||
continue
|
||||
by_state: dict[str, int] = {}
|
||||
for pattern in selected:
|
||||
by_state[pattern.target_state] = by_state.get(pattern.target_state, 0) + 1
|
||||
dominant_state, count = max(by_state.items(), key=lambda item: (item[1], item[0]))
|
||||
profiles.append(
|
||||
TimeProfile(
|
||||
profile_id=profile_id,
|
||||
label=label,
|
||||
sample_count=len(selected),
|
||||
dominant_state=dominant_state,
|
||||
confidence=round(count / len(selected), 4),
|
||||
)
|
||||
)
|
||||
weekend = [pattern for pattern in patterns if pattern.weekday >= 5]
|
||||
profiles.append(
|
||||
TimeProfile(
|
||||
profile_id="weekend",
|
||||
label="Wochenende",
|
||||
sample_count=len(weekend),
|
||||
dominant_state=(
|
||||
max(
|
||||
{pattern.target_state: 0 for pattern in weekend},
|
||||
key=lambda state: sum(pattern.target_state == state for pattern in weekend),
|
||||
)
|
||||
if weekend
|
||||
else None
|
||||
),
|
||||
confidence=round(len(weekend) / len(patterns), 4) if patterns else 0.0,
|
||||
)
|
||||
)
|
||||
return profiles
|
||||
|
||||
|
||||
def _adapt_sensor_weights(
|
||||
record: ActuatorRecord,
|
||||
current_context: dict[str, str | None],
|
||||
*,
|
||||
correct: bool,
|
||||
) -> tuple[list[AdaptiveWeightUpdate], ManualOverride | None]:
|
||||
if not current_context:
|
||||
return [], record.manual_override
|
||||
candidates = {
|
||||
candidate.entity_id: candidate
|
||||
for candidate in [*record.numeric_candidates, *record.context_candidates]
|
||||
}
|
||||
previous = record.manual_override
|
||||
weights = dict(previous.sensor_weights if previous is not None else {})
|
||||
updates: list[AdaptiveWeightUpdate] = []
|
||||
delta = 0.03 if correct else -0.08
|
||||
for entity_id in current_context:
|
||||
candidate = candidates.get(entity_id)
|
||||
base = weights.get(
|
||||
entity_id,
|
||||
candidate.effective_weight if candidate is not None else 1.0,
|
||||
)
|
||||
new_weight = round(min(1.0, max(0.1, base + delta)), 4)
|
||||
if new_weight == base:
|
||||
continue
|
||||
weights[entity_id] = new_weight
|
||||
updates.append(
|
||||
AdaptiveWeightUpdate(
|
||||
entity_id=entity_id,
|
||||
previous_weight=round(base, 4),
|
||||
new_weight=new_weight,
|
||||
reason=(
|
||||
"Feedback korrekt: Kontextsignal leicht höher gewichtet."
|
||||
if correct
|
||||
else "Feedback falsch: Kontextsignal vorsichtig abgewertet."
|
||||
),
|
||||
)
|
||||
)
|
||||
if not updates:
|
||||
return [], previous
|
||||
return updates, ManualOverride(
|
||||
numeric_entity_id=(
|
||||
previous.numeric_entity_id
|
||||
if previous is not None
|
||||
else record.assignment.selected_numeric_entity_id
|
||||
),
|
||||
context_entity_ids=(
|
||||
previous.context_entity_ids
|
||||
if previous is not None
|
||||
else record.assignment.selected_context_entity_ids
|
||||
),
|
||||
sensor_weights=weights,
|
||||
sensor_weight_groups=previous.sensor_weight_groups if previous is not None else [],
|
||||
note="Sensor-Gewichtungen automatisch aus Feedback angepasst.",
|
||||
)
|
||||
|
||||
|
||||
def _automation_conflicts(
|
||||
record: ActuatorRecord,
|
||||
related: list[RelatedAutomation],
|
||||
) -> list[AutomationConflict]:
|
||||
conflicts: list[AutomationConflict] = []
|
||||
for automation in related:
|
||||
if record.behavior.mode is BehaviorMode.ACTIVE and automation.enabled:
|
||||
conflicts.append(
|
||||
AutomationConflict(
|
||||
automation_entity_id=automation.entity_id,
|
||||
severity="warning",
|
||||
status="open",
|
||||
reason=(
|
||||
"SillyHome ist aktiv, aber diese passende HA-Automation "
|
||||
"ist ebenfalls aktiv. Das kann zu konkurrierenden Schaltungen führen."
|
||||
),
|
||||
)
|
||||
)
|
||||
elif automation.entity_id in record.behavior.paused_automation_entity_ids:
|
||||
conflicts.append(
|
||||
AutomationConflict(
|
||||
automation_entity_id=automation.entity_id,
|
||||
severity="info",
|
||||
status="controlled",
|
||||
reason="Automation ist durch SillyHome pausiert.",
|
||||
)
|
||||
)
|
||||
return conflicts
|
||||
|
||||
|
||||
def predict_behavior(
|
||||
patterns: list[BehaviorPattern],
|
||||
*,
|
||||
|
||||
@@ -105,7 +105,7 @@ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
|
||||
app = FastAPI(
|
||||
title="SillyHome Next API",
|
||||
description="Lokales Smart-Home-Intelligenzsystem für Home Assistant.",
|
||||
version="1.1.0",
|
||||
version="1.2.0",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
app.state.settings = load_settings()
|
||||
|
||||
@@ -903,6 +903,11 @@ async function showActuator(actuatorId, evaluationMessage = "") {
|
||||
const knowledge = record.behavior.knowledge || [];
|
||||
const assumptions = record.behavior.assumptions || [];
|
||||
const uncertainties = record.behavior.uncertainties || [];
|
||||
const snapshots = record.behavior.model_snapshots || [];
|
||||
const activeModelVersion = record.behavior.active_model_version || "";
|
||||
const adaptiveUpdates = record.behavior.adaptive_weight_updates || [];
|
||||
const automationConflicts = record.behavior.automation_conflicts || [];
|
||||
const timeProfiles = record.behavior.time_profiles || [];
|
||||
const safetyControls = `
|
||||
<details class="manual-context" open>
|
||||
<summary>Sicherheit und manuelles Gegensteuern</summary>
|
||||
@@ -962,6 +967,43 @@ async function showActuator(actuatorId, evaluationMessage = "") {
|
||||
</div>
|
||||
</details>
|
||||
`;
|
||||
const adaptivePanel = `
|
||||
<details class="manual-context">
|
||||
<summary>v1.2 Lernen, Rollback und Konflikte</summary>
|
||||
<h3>Zeitprofile</h3>
|
||||
<div class="metric-grid">
|
||||
${timeProfiles.length ? timeProfiles.map(profile => `
|
||||
<div class="metric">
|
||||
<strong>${escapeHtml(profile.label)}</strong>
|
||||
${escapeHtml(profile.sample_count)} Samples · ${escapeHtml(profile.dominant_state || "offen")}
|
||||
<p class="muted">${Math.round((profile.confidence || 0) * 100)} % Profilklarheit</p>
|
||||
</div>
|
||||
`).join("") : "<div class='metric'><strong>Zeitprofile</strong>Noch keine Daten</div>"}
|
||||
</div>
|
||||
<h3>Modell-Snapshots</h3>
|
||||
<div class="decision-list">
|
||||
${snapshots.length ? snapshots.slice(-5).reverse().map(snapshot => `
|
||||
<div class="decision-row">
|
||||
<header>
|
||||
<strong>${escapeHtml(snapshot.version_id)}</strong>
|
||||
<span class="chip">${snapshot.version_id === activeModelVersion ? "aktiv" : "Rollback möglich"}</span>
|
||||
</header>
|
||||
<p class="muted">${escapeHtml(snapshot.sample_count)} Samples · ${escapeHtml(snapshot.high_confidence_sample_count)} eindeutig · Ø ${Math.round((snapshot.average_confidence || 0) * 100)} %</p>
|
||||
<p>${escapeHtml(snapshot.reason || "Kein Kommentar")}</p>
|
||||
${snapshot.version_id !== activeModelVersion ? `<button class="secondary compact" onclick="rollbackModel('${escapeHtml(record.actuator_entity_id)}', '${escapeHtml(snapshot.version_id)}')">Rollback</button>` : ""}
|
||||
</div>
|
||||
`).join("") : "<p class='muted'>Noch kein Modell-Snapshot gespeichert.</p>"}
|
||||
</div>
|
||||
<h3>Automatische Gewichtsanpassungen</h3>
|
||||
<ul>${adaptiveUpdates.length ? adaptiveUpdates.slice(-8).reverse().map(update => `
|
||||
<li><code>${escapeHtml(update.entity_id)}</code>: ${Math.round(update.previous_weight * 100)} % → ${Math.round(update.new_weight * 100)} %. ${escapeHtml(update.reason)}</li>
|
||||
`).join("") : "<li>Noch keine automatische Gewichtsanpassung.</li>"}</ul>
|
||||
<h3>Automation-Konflikte</h3>
|
||||
<ul>${automationConflicts.length ? automationConflicts.map(conflict => `
|
||||
<li><code>${escapeHtml(conflict.automation_entity_id)}</code>: <span class="${conflict.severity === "warning" ? "warn" : "muted"}">${escapeHtml(conflict.status)}</span> ${escapeHtml(conflict.reason)}</li>
|
||||
`).join("") : "<li>Keine aktiven Automation-Konflikte erkannt.</li>"}</ul>
|
||||
</details>
|
||||
`;
|
||||
const learnedAutomationActions = record.behavior.patterns.filter(
|
||||
pattern => pattern.source === "automation",
|
||||
).length;
|
||||
@@ -1073,6 +1115,7 @@ async function showActuator(actuatorId, evaluationMessage = "") {
|
||||
</div>
|
||||
${safetyControls}
|
||||
${decisionArchive}
|
||||
${adaptivePanel}
|
||||
<h3>Passende Home-Assistant-Automationen</h3>
|
||||
<p class="muted">Bei einer Übernahme pausiert SillyHome diese Automationen. Beim Stoppen können sie gezielt fortgesetzt werden.</p>
|
||||
<button class="secondary compact" onclick="refreshRelatedAutomations('${escapeHtml(record.actuator_entity_id)}')">Automationen neu suchen</button>
|
||||
@@ -1305,6 +1348,21 @@ async function saveSafetyProfile(actuatorId) {
|
||||
}
|
||||
}
|
||||
|
||||
async function rollbackModel(actuatorId, versionId) {
|
||||
if (!confirm(`${actuatorId}: wirklich auf Modell ${versionId} zurückrollen?`)) return;
|
||||
try {
|
||||
await api(`v1/actuators/${encodeURIComponent(actuatorId)}/model/rollback`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({version_id: versionId}),
|
||||
});
|
||||
invalidateDashboardCache();
|
||||
await loadConfiguredActuators();
|
||||
await showActuator(actuatorId, `Rollback auf ${versionId} ausgeführt.`);
|
||||
} catch (error) {
|
||||
alert(error.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function setActivation(actuatorId, active, pauseMatchingAutomations, restorePausedAutomations) {
|
||||
const question = active
|
||||
? pauseMatchingAutomations
|
||||
|
||||
Reference in New Issue
Block a user