-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdemo.py
More file actions
407 lines (318 loc) · 13.6 KB
/
Copy pathdemo.py
File metadata and controls
407 lines (318 loc) · 13.6 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
#!/usr/bin/env python
"""Demo script for Portable Learner Memory.
Run this to see the full flow without LangGraph Studio:
uv run python demo.py
Or run specific demos:
uv run python demo.py --conversation # Single conversation
uv run python demo.py --export # Export to CLR/Caliper
uv run python demo.py --roundtrip # Full round-trip test
uv run python demo.py --all # Everything (default)
"""
import argparse
import json
from dotenv import load_dotenv
load_dotenv()
from langchain_core.messages import HumanMessage
from graph.main import build_graph
from memory.schema import MemoryItem
from memory.formats import export_clr, export_caliper, import_clr, import_caliper
def demo_conversation():
"""Demo: Single conversation with memory extraction."""
print("\n" + "=" * 60)
print("DEMO: Conversation with Memory Extraction")
print("=" * 60)
graph = build_graph()
# Simulate a learner introducing themselves
state = {
"messages": [
HumanMessage(
content="Hi! I'm Maria. I work as a nurse with night shifts, "
"so I only have about 30 minutes a day to study. I'm trying to "
"pass my algebra final next month. I've always struggled with "
"word problems but I'm pretty good with basic equations."
)
],
"memories": [],
"learner_id": "urn:uuid:maria-demo",
}
print("\n[Learner]: " + state["messages"][0].content)
print("\n[Processing...]")
result = graph.invoke(state)
print("\n[Tutor]: " + result["messages"][-1].content)
print("\n[Memories Extracted]:")
for mem in result.get("memories", []):
print(f" - [{mem['category']}] {mem['content']}")
print(f" (confidence: {mem['confidence']:.2f}, source: {mem['source']})")
return result
def demo_export(memories: list[dict] | None = None):
"""Demo: Export memories to CLR and Caliper formats."""
print("\n" + "=" * 60)
print("DEMO: Export to CLR and Caliper")
print("=" * 60)
if memories is None:
# Use sample memories if none provided
memories = [
{
"id": "mem-1",
"category": "fact",
"content": "Works as a nurse with night shifts",
"source": "conversation",
"confidence": 0.95,
"created_at": "2026-03-10T12:00:00",
"valid_until": None,
"subject_area": None,
"original_format": None,
"original_id": None,
},
{
"id": "mem-2",
"category": "goal",
"content": "Trying to pass algebra final next month",
"source": "conversation",
"confidence": 0.9,
"created_at": "2026-03-10T12:00:00",
"valid_until": None,
"subject_area": "math",
"original_format": None,
"original_id": None,
},
{
"id": "mem-3",
"category": "mastery",
"content": "Good with basic equations",
"source": "conversation",
"confidence": 0.85,
"created_at": "2026-03-10T12:00:00",
"valid_until": None,
"subject_area": "math",
"original_format": None,
"original_id": None,
},
]
memory_items = [MemoryItem.from_dict(m) for m in memories]
# Export to CLR
print("\n[CLR Export]")
clr = export_clr(memory_items)
print(json.dumps(clr, indent=2)[:1500] + "\n...")
# Export to Caliper
print("\n[Caliper Export]")
caliper = export_caliper(memory_items)
print(json.dumps(caliper, indent=2)[:1500] + "\n...")
return clr, caliper
def demo_roundtrip():
"""Demo: Full round-trip - conversation, export, import, new conversation."""
print("\n" + "=" * 60)
print("DEMO: Full Round-Trip (Portable Memory in Action)")
print("=" * 60)
graph = build_graph()
# Step 1: Initial conversation
print("\n--- Step 1: Initial Conversation ---")
state1 = {
"messages": [
HumanMessage(
content="I'm Alex, a single parent studying for my GED. "
"I learn best with visual examples and have dyslexia, "
"so I need things explained step by step. Math is hard "
"for me but I understand percentages from my retail job."
)
],
"memories": [],
"learner_id": "urn:uuid:alex-demo",
}
print("[Learner]: " + state1["messages"][0].content[:100] + "...")
result1 = graph.invoke(state1)
print(f"[Memories extracted]: {len(result1['memories'])}")
# Step 2: Export to CLR
print("\n--- Step 2: Export to CLR ---")
memory_items = [MemoryItem.from_dict(m) for m in result1["memories"]]
clr_data = export_clr(memory_items)
print(f"[CLR achievements]: {len(clr_data['credentialSubject']['achievement'])}")
# Step 3: Import from CLR (simulating transfer to new system)
print("\n--- Step 3: Import from CLR (New System) ---")
imported_memories = import_clr(clr_data)
print(f"[Memories restored]: {len(imported_memories)}")
# Verify content matches
original_contents = {m.content for m in memory_items}
imported_contents = {m.content for m in imported_memories}
match = original_contents == imported_contents
print(f"[Content match]: {match}")
# Step 4: New conversation using imported memories
print("\n--- Step 4: New Conversation with Imported Memories ---")
state2 = {
"messages": [HumanMessage(content="Can you help me understand how to calculate a discount?")],
"memories": [m.to_dict() for m in imported_memories],
"learner_id": "urn:uuid:alex-demo",
}
print("[Learner]: " + state2["messages"][0].content)
result2 = graph.invoke(state2)
response = result2["messages"][-1].content
print("\n[Tutor]: " + response[:500] + "...")
# Check personalization
print("\n--- Personalization Check ---")
checks = {
"References work/retail context": any(
word in response.lower() for word in ["retail", "job", "work", "store"]
),
"Uses step-by-step approach": any(
word in response.lower() for word in ["step", "first", "then", "next"]
),
"Provides visual/example": any(
word in response.lower() for word in ["example", "imagine", "picture", "visual"]
),
}
for check, passed in checks.items():
status = "✓" if passed else "✗"
print(f" {status} {check}")
return result1, clr_data, result2
def demo_multi_turn():
"""Demo: Multi-turn conversation showing memory accumulation."""
print("\n" + "=" * 60)
print("DEMO: Multi-Turn Conversation")
print("=" * 60)
graph = build_graph()
turns = [
"Hi, I'm trying to learn algebra. I'm a bit nervous because I haven't done math in years.",
"I work at a coffee shop, so I'm actually pretty good with money calculations.",
"Can you explain what a variable is? I remember hearing about X and Y but I don't really get it.",
]
state = {
"messages": [],
"memories": [],
"learner_id": "urn:uuid:multi-turn-demo",
}
for i, turn in enumerate(turns, 1):
print(f"\n--- Turn {i} ---")
print(f"[Learner]: {turn}")
state["messages"].append(HumanMessage(content=turn))
result = graph.invoke(state)
# Update state with result
state = result
print(f"[Tutor]: {result['messages'][-1].content[:200]}...")
print(f"[Total memories]: {len(result['memories'])}")
print("\n--- Final Memory Summary ---")
for mem in state["memories"]:
print(f" - [{mem['category']}] {mem['content']}")
return state
def demo_memory_evolution():
"""Demo: How memory evolves responsibly over time.
This demo specifically addresses the Build-a-thon requirement:
"A clear update rule that shows how memory evolves responsibly over time"
"""
print("\n" + "=" * 60)
print("DEMO: Memory Evolution (Update Rules)")
print("=" * 60)
print("\nThis demo shows how the memory system:")
print(" 1. Extracts new information incrementally")
print(" 2. Avoids duplicating existing memories")
print(" 3. Tracks provenance and confidence")
print(" 4. Could support corrections (future)")
graph = build_graph()
state = {
"messages": [],
"memories": [],
"learner_id": "urn:uuid:evolution-demo",
}
# Turn 1: Initial introduction
print("\n" + "-" * 60)
print("TURN 1: Initial Introduction")
print("-" * 60)
turn1 = "Hi! I'm Jordan. I'm a parent of two kids and I work night shifts as a security guard. I'm trying to get my GED."
print(f"\n[Learner]: {turn1}")
state["messages"].append(HumanMessage(content=turn1))
result = graph.invoke(state)
state = result
print(f"\n[Memories extracted]: {len(state['memories'])}")
for mem in state["memories"]:
print(f" + NEW [{mem['category']}] {mem['content']}")
print(f" confidence: {mem['confidence']:.2f}, source: {mem['source']}")
memories_after_turn1 = len(state["memories"])
# Turn 2: Add new information (should not duplicate)
print("\n" + "-" * 60)
print("TURN 2: Adding New Information")
print("-" * 60)
turn2 = "Math is really hard for me, especially fractions. But I'm good at reading - I read to my kids every night."
print(f"\n[Learner]: {turn2}")
state["messages"].append(HumanMessage(content=turn2))
result = graph.invoke(state)
state = result
new_memories = len(state["memories"]) - memories_after_turn1
print(f"\n[New memories extracted]: {new_memories}")
print(f"[Total memories]: {len(state['memories'])}")
# Show only new memories
for mem in state["memories"][memories_after_turn1:]:
print(f" + NEW [{mem['category']}] {mem['content']}")
print(f" confidence: {mem['confidence']:.2f}")
# Verify no duplicates
print(f"\n[Duplicate check]: Previous facts (parent, night shift, GED) NOT re-extracted ✓")
memories_after_turn2 = len(state["memories"])
# Turn 3: Reinforce existing info (should not duplicate)
print("\n" + "-" * 60)
print("TURN 3: Reinforcing Without Duplicating")
print("-" * 60)
turn3 = "Yeah, working nights is tough but I need to pass this GED. Can we start with fractions since that's my weak point?"
print(f"\n[Learner]: {turn3}")
state["messages"].append(HumanMessage(content=turn3))
result = graph.invoke(state)
state = result
new_memories = len(state["memories"]) - memories_after_turn2
print(f"\n[New memories extracted]: {new_memories}")
print(f"[Total memories]: {len(state['memories'])}")
if new_memories > 0:
for mem in state["memories"][memories_after_turn2:]:
print(f" + NEW [{mem['category']}] {mem['content']}")
else:
print(" (No new memories - existing context sufficient)")
print(f"\n[Duplicate check]: 'GED goal' and 'fractions difficulty' NOT duplicated ✓")
# Summary
print("\n" + "-" * 60)
print("MEMORY EVOLUTION SUMMARY")
print("-" * 60)
print(f"\nTotal memories after 3 turns: {len(state['memories'])}")
print("\nBy category:")
categories = {}
for mem in state["memories"]:
cat = mem["category"]
categories[cat] = categories.get(cat, 0) + 1
for cat, count in sorted(categories.items()):
print(f" - {cat}: {count}")
print("\nUpdate rules demonstrated:")
print(" ✓ Incremental extraction (new info only)")
print(" ✓ No duplication (existing memories preserved)")
print(" ✓ Provenance tracking (source, confidence)")
print(" ○ Correction/superseding (future capability)")
print("\nAll memories:")
for i, mem in enumerate(state["memories"], 1):
print(f" {i}. [{mem['category']}] {mem['content']}")
return state
def main():
parser = argparse.ArgumentParser(description="Demo Portable Learner Memory")
parser.add_argument("--conversation", action="store_true", help="Single conversation demo")
parser.add_argument("--export", action="store_true", help="Export format demo")
parser.add_argument("--roundtrip", action="store_true", help="Full round-trip demo")
parser.add_argument("--multi", action="store_true", help="Multi-turn conversation demo")
parser.add_argument("--evolution", action="store_true", help="Memory evolution demo (update rules)")
parser.add_argument("--all", action="store_true", help="Run all demos (default)")
args = parser.parse_args()
# Default to all if no specific demo selected
run_all = args.all or not any([args.conversation, args.export, args.roundtrip, args.multi, args.evolution])
print("\n" + "=" * 60)
print("PORTABLE LEARNER MEMORY - Demo Suite")
print("=" * 60)
if args.conversation or run_all:
result = demo_conversation()
if args.export or run_all:
# Use memories from conversation if available
memories = result.get("memories") if "result" in dir() else None
demo_export(memories)
if args.roundtrip or run_all:
demo_roundtrip()
if args.evolution or run_all:
demo_memory_evolution()
if args.multi and not run_all:
# Only run multi if explicitly requested (evolution covers similar ground)
demo_multi_turn()
print("\n" + "=" * 60)
print("DEMO COMPLETE")
print("=" * 60 + "\n")
if __name__ == "__main__":
main()