File size: 6,103 Bytes
f69e608
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
"""
Self-healing prompt adapter for RetailMind.

Dynamically rewrites the LLM system prompt based on detected semantic drift.
This is the "self-healing" core β€” the system adapts its behavior in real time
without human intervention when it detects shifting user intent patterns.
"""

from __future__ import annotations

import logging
from dataclasses import dataclass

logger = logging.getLogger(__name__)

_BASE_PROMPT = (
    "You are RetailMind, a knowledgeable and friendly AI shopping assistant for "
    "an online retail store. You help customers find the perfect products from "
    "our catalog.\n\n"
    "RULES:\n"
    "1. ONLY recommend products that appear in the 'Available Inventory' below.\n"
    "2. Always mention the exact product name and price.\n"
    "3. Keep responses concise (3–5 sentences) but helpful.\n"
    "4. If a product matches the customer's needs, explain WHY it's a good fit.\n"
    "5. Never invent products that aren't in the inventory list."
)


@dataclass
class AdaptationRule:
    """A single self-healing rule triggered by a drift concept."""

    concept: str
    label: str
    prompt_injection: str
    explanation: str


# Pre-defined adaptation rules β€” each maps a drift signal to a prompt mutation
_RULES: dict[str, AdaptationRule] = {
    "price_sensitive": AdaptationRule(
        concept="price_sensitive",
        label="πŸ’° Price-Sensitive Mode",
        prompt_injection=(
            "\n\n⚠️ ACTIVE ADAPTATION β€” PRICE SENSITIVITY DETECTED:\n"
            "Customer intent analysis shows strong budget-consciousness. "
            "You MUST:\n"
            "β€’ Lead with the cheapest matching products first.\n"
            "β€’ Explicitly state the price and any savings.\n"
            "β€’ Compare price-to-value across options.\n"
            "β€’ Mention if an item is the lowest-priced in its category."
        ),
        explanation=(
            "πŸ”§ Self-Healing Activated\n"
            "━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
            "Signal: Price-sensitive keyword drift detected (budget, cheap, under $X)\n"
            "Action: Injected price-prioritization directives into system prompt\n"
            "Effect: LLM now ranks by price-to-value instead of general relevance\n"
            "Trigger: EWMA score exceeded threshold (0.38)"
        ),
    ),
    "summer_shift": AdaptationRule(
        concept="summer_shift",
        label="β˜€οΈ Summer Season Mode",
        prompt_injection=(
            "\n\n⚠️ ACTIVE ADAPTATION β€” SEASONAL SHIFT DETECTED:\n"
            "Query patterns indicate a seasonal shift toward summer. "
            "You MUST:\n"
            "β€’ Prioritize lightweight, breathable, and warm-weather products.\n"
            "β€’ Highlight UV protection and heat-management features.\n"
            "β€’ De-prioritize winter and cold-weather items.\n"
            "β€’ Mention materials suited for hot climates (linen, mesh, moisture-wicking)."
        ),
        explanation=(
            "πŸ”§ Self-Healing Activated\n"
            "━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
            "Signal: Seasonal semantic shift detected (summer, beach, UV, lightweight)\n"
            "Action: Injected warm-weather prioritization into system prompt\n"
            "Effect: LLM now filters for breathable materials and summer categories\n"
            "Trigger: EWMA score exceeded threshold (0.38)"
        ),
    ),
    "eco_trend": AdaptationRule(
        concept="eco_trend",
        label="🌿 Eco-Conscious Mode",
        prompt_injection=(
            "\n\n⚠️ ACTIVE ADAPTATION β€” SUSTAINABILITY TREND DETECTED:\n"
            "User intent strongly favors eco-friendly products. "
            "You MUST:\n"
            "β€’ Lead with recycled, organic, and plant-based items.\n"
            "β€’ Highlight environmental certifications (GOTS, OEKO-TEX).\n"
            "β€’ Explain the sustainability story behind each recommendation.\n"
            "β€’ Mention materials: recycled ocean plastic, organic cotton, bamboo, cork."
        ),
        explanation=(
            "πŸ”§ Self-Healing Activated\n"
            "━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
            "Signal: Eco-conscious trend detected (sustainable, recycled, organic)\n"
            "Action: Injected sustainability-first directives into system prompt\n"
            "Effect: LLM now leads with eco-credentials and material sourcing\n"
            "Trigger: EWMA score exceeded threshold (0.38)"
        ),
    ),
}

_NORMAL_EXPLANATION = (
    "πŸ“Š System Status: Normal\n"
    "━━━━━━━━━━━━━━━━━━━━━━━━━━\n"
    "No significant drift detected in user intent patterns.\n"
    "System prompt: Default balanced recommendation mode.\n"
    "All EWMA concept scores below threshold (0.38)."
)


class Adapter:
    """Stateless prompt adapter β€” maps drift signals to prompt mutations."""

    def __init__(self) -> None:
        self.base_prompt: str = _BASE_PROMPT
        self._active_rule: AdaptationRule | None = None

    def adapt_prompt(self, drift_state: str) -> str:
        """Return the adapted system prompt for the current drift state."""
        rule = _RULES.get(drift_state)
        self._active_rule = rule

        if rule:
            logger.info("Adaptation triggered: %s", rule.label)
            return self.base_prompt + rule.prompt_injection

        return self.base_prompt + "\n\nProvide balanced recommendations covering a mix of features, prices, and styles."

    def get_explanation(self, drift_state: str) -> str:
        """Human-readable explanation of what the adapter did and why."""
        rule = _RULES.get(drift_state)
        return rule.explanation if rule else _NORMAL_EXPLANATION

    def get_label(self, drift_state: str) -> str:
        """Short UI label for the active state."""
        rule = _RULES.get(drift_state)
        return rule.label if rule else "βš–οΈ Balanced Mode"