File size: 10,576 Bytes
de07704 | 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 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 | // ==========================================
// MEEZAN - ميزان Self-Reflection Engine
// After each session, Meezan reviews itself
// and generates lessons to improve
// Based on the "Reflexion" AI technique
// ==========================================
import Anthropic from '@anthropic-ai/sdk';
import * as fs from 'fs';
import * as path from 'path';
import { ReflectionNote, LearnedLesson, FeedbackSignal, KnowledgeGap } from '../types';
const client = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY
});
interface ConversationToReflect {
userId: string;
messages: Array<{ role: string; content: string }>;
feedbackSignals: FeedbackSignal[];
knowledgeGaps: KnowledgeGap[];
}
export class SelfReflectionEngine {
private dbPath: string;
private reflections: ReflectionNote[];
private lessons: LearnedLesson[];
private reflectionQueue: ConversationToReflect[];
constructor(dbPath: string = './data/reflections.json') {
this.dbPath = dbPath;
this.reflections = [];
this.lessons = [];
this.reflectionQueue = [];
this.load();
// Run reflection every 30 minutes on queued conversations
setInterval(() => this.processQueue(), 30 * 60 * 1000);
}
/**
* Queue a conversation for later reflection
* (non-blocking — runs in background)
*/
queueForReflection(conversation: ConversationToReflect): void {
this.reflectionQueue.push(conversation);
// Process immediately if queue gets large
if (this.reflectionQueue.length >= 5) {
this.processQueue();
}
}
/**
* Process queued conversations — runs in background
*/
async processQueue(): Promise<void> {
if (this.reflectionQueue.length === 0) return;
const toProcess = this.reflectionQueue.splice(0, 3); // Process 3 at a time
for (const conversation of toProcess) {
try {
await this.reflectOnConversation(conversation);
} catch (error) {
console.error('Reflection error:', error);
}
}
}
/**
* Core reflection — Claude analyzes its own conversation
*/
async reflectOnConversation(conversation: ConversationToReflect): Promise<ReflectionNote | null> {
if (conversation.messages.length < 2) return null;
const sessionId = `session_${Date.now()}`;
// Format conversation for analysis
const convText = conversation.messages
.map(m => `${m.role.toUpperCase()}: ${m.content}`)
.join('\n\n');
const feedbackSummary = conversation.feedbackSignals.length > 0
? conversation.feedbackSignals.map(f =>
`- Signal: ${f.signal} | Reason: ${f.reason}`
).join('\n')
: 'No explicit feedback signals detected.';
const gapsSummary = conversation.knowledgeGaps.length > 0
? conversation.knowledgeGaps.map(g =>
`- Topic: ${g.topic} (${g.category})`
).join('\n')
: 'No knowledge gaps detected.';
const reflectionPrompt = `You are Meezan's internal quality reviewer. Analyze this conversation and provide honest, structured feedback for self-improvement.
CONVERSATION:
${convText}
USER FEEDBACK SIGNALS:
${feedbackSummary}
DETECTED KNOWLEDGE GAPS:
${gapsSummary}
Analyze this conversation across these dimensions:
1. SHARIAH ACCURACY: Were all responses Shariah-compliant? Any errors or near-misses?
2. ARABIC QUALITY: Was the Arabic natural, appropriate register, correct Gulf dialect?
3. HELPFULNESS: Did Meezan actually solve the user's problem?
4. CLARITY: Were responses clear and well-structured?
5. ISLAMIC ADAB: Was the tone warm, respectful, Islamic in character?
6. MISSED OPPORTUNITIES: What could Meezan have proactively offered that it didn't?
Respond ONLY with this exact JSON format:
{
"strengths": ["list of 2-3 things done well"],
"weaknesses": ["list of 1-3 specific weaknesses"],
"missedOpportunities": ["things Meezan could have offered but didn't"],
"shariahErrors": ["any Shariah compliance issues found, empty array if none"],
"languageQuality": "excellent|good|poor",
"overallScore": 7,
"lessonsLearned": [
"Specific actionable lesson 1",
"Specific actionable lesson 2"
]
}`;
try {
const response = await client.messages.create({
model: 'claude-sonnet-4-6',
max_tokens: 800,
messages: [{ role: 'user', content: reflectionPrompt }]
});
const rawText = response.content[0].type === 'text' ? response.content[0].text : '';
// Parse JSON response
const jsonMatch = rawText.match(/\{[\s\S]*\}/);
if (!jsonMatch) return null;
const parsed = JSON.parse(jsonMatch[0]);
const note: ReflectionNote = {
id: `ref_${Date.now()}`,
sessionId,
userId: conversation.userId,
timestamp: new Date().toISOString(),
strengths: parsed.strengths || [],
weaknesses: parsed.weaknesses || [],
missedOpportunities: parsed.missedOpportunities || [],
shariahErrors: parsed.shariahErrors || [],
languageQuality: parsed.languageQuality || 'good',
overallScore: Math.min(10, Math.max(1, parsed.overallScore || 7)),
lessonsLearned: parsed.lessonsLearned || []
};
this.reflections.push(note);
// Extract and store lessons
for (const lesson of note.lessonsLearned) {
this.storelesson(lesson, 'reflection', note.id);
}
// Flag Shariah errors urgently
if (note.shariahErrors.length > 0) {
console.warn(`⚠️ SHARIAH REVIEW NEEDED: ${note.shariahErrors.join('; ')}`);
this.storeShariahErrorLesson(note.shariahErrors);
}
this.save();
console.log(`✅ Reflection complete for session ${sessionId}. Score: ${note.overallScore}/10`);
return note;
} catch (error) {
console.error('Self-reflection API error:', error);
return null;
}
}
/**
* Generate a comprehensive improvement summary
* Used to update the system prompt with learned lessons
*/
async generateImprovementContext(): Promise<string> {
if (this.lessons.length === 0) return '';
// Get top lessons by confidence and reinforcement
const topLessons = this.lessons
.filter(l => l.confidence >= 0.6)
.sort((a, b) => (b.confidence * b.reinforcementCount) - (a.confidence * a.reinforcementCount))
.slice(0, 10);
if (topLessons.length === 0) return '';
const lessonsList = topLessons
.map(l => `• ${l.lesson}`)
.join('\n');
return `\nLEARNED IMPROVEMENTS (from ${this.reflections.length} self-reflections):\n${lessonsList}\n`;
}
/**
* Get recent Shariah errors to always keep in system prompt
*/
getShariahErrorAlerts(): string[] {
return this.lessons
.filter(l => l.category === 'shariah_error' && l.confidence >= 0.8)
.map(l => l.lesson)
.slice(-5);
}
/**
* Get improvement stats for dashboard
*/
getStats(): {
totalReflections: number;
averageScore: number;
totalLessons: number;
shariahErrors: number;
trend: 'improving' | 'stable' | 'declining';
} {
const recent = this.reflections.slice(-10);
const older = this.reflections.slice(-20, -10);
const avgRecent = recent.length > 0
? recent.reduce((s, r) => s + r.overallScore, 0) / recent.length
: 0;
const avgOlder = older.length > 0
? older.reduce((s, r) => s + r.overallScore, 0) / older.length
: avgRecent;
const trend = avgRecent > avgOlder + 0.5 ? 'improving'
: avgRecent < avgOlder - 0.5 ? 'declining'
: 'stable';
return {
totalReflections: this.reflections.length,
averageScore: Math.round(avgRecent * 10) / 10,
totalLessons: this.lessons.length,
shariahErrors: this.lessons.filter(l => l.category === 'shariah_error').length,
trend
};
}
getRecentReflections(limit: number = 5): ReflectionNote[] {
return this.reflections.slice(-limit).reverse();
}
getLessons(): LearnedLesson[] {
return this.lessons.sort((a, b) => b.confidence - a.confidence);
}
private storelesson(lessonText: string, source: LearnedLesson['source'], sourceId: string): void {
// Check if similar lesson already exists
const existing = this.lessons.find(l =>
this.similarity(l.lesson, lessonText) > 0.7
);
if (existing) {
existing.reinforcementCount++;
existing.confidence = Math.min(1, existing.confidence + 0.1);
existing.lastReinforced = new Date().toISOString();
} else {
this.lessons.push({
id: `lesson_${Date.now()}_${Math.random().toString(36).slice(2)}`,
lesson: lessonText,
lessonAr: lessonText, // TODO: translate
category: 'general',
confidence: 0.5,
reinforcementCount: 1,
firstLearned: new Date().toISOString(),
lastReinforced: new Date().toISOString(),
source
});
}
}
private storeShariahErrorLesson(errors: string[]): void {
for (const error of errors) {
const lesson: LearnedLesson = {
id: `shariah_err_${Date.now()}`,
lesson: `SHARIAH ALERT: ${error}`,
lessonAr: `تنبيه شرعي: ${error}`,
category: 'shariah_error',
confidence: 0.9, // High confidence for Shariah errors
reinforcementCount: 1,
firstLearned: new Date().toISOString(),
lastReinforced: new Date().toISOString(),
source: 'reflection'
};
this.lessons.push(lesson);
}
}
private similarity(a: string, b: string): number {
const aWords = new Set(a.toLowerCase().split(/\s+/));
const bWords = new Set(b.toLowerCase().split(/\s+/));
const intersection = new Set([...aWords].filter(w => bWords.has(w)));
const union = new Set([...aWords, ...bWords]);
return intersection.size / union.size;
}
private load(): void {
const dir = path.dirname(this.dbPath);
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
if (fs.existsSync(this.dbPath)) {
try {
const data = JSON.parse(fs.readFileSync(this.dbPath, 'utf-8'));
this.reflections = data.reflections || [];
this.lessons = data.lessons || [];
} catch { /* start fresh */ }
}
}
private save(): void {
fs.writeFileSync(
this.dbPath,
JSON.stringify({ reflections: this.reflections, lessons: this.lessons }, null, 2),
'utf-8'
);
}
}
export const selfReflection = new SelfReflectionEngine(
process.env.DB_PATH?.replace('memory.json', 'reflections.json') || './data/reflections.json'
);
|