Skip to content

Commit 015c4e3

Browse files
committed
Fix syntax errors and API usage in section-3 notebooks
Fixed 03_memory_integration.ipynb: - Added missing user_id parameter to get_or_create_working_memory calls - Fixed iteration over search results (need .memories attribute) - Fixed filtering of all_memories (need .memories attribute) - Fixed incomplete list comprehension Fixed 04_memory_tools.ipynb: - Added missing closing bracket ] in create_long_term_memory call
1 parent 85cbe9e commit 015c4e3

File tree

3 files changed

+151
-6
lines changed

3 files changed

+151
-6
lines changed

python-recipes/context-engineering/notebooks/section-3-memory/03_memory_integration.ipynb

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,7 @@
191191
"from agent_memory_client.models import WorkingMemory, MemoryMessage\n",
192192
"\n",
193193
"# Convert messages to MemoryMessage format\n",
194-
"memory_messages = [MemoryMessage(**msg) for msg in []\n",
194+
"memory_messages = [MemoryMessage(**msg) for msg in []]\n",
195195
"\n",
196196
"# Create WorkingMemory object\n",
197197
"working_memory = WorkingMemory(\n",
@@ -332,7 +332,7 @@
332332
"\n",
333333
"if memories:\n",
334334
" print(\"✅ Extracted memories found:\\n\")\n",
335-
" for i, memory in enumerate(memories, 1):\n",
335+
" for i, memory in enumerate(memories.memories, 1):\n",
336336
" print(f\"{i}. {memory.text}\")\n",
337337
" print(f\" Type: {memory.memory_type} | Topics: {', '.join(memory.topics)}\")\n",
338338
" print()\n",
@@ -405,7 +405,7 @@
405405
"from agent_memory_client.models import WorkingMemory, MemoryMessage\n",
406406
"\n",
407407
"# Convert messages to MemoryMessage format\n",
408-
"memory_messages = [MemoryMessage(**msg) for msg in []\n",
408+
"memory_messages = [MemoryMessage(**msg) for msg in []]\n",
409409
"\n",
410410
"# Create WorkingMemory object\n",
411411
"working_memory = WorkingMemory(\n",
@@ -451,8 +451,8 @@
451451
" limit=20\n",
452452
")\n",
453453
"\n",
454-
"semantic_memories = [m for m in all_memories if m.memory_type == \"semantic\"].memories\n",
455-
"episodic_memories = [m for m in all_memories if m.memory_type == \"episodic\"].memories\n",
454+
"semantic_memories = [m for m in all_memories.memories if m.memory_type == \"semantic\"].memories\n",
455+
"episodic_memories = [m for m in all_memories.memories if m.memory_type == \"episodic\"].memories\n",
456456
"\n",
457457
"print(f\"Semantic memories (facts): {len(semantic_memories)}\")\n",
458458
"for memory in semantic_memories.memories:\n",

