268 lines
8.3 KiB
Python
268 lines
8.3 KiB
Python
"""Adaptive system prompt builder.
|
|
|
|
Dynamically adjusts system prompts based on user interaction patterns
|
|
to reduce repeated mistakes and improve relevance.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
from .user_stats import UserStats, UserStatsTracker
|
|
|
|
|
|
class AdaptivePromptBuilder:
|
|
"""Builds adaptive system prompts based on user statistics."""
|
|
|
|
def __init__(
|
|
self,
|
|
user_id: str,
|
|
storage_dir: Path | None = None,
|
|
stats_days: int = 30,
|
|
) -> None:
|
|
"""Initialize adaptive prompt builder.
|
|
|
|
Args:
|
|
user_id: User identifier for personalization
|
|
storage_dir: Feedback storage directory (default: ~/.cache/crystal/feedback)
|
|
stats_days: Number of days to analyze for stats
|
|
"""
|
|
self.user_id = user_id
|
|
self.stats_days = stats_days
|
|
|
|
if storage_dir is None:
|
|
storage_dir = Path.home() / ".cache" / "crystal" / "feedback"
|
|
|
|
self.tracker = UserStatsTracker(storage_dir)
|
|
self._stats: UserStats | None = None
|
|
|
|
@property
|
|
def stats(self) -> UserStats:
|
|
"""Get or compute user stats (cached)."""
|
|
if self._stats is None:
|
|
self._stats = self.tracker.get_user_stats(
|
|
self.user_id, days=self.stats_days
|
|
)
|
|
return self._stats
|
|
|
|
def build(
|
|
self,
|
|
base_prompt: str,
|
|
context: dict[str, Any] | None = None,
|
|
) -> str:
|
|
"""Build adaptive prompt based on user stats.
|
|
|
|
Args:
|
|
base_prompt: Original system prompt
|
|
context: Optional context dict with:
|
|
- recent_low_confidence: bool
|
|
- current_topic: str
|
|
- session_corrections: int
|
|
|
|
Returns:
|
|
Enhanced system prompt with user-specific adaptations
|
|
"""
|
|
context = context or {}
|
|
sections = [base_prompt]
|
|
|
|
# Add frequent correction reminders
|
|
correction_section = self._build_correction_reminders()
|
|
if correction_section:
|
|
sections.append(correction_section)
|
|
|
|
# Add low-confidence topic disclaimers
|
|
confidence_section = self._build_confidence_disclaimers(context)
|
|
if confidence_section:
|
|
sections.append(confidence_section)
|
|
|
|
# Add domain focus hints
|
|
domain_section = self._build_domain_focus()
|
|
if domain_section:
|
|
sections.append(domain_section)
|
|
|
|
# Add error prevention hints
|
|
error_section = self._build_error_prevention()
|
|
if error_section:
|
|
sections.append(error_section)
|
|
|
|
return "\n\n".join(sections)
|
|
|
|
def _build_correction_reminders(self) -> str | None:
|
|
"""Build reminder section for frequent corrections."""
|
|
if not self.stats.corrections:
|
|
return None
|
|
|
|
patterns = self.stats.corrections.frequent_patterns
|
|
if not patterns:
|
|
return None
|
|
|
|
# Top 3 most frequent corrections
|
|
top_patterns = patterns[:3]
|
|
|
|
lines = ["## Frequent Corrections", "", "You often correct these patterns:"]
|
|
for original, replacement, count in top_patterns:
|
|
lines.append(f"- **Avoid:** \"{original}\" → **Use:** \"{replacement}\" (corrected {count}x)")
|
|
|
|
lines.append("")
|
|
lines.append("Please be extra careful with these terms to reduce repeated corrections.")
|
|
|
|
return "\n".join(lines)
|
|
|
|
def _build_confidence_disclaimers(
|
|
self, context: dict[str, Any]
|
|
) -> str | None:
|
|
"""Build disclaimer for low-confidence topics."""
|
|
if not self.stats.topics:
|
|
return None
|
|
|
|
low_conf_topics = self.stats.topics.low_confidence_topics
|
|
if not low_conf_topics:
|
|
return None
|
|
|
|
# Check if current context involves a low-confidence topic
|
|
current_topic = context.get("current_topic", "").lower()
|
|
is_low_confidence = any(
|
|
topic in current_topic for topic, _ in low_conf_topics
|
|
)
|
|
|
|
if not is_low_confidence and not context.get("recent_low_confidence"):
|
|
return None
|
|
|
|
lines = [
|
|
"## Confidence Notice",
|
|
"",
|
|
"Based on recent interactions, confidence may be lower for these topics:",
|
|
]
|
|
|
|
for topic, conf in low_conf_topics[:3]:
|
|
conf_pct = int(conf * 100)
|
|
lines.append(f"- {topic} (avg confidence: {conf_pct}%)")
|
|
|
|
lines.append("")
|
|
lines.append(
|
|
"Consider requesting additional context or verification for these areas."
|
|
)
|
|
|
|
return "\n".join(lines)
|
|
|
|
def _build_domain_focus(self) -> str | None:
|
|
"""Build domain-specific focus hints."""
|
|
if not self.stats.topics:
|
|
return None
|
|
|
|
primary_topics = self.stats.topics.primary_topics
|
|
if not primary_topics:
|
|
return None
|
|
|
|
# Check if user has strong focus on specific domains
|
|
total_interactions = sum(count for _, count in primary_topics)
|
|
if not total_interactions:
|
|
return None
|
|
|
|
# Calculate focus percentage for top topic
|
|
top_topic, top_count = primary_topics[0]
|
|
focus_pct = (top_count / total_interactions) * 100
|
|
|
|
# Only add hint if >60% focused on one topic
|
|
if focus_pct < 60:
|
|
return None
|
|
|
|
lines = [
|
|
"## Domain Focus",
|
|
"",
|
|
f"Note: This user primarily works with **{top_topic}** topics ({int(focus_pct)}% of interactions).",
|
|
"Prioritize information relevant to this domain when appropriate.",
|
|
]
|
|
|
|
return "\n".join(lines)
|
|
|
|
def _build_error_prevention(self) -> str | None:
|
|
"""Build error prevention hints based on common mistakes."""
|
|
if not self.stats.corrections:
|
|
return None
|
|
|
|
error_types = self.stats.corrections.common_error_types
|
|
if not error_types:
|
|
return None
|
|
|
|
# Only show if there are significant error patterns
|
|
total_errors = sum(count for _, count in error_types)
|
|
if total_errors < 5:
|
|
return None
|
|
|
|
lines = [
|
|
"## Error Prevention",
|
|
"",
|
|
"Common error types in corrections:",
|
|
]
|
|
|
|
for error_type, count in error_types[:3]:
|
|
pct = int((count / total_errors) * 100)
|
|
lines.append(f"- {error_type}: {pct}% of corrections")
|
|
|
|
lines.append("")
|
|
lines.append("Double-check content for these error types before responding.")
|
|
|
|
return "\n".join(lines)
|
|
|
|
def refresh_stats(self) -> None:
|
|
"""Force refresh of user stats from storage."""
|
|
self.tracker.clear_cache(self.user_id)
|
|
self._stats = None
|
|
|
|
def get_stats_summary(self) -> dict[str, Any]:
|
|
"""Get summary of user stats for debugging/monitoring.
|
|
|
|
Returns:
|
|
Dict with user statistics summary
|
|
"""
|
|
stats = self.stats
|
|
|
|
summary = {
|
|
"user_id": stats.user_id,
|
|
"period": {
|
|
"start": stats.period_start,
|
|
"end": stats.period_end,
|
|
},
|
|
"total_interactions": stats.total_interactions,
|
|
}
|
|
|
|
if stats.corrections:
|
|
summary["corrections"] = {
|
|
"total": stats.corrections.total_corrections,
|
|
"avg_confidence": round(stats.corrections.avg_confidence, 2),
|
|
"frequent_patterns_count": len(stats.corrections.frequent_patterns),
|
|
"top_error_types": [
|
|
type_name for type_name, _ in stats.corrections.common_error_types[:3]
|
|
],
|
|
}
|
|
|
|
if stats.topics:
|
|
summary["topics"] = {
|
|
"primary": [topic for topic, _ in stats.topics.primary_topics[:3]],
|
|
"low_confidence_count": len(stats.topics.low_confidence_topics),
|
|
}
|
|
|
|
return summary
|
|
|
|
|
|
def build_adaptive_prompt(
|
|
base_prompt: str,
|
|
user_id: str,
|
|
context: dict[str, Any] | None = None,
|
|
storage_dir: Path | None = None,
|
|
) -> str:
|
|
"""Convenience function to build adaptive prompt in one call.
|
|
|
|
Args:
|
|
base_prompt: Original system prompt
|
|
user_id: User identifier
|
|
context: Optional context dict
|
|
storage_dir: Feedback storage directory
|
|
|
|
Returns:
|
|
Enhanced system prompt
|
|
"""
|
|
builder = AdaptivePromptBuilder(user_id, storage_dir)
|
|
return builder.build(base_prompt, context)
|