Repository navigation
Expand file tree
/
Copy pathagentmem.py
More file actions
957 lines (810 loc) · 40.1 KB
/
Copy pathagentmem.py
File metadata and controls
957 lines (810 loc) · 40.1 KB
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
"""
AgentMem v1.0
=============
Two problems solved. One file. Zero extra cost.
1. Agent reads its own past mistakes before every run → stops repeating errors
2. Event bridge fires next step the instant agent finishes → no timers needed
5-chance adaptive system:
Chance 1-2 → simple log (fast, 2 fields)
Chance 3-4 → deep diagnosis (6 fields)
Chance 5 → deep log → shutdown → Gmail / WhatsApp alert
Any success → success log written, counter resets to 0
First-time success → no log needed, agent already knows this
Setup:
pip install flask requests anthropic
Fill .env file (copy from .env.example)
python agentmem.py
n8n wiring (3 nodes, no timer):
Node 1 — Trigger
Node 2 — HTTP POST http://localhost:8765/run
body: { "task": "...", "callback_url": "http://n8n/webhook/done" }
Node 3 — Webhook node (replaces timer — fires instantly when agent done)
use: $json.output $json.success $json.confidence
"""
# ── stdlib only for core mechanics — zero heavy dependencies ──────
import json
import logging
import os
import re
import signal
import smtplib
import sys
import threading
import time
from collections import Counter
from datetime import datetime
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from pathlib import Path
import requests
from flask import Flask, jsonify, request
# ── optional: anthropic (default) or openai ───────────────────────
try:
import anthropic
_PROVIDER = "anthropic"
except ImportError:
try:
from openai import OpenAI
_PROVIDER = "openai"
except ImportError:
print("ERROR: Install anthropic or openai.\n pip install anthropic")
sys.exit(1)
# ═══════════════════════════════════════════════════════════════════
# CONFIG — reads from .env file automatically
# ═══════════════════════════════════════════════════════════════════
def _env(key: str, default: str = "") -> str:
"""Read from environment. Also reads .env file if present."""
val = os.environ.get(key, "")
if not val and Path(".env").exists():
for line in Path(".env").read_text().splitlines():
line = line.strip()
if line.startswith("#") or "=" not in line:
continue
k, _, v = line.partition("=")
if k.strip() == key:
val = v.strip().strip('"').strip("'")
break
return val or default
# core
PORT = int(_env("PORT", "8765"))
ERROR_LOG = _env("ERROR_LOG", "errors.jsonl")
MAX_MEMORY = int(_env("MAX_MEMORY", "5"))
MAX_TOKENS = int(_env("MAX_TOKENS", "800"))
CALLBACK_TIMEOUT = int(_env("CALLBACK_TIMEOUT", "30"))
PATTERN_TRIGGER = int(_env("PATTERN_TRIGGER", "3")) # repeats before CRITICAL WARNING
# AI model
AI_MODEL_ANTHROPIC = _env("AI_MODEL", "claude-haiku-4-5-20251001")
AI_MODEL_OPENAI = _env("AI_MODEL", "gpt-4o-mini")
# alerts
GMAIL_ADDRESS = _env("GMAIL_ADDRESS")
GMAIL_PASSWORD = _env("GMAIL_APP_PASSWORD")
ALERT_EMAIL = _env("ALERT_EMAIL")
ALERT_METHOD = _env("ALERT_METHOD", "gmail").lower() # gmail | whatsapp | both | none
# whatsapp (twilio)
TWILIO_SID = _env("TWILIO_ACCOUNT_SID")
TWILIO_TOKEN = _env("TWILIO_AUTH_TOKEN")
TWILIO_FROM = _env("TWILIO_WHATSAPP_FROM", "whatsapp:+14155238886")
ALERT_WA_TO = _env("ALERT_WHATSAPP_TO")
# ═══════════════════════════════════════════════════════════════════
# LOGGING — clean, readable, no noise
# ═══════════════════════════════════════════════════════════════════
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)-7s %(message)s",
datefmt="%H:%M:%S",
)
log = logging.getLogger("agentmem")
logging.getLogger("werkzeug").setLevel(logging.ERROR) # silence Flask request logs
# ═══════════════════════════════════════════════════════════════════
# AI CLIENT — anthropic or openai, auto-detected
# ═══════════════════════════════════════════════════════════════════
def _ai_call(prompt: str) -> str:
"""Single unified AI call. Works with Anthropic or OpenAI."""
if _PROVIDER == "anthropic":
client = anthropic.Anthropic(api_key=_env("ANTHROPIC_API_KEY"))
resp = client.messages.create(
model=AI_MODEL_ANTHROPIC,
max_tokens=MAX_TOKENS,
messages=[{"role": "user", "content": prompt}],
)
return resp.content[0].text.strip()
else:
client = OpenAI(api_key=_env("OPENAI_API_KEY"))
resp = client.chat.completions.create(
model=AI_MODEL_OPENAI,
max_tokens=MAX_TOKENS,
messages=[{"role": "user", "content": prompt}],
)
return resp.choices[0].message.content.strip()
# ═══════════════════════════════════════════════════════════════════
# COUNTER — tracks attempts per task (exact text match)
# ═══════════════════════════════════════════════════════════════════
_counters: dict = {} # { task_text: attempt_count }
_counters_lock = threading.Lock()
def _get_attempts(task: str) -> int:
with _counters_lock:
return _counters.get(task, 0)
def _increment(task: str) -> int:
"""Increment attempt counter. Returns NEW count."""
with _counters_lock:
_counters[task] = _counters.get(task, 0) + 1
return _counters[task]
def _reset(task: str) -> None:
"""Reset counter to 0 on success."""
with _counters_lock:
_counters.pop(task, None)
# ═══════════════════════════════════════════════════════════════════
# FILE LOCK — thread-safe writes to errors.jsonl
# ═══════════════════════════════════════════════════════════════════
_file_lock = threading.Lock()
def _read_log() -> list:
"""Read all entries from errors.jsonl. Returns [] if missing or corrupt."""
path = Path(ERROR_LOG)
if not path.exists():
return []
entries = []
try:
with _file_lock:
lines = path.read_text(encoding="utf-8").splitlines()
for line in lines:
line = line.strip()
if not line:
continue
try:
entries.append(json.loads(line))
except json.JSONDecodeError:
pass # skip corrupted lines silently
except Exception as e:
log.warning(f"Log read error (continuing): {e}")
return entries
def _write_log(entry: dict) -> None:
"""Append one entry to errors.jsonl. Thread-safe. Never crashes workflow."""
try:
with _file_lock:
with open(ERROR_LOG, "a", encoding="utf-8") as f:
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
except Exception as e:
log.error(f"Log write failed: {e}")
# ═══════════════════════════════════════════════════════════════════
# PATTERN DETECTION — finds errors that repeat 3+ times
# ═══════════════════════════════════════════════════════════════════
_STOPWORDS = {
"the","a","an","is","was","in","on","at","to","for",
"of","and","or","not","it","be","as","by","with","this"
}
def _find_patterns(entries: list) -> dict:
"""
Returns { keyword: count } for keywords appearing in 3+ error entries.
Used to escalate repeated mistakes to CRITICAL WARNING in agent prompt.
"""
counts = Counter()
for e in entries:
text = e.get("what_broke", e.get("error", "")).lower()
words = re.findall(r'\b[a-z]{4,}\b', text)
counts.update(w for w in words if w not in _STOPWORDS)
return {k: v for k, v in counts.items() if v >= PATTERN_TRIGGER}
# ═══════════════════════════════════════════════════════════════════
# MEMORY READ — inject past mistakes as active checklist
# ═══════════════════════════════════════════════════════════════════
def _build_memory_context(task: str) -> str:
"""
Loads recent errors + success logs and formats them as:
- CRITICAL WARNINGS for patterns (3+ repeats)
- Active checklist items the agent must verify this run
Returns "" on first run — clean slate.
"""
entries = _read_log()
if not entries:
return ""
patterns = _find_patterns(entries)
recent = entries[-MAX_MEMORY:]
ctx = "\n\n════════ MEMORY: LEARN FROM YOUR PAST ════════\n"
# critical warnings first — systematic problems
if patterns:
ctx += "\n⚠️ CRITICAL — these errors have repeated multiple times:\n"
for kw, count in sorted(patterns.items(), key=lambda x: -x[1]):
ctx += f" • '{kw}' appeared in {count} past failures — treat as known issue\n"
# checklist: errors to avoid
errors = [e for e in recent if e.get("type") == "error"]
success = [e for e in recent if e.get("type") == "success"]
if errors:
ctx += "\nPAST FAILURES — actively verify you are NOT repeating these:\n"
for i, e in enumerate(errors, 1):
ctx += (
f"\n [CHECK {i}]\n"
f" Task : {e.get('task','')[:80]}\n"
f" What broke : {e.get('what_broke', e.get('error',''))}\n"
)
if e.get("root_cause"):
ctx += f" Root cause : {e['root_cause']}\n"
if e.get("next_time"):
ctx += f" Fix to use : {e['next_time']}\n"
ctx += " → Confirm: are you applying this fix? (YES / N/A)\n"
# success logs — proven solutions
if success:
ctx += "\nPROVEN SOLUTIONS — these worked after previous failures:\n"
for s in success[-2:]: # last 2 success logs only
ctx += (
f"\n ✓ Task : {s.get('task','')[:80]}\n"
f" What worked : {s.get('what_changed','')}\n"
f" Why it worked: {s.get('why_it_worked','')}\n"
f" → Use this approach directly if relevant.\n"
)
ctx += "\n════════════════════════════════════════════════\n"
return ctx
# ═══════════════════════════════════════════════════════════════════
# MEMORY WRITE — error log (simple or deep)
# ═══════════════════════════════════════════════════════════════════
def _save_error(task: str, attempt: int, parsed: dict) -> None:
"""
Chance 1-2 → simple 2-field entry.
Chance 3-5 → full 6-field deep entry.
"""
entry = {
"type" : "error",
"timestamp" : datetime.now().isoformat(),
"task" : task,
"attempt" : attempt,
"what_broke": parsed.get("what_broke", parsed.get("error", "")),
"next_time" : parsed.get("next_time", parsed.get("lesson", "")),
}
if attempt >= 3:
# add deep fields only for chance 3+
entry.update({
"what_tried" : parsed.get("what_tried", ""),
"root_cause" : parsed.get("root_cause", ""),
"failed_at_step": parsed.get("failed_at_step", ""),
"confidence" : parsed.get("confidence", ""),
})
_write_log(entry)
log.info(f"Error logged (attempt {attempt}) — {entry['what_broke'][:70]}")
def _save_success(task: str, attempt: int, parsed: dict) -> None:
"""
Save success log ONLY when there were previous failures (attempt >= 2).
First-time success = no log needed.
"""
if attempt < 2:
return # first-time success — agent already knew this, nothing to learn
entry = {
"type" : "success",
"timestamp" : datetime.now().isoformat(),
"task" : task,
"succeeded_on": attempt,
"what_changed": parsed.get("what_changed", ""),
"why_it_worked": parsed.get("why_it_worked", ""),
"lesson" : parsed.get("lesson", ""),
}
_write_log(entry)
log.info(f"Success logged after {attempt} attempts — {entry['lesson'][:70]}")
# ═══════════════════════════════════════════════════════════════════
# RESPONSE PARSER — extract structured fields from agent response
# ═══════════════════════════════════════════════════════════════════
def _parse(response: str) -> dict:
"""
Parses agent's structured response into a clean dict.
Handles imperfect formatting — extracts what it can, fills blanks.
"""
# label aliases → field name
aliases = {
"OUTPUT" : "output",
"WHAT_I_TRIED" : "what_tried",
"WHAT_TRIED" : "what_tried",
"WHAT_BROKE" : "what_broke",
"WHAT BROKE" : "what_broke",
"ROOT_CAUSE" : "root_cause",
"ROOT CAUSE" : "root_cause",
"FAILED_AT_STEP" : "failed_at_step",
"FAILED AT STEP" : "failed_at_step",
"NEXT_TIME" : "next_time",
"NEXT TIME" : "next_time",
"CONFIDENCE" : "confidence",
"STEPS_VERIFIED" : "steps_verified",
"CHECKS_APPLIED" : "checks_applied",
"WHAT_CHANGED" : "what_changed",
"WHAT CHANGED" : "what_changed",
"WHY_IT_WORKED" : "why_it_worked",
"WHY IT WORKED" : "why_it_worked",
"LESSON" : "lesson",
}
result = {}
for line in response.splitlines():
if ":" not in line:
continue
label, _, value = line.partition(":")
key = label.strip().upper().lstrip("•→-[ ]")
field = aliases.get(key)
if field and value.strip():
result[field] = value.strip()
return result
# ═══════════════════════════════════════════════════════════════════
# PROMPT BUILDER — changes based on attempt number
# ═══════════════════════════════════════════════════════════════════
def _build_prompt(task: str, attempt: int, memory: str) -> str:
"""
Attempt 1-2 → simple prompt (fast, small response)
Attempt 3-5 → deep prompt (full diagnosis required)
Both include memory context and success logging fields.
"""
base = f"""You are a precise AI agent. Complete the task below.
TASK:
{task}
{memory}"""
if attempt <= 2:
# ── SIMPLE prompt for chances 1 & 2 ──────────────────────
return base + """
━━━ HOW TO RESPOND ━━━
IF YOU SUCCEED:
OUTPUT: <your complete result>
STEPS_VERIFIED: <briefly confirm key steps passed>
CONFIDENCE: <HIGH / MEDIUM / LOW>
IF THIS IS A SUCCESS AFTER PREVIOUS FAILURES:
OUTPUT: <your complete result>
WHAT_CHANGED: <what you did differently this time>
WHY_IT_WORKED: <why this approach succeeded>
LESSON: <one precise instruction for next time>
CONFIDENCE: <HIGH / MEDIUM / LOW>
IF YOU FAIL:
FAILED
WHAT_BROKE: <exact value or condition that caused failure — be specific, include actual values>
NEXT_TIME: <precise fix — specific enough to follow without guessing>
Rules:
- Start with OUTPUT:, FAILED, nothing else before these
- No vague words like "something" or "issue" — name the exact thing
"""
else:
# ── DEEP prompt for chances 3, 4, 5 ─────────────────────
return base + """
━━━ HOW TO RESPOND ━━━
IF YOU SUCCEED:
OUTPUT: <your complete result>
STEPS_VERIFIED: <list each step and confirm PASS/FAIL>
CHECKS_APPLIED: <for each CHECK in memory, write YES or N/A>
WHAT_CHANGED: <what you did differently vs past failures>
WHY_IT_WORKED: <the root reason this approach worked>
LESSON: <one precise instruction for future runs>
CONFIDENCE: <HIGH / MEDIUM / LOW>
CONFIDENCE_REASON: <why you rated it this way>
IF YOU FAIL:
FAILED
WHAT_I_TRIED: <exact steps you attempted, in order>
WHAT_BROKE: <exact value, field, format, or condition — include actual values, not descriptions>
ROOT_CAUSE: <the underlying reason — not the symptom, the cause beneath it>
FAILED_AT_STEP: <step number that failed, what previous steps returned>
NEXT_TIME: <precise instruction — specific enough a future agent can follow without guessing>
CONFIDENCE: <HIGH / MEDIUM / LOW — how certain you are about this diagnosis>
Rules:
- Start with OUTPUT: or FAILED — nothing before these words
- Never use vague words: "something", "issue", "problem", "error" without specifics
- WHAT_BROKE must contain the actual value that failed, not just what type of value
- ROOT_CAUSE must be the cause, not a repeat of the symptom
"""
# ═══════════════════════════════════════════════════════════════════
# AGENT RUNNER — the core loop
# ═══════════════════════════════════════════════════════════════════
MAX_CHANCES = 5
def run_agent(task: str) -> dict:
"""
Runs the agent with memory context.
Handles the full 5-chance adaptive system.
Returns a clean dict for n8n / Make / Zapier.
"""
attempt = _increment(task)
log.info(f"Attempt {attempt}/{MAX_CHANCES} — {task[:70]}")
memory = _build_memory_context(task)
prompt = _build_prompt(task, attempt, memory)
# ── API call — catch all crashes ─────────────────────────────
try:
response = _ai_call(prompt)
except Exception as e:
err = str(e)
log.error(f"API call crashed: {err}")
_save_error(task, attempt, {
"what_broke": err,
"next_time" : "Check API key and network connection",
"root_cause": "API call failed before agent could respond",
"failed_at_step": "Step 0 — API call",
"confidence": "HIGH",
})
result = {
"success" : False,
"error" : err,
"attempts" : attempt,
"chances_remaining": max(0, MAX_CHANCES - attempt),
}
if attempt >= MAX_CHANCES:
_handle_shutdown(task, result)
return result
parsed = _parse(response)
# ── SUCCESS ───────────────────────────────────────────────────
if response.upper().startswith("OUTPUT:"):
output = parsed.get("output", response[7:].strip())
confidence = parsed.get("confidence", "HIGH").upper()
if confidence not in ("HIGH", "MEDIUM", "LOW"):
confidence = "HIGH"
_save_success(task, attempt, parsed)
_reset(task)
result = {
"success" : True,
"output" : output,
"confidence" : confidence,
"attempts" : attempt,
"chances_remaining": MAX_CHANCES, # reset
}
# flag low confidence for human review in n8n
if confidence == "LOW":
result["flag_for_review"] = True
result["review_reason"] = parsed.get(
"confidence_reason", "Agent rated output as LOW confidence"
)
log.warning("LOW confidence output — flagged for human review")
log.info(f"SUCCESS on attempt {attempt} — confidence: {confidence}")
return result
# ── FAILURE ───────────────────────────────────────────────────
elif response.upper().startswith("FAILED"):
# fill blanks if agent didn't follow format perfectly
if not parsed.get("what_broke"):
parsed["what_broke"] = "Agent reported failure — check raw response"
if not parsed.get("next_time"):
parsed["next_time"] = "Review task and retry with more specific instructions"
_save_error(task, attempt, parsed)
result = {
"success" : False,
"error" : parsed.get("what_broke", ""),
"lesson" : parsed.get("next_time", ""),
"attempts" : attempt,
"chances_remaining": max(0, MAX_CHANCES - attempt),
}
if attempt >= MAX_CHANCES:
_handle_shutdown(task, result)
else:
log.warning(f"Failure {attempt}/{MAX_CHANCES} — {result['error'][:70]}")
return result
# ── UNFORMATTED RESPONSE — return as output, flag it ─────────
else:
log.warning("Agent did not follow response format — returning raw output")
_reset(task)
return {
"success" : True,
"output" : response,
"confidence" : "LOW",
"flag_for_review" : True,
"review_reason" : "Agent response format was unexpected",
"attempts" : attempt,
"chances_remaining": MAX_CHANCES,
}
# ═══════════════════════════════════════════════════════════════════
# SHUTDOWN HANDLER — chance 5 failure
# ═══════════════════════════════════════════════════════════════════
def _handle_shutdown(task: str, result: dict) -> None:
"""
Called when chance 5 fails.
1. Marks result as shutdown
2. Sends human alert (Gmail / WhatsApp / both)
3. Resets counter so next manual run starts fresh
"""
log.error(f"MAX ATTEMPTS REACHED — shutting down task: {task[:70]}")
result["shutdown"] = True
result["reason"] = "Max attempts reached — human review required"
result["human_alert_sent"] = False
history = _read_log()
task_history = [
e for e in history if e.get("task") == task
][-MAX_CHANCES:]
# build alert
subject, body_text, body_html = _build_alert(task, task_history)
sent = False
if ALERT_METHOD in ("gmail", "both"):
sent = _send_gmail(subject, body_text, body_html)
if ALERT_METHOD in ("whatsapp", "both"):
sent = _send_whatsapp(task, task_history) or sent
result["human_alert_sent"] = sent
_reset(task) # reset so next human-triggered run starts from chance 1
# ═══════════════════════════════════════════════════════════════════
# ALERT BUILDER — builds rich email content from attempt history
# ═══════════════════════════════════════════════════════════════════
def _build_alert(task: str, history: list) -> tuple:
"""Returns (subject, plain_text, html) for the alert."""
subject = f"🚨 AgentMem — Task Failed After {MAX_CHANCES} Attempts"
# ── plain text ────────────────────────────────────────────────
lines = [
f"TASK: {task}",
f"Total attempts: {MAX_CHANCES}",
f"Time: {datetime.now().strftime('%Y-%m-%d %H:%M')}",
"",
"━" * 40,
"ATTEMPT HISTORY",
"━" * 40,
]
for e in history:
a = e.get("attempt", "?")
depth = "simple" if int(a) <= 2 else "deep"
lines.append(f"\nAttempt {a} — FAILED ({depth})")
lines.append(f" Broke : {e.get('what_broke', e.get('error','?'))}")
if e.get("root_cause"):
lines.append(f" Cause : {e['root_cause']}")
if e.get("failed_at_step"):
lines.append(f" At step : {e['failed_at_step']}")
lines.append(f" Next try : {e.get('next_time', e.get('lesson','?'))}")
lines += [
"",
"━" * 40,
"ALL APPROACHES EXHAUSTED",
"Human review required.",
"Start from the LAST root cause — that is the real blocker.",
"Full history saved to errors.jsonl",
"━" * 40,
]
plain = "\n".join(lines)
# ── html version — clean, readable in Gmail ───────────────────
rows = ""
for e in history:
a = e.get("attempt", "?")
rows += f"""
<tr>
<td style="padding:8px;border-bottom:1px solid #eee;color:#c0392b;font-weight:bold;">
Attempt {a}
</td>
<td style="padding:8px;border-bottom:1px solid #eee;">
<b>Broke:</b> {e.get('what_broke', e.get('error','?'))}<br>
{"<b>Cause:</b> " + e['root_cause'] + "<br>" if e.get('root_cause') else ""}
{"<b>At step:</b> " + e['failed_at_step'] + "<br>" if e.get('failed_at_step') else ""}
<b>Fix to try:</b> {e.get('next_time', e.get('lesson','?'))}
</td>
</tr>"""
html = f"""
<html><body style="font-family:Arial,sans-serif;max-width:600px;margin:auto;padding:20px;">
<h2 style="color:#c0392b;">🚨 Task Failed After {MAX_CHANCES} Attempts</h2>
<p><b>Task:</b> {task}</p>
<p><b>Time:</b> {datetime.now().strftime('%Y-%m-%d %H:%M')}</p>
<table width="100%" style="border-collapse:collapse;margin-top:16px;">
<thead>
<tr style="background:#f5f5f5;">
<th style="padding:8px;text-align:left;width:80px;">Attempt</th>
<th style="padding:8px;text-align:left;">Details</th>
</tr>
</thead>
<tbody>{rows}</tbody>
</table>
<div style="margin-top:20px;padding:12px;background:#fff3cd;border-radius:6px;">
<b>Action needed:</b> Review the last root cause — that is the real blocker.<br>
Full history saved to <code>errors.jsonl</code>.
</div>
</body></html>"""
return subject, plain, html
# ═══════════════════════════════════════════════════════════════════
# GMAIL ALERT
# ═══════════════════════════════════════════════════════════════════
def _send_gmail(subject: str, plain: str, html: str) -> bool:
"""
Sends alert via Gmail SMTP. Free. No external API.
Requires GMAIL_ADDRESS + GMAIL_APP_PASSWORD in .env
"""
if not all([GMAIL_ADDRESS, GMAIL_PASSWORD, ALERT_EMAIL]):
log.warning("Gmail not configured — skipping alert (set GMAIL_ADDRESS, GMAIL_APP_PASSWORD, ALERT_EMAIL in .env)")
return False
try:
msg = MIMEMultipart("alternative")
msg["Subject"] = subject
msg["From"] = GMAIL_ADDRESS
msg["To"] = ALERT_EMAIL
msg.attach(MIMEText(plain, "plain"))
msg.attach(MIMEText(html, "html"))
with smtplib.SMTP_SSL("smtp.gmail.com", 465, timeout=15) as server:
server.login(GMAIL_ADDRESS, GMAIL_PASSWORD)
server.sendmail(GMAIL_ADDRESS, ALERT_EMAIL, msg.as_string())
log.info(f"Gmail alert sent → {ALERT_EMAIL}")
return True
except smtplib.SMTPAuthenticationError:
log.error("Gmail auth failed — check GMAIL_APP_PASSWORD (not your regular password)")
return False
except Exception as e:
log.error(f"Gmail send failed: {e}")
return False
# ═══════════════════════════════════════════════════════════════════
# WHATSAPP ALERT (Twilio)
# ═══════════════════════════════════════════════════════════════════
def _send_whatsapp(task: str, history: list) -> bool:
"""
Sends short WhatsApp alert via Twilio.
Free tier: 1000 messages/month.
Requires TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, ALERT_WHATSAPP_TO in .env
"""
if not all([TWILIO_SID, TWILIO_TOKEN, ALERT_WA_TO]):
log.warning("WhatsApp not configured — skipping (set TWILIO_* vars in .env)")
return False
last = history[-1] if history else {}
msg = (
f"🚨 *AgentMem Alert*\n"
f"Task: {task[:60]}\n"
f"Failed after {MAX_CHANCES} attempts.\n\n"
f"Last error: {last.get('what_broke', last.get('error','?'))[:100]}\n"
f"Last root cause: {last.get('root_cause', 'see errors.jsonl')[:100]}\n\n"
f"Human review needed."
)
try:
resp = requests.post(
f"https://api.twilio.com/2010-04-01/Accounts/{TWILIO_SID}/Messages.json",
auth=(TWILIO_SID, TWILIO_TOKEN),
data={"From": TWILIO_FROM, "To": ALERT_WA_TO, "Body": msg},
timeout=15,
)
if resp.status_code == 201:
log.info(f"WhatsApp alert sent → {ALERT_WA_TO}")
return True
log.error(f"WhatsApp failed: HTTP {resp.status_code} — {resp.text[:100]}")
return False
except Exception as e:
log.error(f"WhatsApp send failed: {e}")
return False
# ═══════════════════════════════════════════════════════════════════
# EVENT BRIDGE — replaces timers in n8n / Make / Zapier
# ═══════════════════════════════════════════════════════════════════
def _fire_callback(url: str, payload: dict) -> None:
"""
Fires result to n8n the instant agent finishes.
Retries once on failure. Never crashes the process.
"""
for attempt in (1, 2):
try:
r = requests.post(
url, json=payload,
headers={"Content-Type": "application/json"},
timeout=CALLBACK_TIMEOUT,
)
if r.status_code < 300:
log.info(f"Callback delivered (attempt {attempt}) → {url}")
return
log.warning(f"Callback attempt {attempt} — HTTP {r.status_code}")
except requests.exceptions.Timeout:
log.warning(f"Callback attempt {attempt} — timeout after {CALLBACK_TIMEOUT}s")
except Exception as e:
log.warning(f"Callback attempt {attempt} — {e}")
if attempt == 1:
time.sleep(2)
log.error(f"Callback failed after 2 attempts → {url}")
# ═══════════════════════════════════════════════════════════════════
# FLASK APP — HTTP endpoints
# ═══════════════════════════════════════════════════════════════════
app = Flask(__name__)
@app.route("/run", methods=["POST"])
def handle_run():
"""
Main endpoint.
n8n sends task here → gets 202 instantly → result fires to callback_url when done.
This is what eliminates the need for timers.
"""
body = request.get_json(silent=True)
if not body:
return jsonify({"error": "Body must be JSON"}), 400
task = (body.get("task") or "").strip()
callback_url = (body.get("callback_url") or "").strip()
if not task:
return jsonify({"error": "Missing 'task' field"}), 400
if not callback_url:
return jsonify({"error": "Missing 'callback_url' — set to your n8n webhook URL"}), 400
def process():
start = time.time()
result = run_agent(task)
result["task"] = task
result["duration_sec"] = round(time.time() - start, 2)
result["timestamp"] = datetime.now().isoformat()
_fire_callback(callback_url, result)
threading.Thread(target=process, daemon=True).start()
return jsonify({"status": "running", "task": task[:80]}), 202
@app.route("/health", methods=["GET"])
def health():
"""http://localhost:8765/health"""
entries = _read_log()
errors = sum(1 for e in entries if e.get("type") == "error")
wins = sum(1 for e in entries if e.get("type") == "success")
return jsonify({
"status" : "ok",
"port" : PORT,
"model" : AI_MODEL_ANTHROPIC if _PROVIDER == "anthropic" else AI_MODEL_OPENAI,
"provider" : _PROVIDER,
"errors_logged" : errors,
"successes_logged": wins,
"active_counters": dict(_counters),
})
@app.route("/memory", methods=["GET"])
def view_memory():
"""http://localhost:8765/memory — all stored entries"""
entries = _read_log()
patterns = _find_patterns(entries)
return jsonify({
"entries" : entries,
"count" : len(entries),
"patterns": patterns,
})
@app.route("/memory/patterns", methods=["GET"])
def view_patterns():
"""http://localhost:8765/memory/patterns — repeated errors"""
entries = _read_log()
patterns = _find_patterns(entries)
return jsonify({
"patterns" : dict(sorted(patterns.items(), key=lambda x: -x[1])),
"threshold": PATTERN_TRIGGER,
})
@app.route("/memory/clear", methods=["POST"])
def clear_memory():
"""POST http://localhost:8765/memory/clear"""
try:
with _file_lock:
Path(ERROR_LOG).write_text("", encoding="utf-8")
with _counters_lock:
_counters.clear()
log.info("Memory and counters cleared")
return jsonify({"status": "cleared"})
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/test/alert", methods=["POST"])
def test_alert():
"""POST http://localhost:8765/test/alert — send a test alert to verify Gmail/WhatsApp works"""
subject = "✅ AgentMem — Test Alert"
plain = "This is a test alert from AgentMem. Alerts are working correctly."
html = "<html><body><h2>✅ AgentMem Test Alert</h2><p>Alerts are working correctly.</p></body></html>"
results = {}
if ALERT_METHOD in ("gmail", "both"):
results["gmail"] = _send_gmail(subject, plain, html)
if ALERT_METHOD in ("whatsapp", "both"):
results["whatsapp"] = _send_whatsapp("Test alert", [])
return jsonify({"sent": results})
# ═══════════════════════════════════════════════════════════════════
# STARTUP
# ═══════════════════════════════════════════════════════════════════
def _check_config() -> None:
"""Validate required config at startup. Clear errors, not surprises later."""
errors = []
if _PROVIDER == "anthropic" and not _env("ANTHROPIC_API_KEY"):
errors.append("ANTHROPIC_API_KEY not set")
if _PROVIDER == "openai" and not _env("OPENAI_API_KEY"):
errors.append("OPENAI_API_KEY not set")
if ALERT_METHOD in ("gmail", "both"):
missing = [k for k in ("GMAIL_ADDRESS","GMAIL_APP_PASSWORD","ALERT_EMAIL")
if not _env(k)]
if missing:
log.warning(f"Gmail alert not configured — missing: {', '.join(missing)}")
if ALERT_METHOD in ("whatsapp", "both"):
missing = [k for k in ("TWILIO_ACCOUNT_SID","TWILIO_AUTH_TOKEN","ALERT_WHATSAPP_TO")
if not _env(k)]
if missing:
log.warning(f"WhatsApp alert not configured — missing: {', '.join(missing)}")
if errors:
for e in errors:
print(f"\n ERROR: {e}")
print("\n Create a .env file with your API key.")
print(" See .env.example for the template.\n")
sys.exit(1)
def _shutdown(sig, frame):
log.info("Shutting down cleanly...")
sys.exit(0)
if __name__ == "__main__":
signal.signal(signal.SIGINT, _shutdown)
signal.signal(signal.SIGTERM, _shutdown)
_check_config()
alert_status = "not configured"
if ALERT_METHOD == "gmail" and GMAIL_ADDRESS: alert_status = f"Gmail → {ALERT_EMAIL}"
if ALERT_METHOD == "whatsapp" and TWILIO_SID: alert_status = f"WhatsApp → {ALERT_WA_TO}"
if ALERT_METHOD == "both": alert_status = f"Gmail + WhatsApp"
print(f"""
╔══════════════════════════════════════════════════════╗
║ AgentMem v1.0 is running ║
╠══════════════════════════════════════════════════════╣
║ POST task → http://localhost:{PORT}/run ║
║ Health → http://localhost:{PORT}/health ║
║ Memory → http://localhost:{PORT}/memory ║
║ Patterns → http://localhost:{PORT}/memory/patterns
║ Clear → POST /memory/clear ║
║ Test alert → POST /test/alert ║
╠══════════════════════════════════════════════════════╣
║ Provider : {_PROVIDER:<41}║
║ Alerts : {alert_status:<41}║
║ Max tries : {MAX_CHANCES:<41}║
╚══════════════════════════════════════════════════════╝
""")
app.run(
host="0.0.0.0",
port=PORT,
debug=False,
threaded=True,
)