python-recipes/context-engineering/notebooks/section-3-memory/04_memory_tools.ipynb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,7 @@
204204
" text=text,\n",
205205
" memory_type=memory_type,\n",
206206
" topics=topics if topics else [\"general\"]\n",
207-
" )\n",
207+
" )])\n",
208208
" return f\"✅ Stored memory: {text}\"\n",
209209
" except Exception as e:\n",
210210
" return f\"❌ Failed to store memory: {str(e)}\"\n",
Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Fix syntax errors and API usage issues in notebooks.
4+
"""
5+
6+
import json
7+
import re
8+
from pathlib import Path
9+
10+
11+
def fix_04_memory_tools(notebook_path):
12+
"""Fix 04_memory_tools.ipynb issues."""
13+
with open(notebook_path, 'r') as f:
14+
nb = json.load(f)
15+
16+
modified = False
17+
for cell in nb['cells']:
18+
if cell['cell_type'] == 'code':
19+
source = ''.join(cell['source'])
20+
21+
# Fix missing closing bracket in create_long_term_memory call
22+
if 'await memory_client.create_long_term_memory([ClientMemoryRecord(' in source:
23+
new_source = []
24+
in_create_call = False
25+
bracket_count = 0
26+
27+
for line in cell['source']:
28+
if 'await memory_client.create_long_term_memory([ClientMemoryRecord(' in line:
29+
in_create_call = True
30+
bracket_count = line.count('[') - line.count(']')
31+
elif in_create_call:
32+
bracket_count += line.count('[') - line.count(']')
33+
bracket_count += line.count('(') - line.count(')')
34+
35+
# If we see the closing paren for ClientMemoryRecord but no closing bracket
36+
if in_create_call and '))' in line and bracket_count > 0:
37+
# Add the missing closing bracket
38+
line = line.replace('))', ')])')
39+
in_create_call = False
40+
modified = True
41+
42+
new_source.append(line)
43+
44+
cell['source'] = new_source
45+
46+
if modified:
47+
with open(notebook_path, 'w') as f:
48+
json.dump(nb, f, indent=2, ensure_ascii=False)
49+
f.write('\n')
50+
return True
51+
return False
52+
53+
54+
def fix_03_memory_integration(notebook_path):
55+
"""Fix 03_memory_integration.ipynb issues."""
56+
with open(notebook_path, 'r') as f:
57+
nb = json.load(f)
58+
59+
modified = False
60+
for cell in nb['cells']:
61+
if cell['cell_type'] == 'code':
62+
source = ''.join(cell['source'])
63+
64+
# Fix 1: Add missing user_id to get_or_create_working_memory calls
65+
if 'get_or_create_working_memory(' in source and 'user_id=' not in source:
66+
new_source = []
67+
for i, line in enumerate(cell['source']):
68+
new_source.append(line)
69+
# Add user_id after session_id
70+
if 'session_id=' in line and i + 1 < len(cell['source']) and 'model_name=' in cell['source'][i + 1]:
71+
indent = len(line) - len(line.lstrip())
72+
new_source.append(' ' * indent + 'user_id="demo_user",\n')
73+
modified = True
74+
cell['source'] = new_source
75+
source = ''.join(cell['source'])
76+
77+
# Fix 2: Fix incomplete list comprehension
78+
if 'memory_messages = [MemoryMessage(**msg) for msg in []' in source and not 'memory_messages = [MemoryMessage(**msg) for msg in []]' in source:
79+
new_source = []
80+
for line in cell['source']:
81+
if 'memory_messages = [MemoryMessage(**msg) for msg in []' in line and line.strip().endswith('[]'):
82+
# This line is incomplete, should be empty list
83+
line = line.replace('for msg in []', 'for msg in []]')
84+
modified = True
85+
new_source.append(line)
86+
cell['source'] = new_source
87+
source = ''.join(cell['source'])
88+
89+
# Fix 3: Fix iteration over search results - need .memories
90+
if 'for i, memory in enumerate(memories' in source and 'enumerate(memories.memories' not in source:
91+
new_source = []
92+
for line in cell['source']:
93+
if 'for i, memory in enumerate(memories' in line and '.memories' not in line:
94+
line = line.replace('enumerate(memories', 'enumerate(memories.memories')
95+
modified = True
96+
elif 'for memory in long_term_memories:' in line:
97+
line = line.replace('for memory in long_term_memories:', 'for memory in long_term_memories.memories:')
98+
modified = True
99+
new_source.append(line)
100+
cell['source'] = new_source
101+
source = ''.join(cell['source'])
102+
103+
# Fix 4: Fix filtering - all_memories is a result object
104+
if '[m for m in all_memories if m.memory_type' in source:
105+
new_source = []
106+
for line in cell['source']:
107+
if '[m for m in all_memories if m.memory_type' in line:
108+
line = line.replace('[m for m in all_memories if m.memory_type', '[m for m in all_memories.memories if m.memory_type')
109+
modified = True
110+
new_source.append(line)
111+
cell['source'] = new_source
112+
113+
if modified:
114+
with open(notebook_path, 'w') as f:
115+
json.dump(nb, f, indent=2, ensure_ascii=False)
116+
f.write('\n')
117+
return True
118+
return False
119+
120+
121+
def main():
122+
notebooks_dir = Path(__file__).parent.parent / 'notebooks'
123+
124+
# Fix specific notebooks
125+
fixed = []
126+
127+
nb_path = notebooks_dir / 'section-3-memory' / '04_memory_tools.ipynb'
128+
if nb_path.exists() and fix_04_memory_tools(nb_path):
129+
fixed.append(str(nb_path.relative_to(notebooks_dir)))
130+
131+
nb_path = notebooks_dir / 'section-3-memory' / '03_memory_integration.ipynb'
132+
if nb_path.exists() and fix_03_memory_integration(nb_path):
133+
fixed.append(str(nb_path.relative_to(notebooks_dir)))
134+
135+
if fixed:
136+
print(f"Fixed {len(fixed)} notebooks:")
137+
for nb in fixed:
138+
print(f" - {nb}")
139+
else:
140+
print("No changes needed")
141+
142+
143+
if __name__ == '__main__':
144+
main()
145+

0 commit comments

Comments
 (0)