Module contents
Lesson 24 of 31Core 110 min

External memory and context management

Study an agent's finite context as working memory: context budgeting and ordering, trajectory compaction and prefix caching, and external long-term memory with scoring, virtual context management, writing, and consolidation. Compare policies with a local agent and long-conversation benchmarks.

After this lesson you can

  • Budget an agent's context by component and explain degradation with length even when information fits.
  • Implement and compare windowing, periodic summaries, and old-observation masking on success, tokens, and prefix-cache cost.
  • Implement episodic memory scored by recency, importance, and relevance with periodic reflection.
  • Implement virtual context management with memory functions invoked by the agent.
  • Evaluate long-term memory on a long-conversation benchmark subset against full context and simple RAG.

Before you start

Context has a budget

Context engineering decides which instructions, tools, history, results, and memories the model receives at each step. If a trajectory adds 2,000 tokens at each of 50 steps, accumulated results already total 100,000 tokens before instructions and the answer are counted. The nominal window does not guarantee that the model uses all data equally: position, distractors, and task matter. Context Rot studies performance changes as input grows; it does not imply that every task deteriorates monotonically.

Reserve space for stable instructions, goal, tools, observations, retrieved memory, and output. Measure with the model tokenizer; characters or words are approximations. If data is too large, select it or store it outside the prompt with retrievable identifiers. Order also affects cache reuse and context reading.

Compact and reuse

Compaction can retain a recent window, replace past stages with a summary, mask old observations, or write structured notes outside the context. A window loses old facts; a summary can omit a path, error, or negation; masking preserves conversation structure but not the hidden content. Check the result against tasks requiring those details.

A prefix cache reuses the computation state of an identical prefix. If an edit changes an early token, what follows is no longer a common prefix; changing a summary on each call can save context while reducing reuse. Actual impact depends on the server, cache policy, and measurements, not only length. Anthropic describes compaction and notes; LLMLingua studies another family of prompt compression.

InteractiveThe context timeline
  • Without cache
  • Ideal prefix

Each step adds 120 action and 900 observation tokens; the system uses 100. The simulated summary uses 200 and replaces prior steps. The mask uses 16. The 0/3 result is from the local 0.5B FP16 agent: all four policies failed all three tasks, a sample too small to generalize. Curve sizes are illustrative assumptions.

12
Current context12340
System / actions / observations / summary100 / 1440 / 10800 / 0
Reused prefix11320
Prefill without / with cache80760 / 12340
Prefix invalidatedno
Measured success: three tasks0/3
Simulate policies and the common prefix; compare the size model with measured success on three lab tasks.

The figure counts synthetic prefill tokens under an ideal cache containing only the previous prefix. Success comes from the compaction lab: the 0.5B agent solved 0 of 3 tasks for each policy shown. Three tasks do not support generalization, and the curve measures neither latency nor success.

Memory outside the window

The memory taxonomy distinguishes working memory, situated episodes, semantic knowledge, and procedures. CoALA organizes these functions for language agents. These are not mandatory physical compartments: a single implementation can represent several functions in the same store.

A retrieval score can combine recency rir_i, importance uiu_i, and relevance viv_i:

si=wr norm⁡(ri)+wu norm⁡(ui)+wv norm⁡(vi).s_i=w_r\,\operatorname{norm}(r_i)+w_u\,\operatorname{norm}(u_i)+w_v\,\operatorname{norm}(v_i).

One option is ri=γΔir_i=\gamma^{\Delta_i} with 0<γ≤10<\gamma\le 1; viv_i can be the cosine between query and memory embeddings. Min-max normalization depends on the candidate set and must define the constant case. A high score does not prove that a memory is true. Generative Agents combines these signals and generates reflections from memories; its reflections are inferences that can also be wrong.

InteractiveWhat does the agent remember?

Enter Spanish words from the topics bebida, reunión, documento or música. The vector counts matches in a small vocabulary; it does not understand synonyms outside it.

  1. E. Laura ahora prefiere café. Age 0, importance 9; recency 1.00, normalized importance 1.00, relevance 1.00; total 3.00.
  2. A. Laura prefiere té. Age 8, importance 7; recency 0.00, normalized importance 0.60, relevance 1.00; total 1.60.
  3. C. La ruta del documento está en el archivo. Age 6, importance 8; recency 0.18, normalized importance 0.80, relevance 0.00; total 0.98.
  4. B. La reunión será el martes. Age 3, importance 6; recency 0.52, normalized importance 0.40, relevance 0.00; total 0.92.
  5. D. Laura practica violín antes del concierto. Age 1, importance 4; recency 0.82, normalized importance 0.00, relevance 0.00; total 0.82.

The old and new preferences compete: choosing by score does not automatically resolve the contradiction.

1.0
1.0
1.0
0.90
Top memoryE
Score3.000
Adjust the weights and enter a situation in a synthetic example with four explicit topics.

Virtual context management maintains a small core and an external archive, with functions to search, write, and move data. MemGPT uses the hierarchical memory analogy: the policy and calls decide what enters the window. The next figure is a synthetic trace executed by deterministic functions; it does not claim that a model chose those calls.

InteractivePage memory

Action: Write path and evict oldest

Main context

  • La reunión es el martes.
  • El documento está en /proyecto/notas.md.

External archive

  • Laura prefiere té sin azúcar.

Loading an entry into a full core evicts the oldest. Updating changes the existing preference; it does not by itself erase other contradictory records. Memory texts and identifiers remain in their original Spanish.

3
Core2/2
Archive1
Pressureyes
Step through a sequence of writing, archiving, searching, loading, and updating.

The write and consolidation policy should retain provenance and date, update a preference when it changes, resolve contradictions, and avoid indiscriminately storing everything. A reflection should not automatically overwrite its source: keep links to supporting episodes and allow review. Deletion and expiration are product and task decisions, not properties guaranteed by an embedding.

Evaluate over the long term

Memory evaluation should cover extraction, cross-session relationships, time, changes, and abstention. LoCoMo contains long conversations and evidence-backed questions; LongMemEval studies memory capabilities over extended interactions. One question or conversation does not estimate general performance. Compare truncated context, turn retrieval, and your own memory using the same model, record cost, and use paired intervals when the sample is large enough. An answer verifier also needs domain validation.

Lab: move memories

This synthetic example implements writing, searching, and loading with a two-entry core. The preference is updated without duplicating its key; the states feed the figure. Content and calls form an explicit procedure, not a model trace.

[ ]Core and archiveBrowser
import json,copy
capacity=2;core=[];archive={};trace=[]
def snapshot(action,found=None):
    trace.append({'action':action,'core':copy.deepcopy(core),'archive':copy.deepcopy(list(archive.values())),
                  'found':found,'pressure':len(core)>=capacity})
def write(key,text):
    old=next((x for x in core if x['key']==key),None)
    if old:old['text']=text
    elif key in archive:archive[key]['text']=text
    else:
        if len(core)>=capacity:
            item=core.pop(0);archive[item['key']]=item
        core.append({'key':key,'text':text})
def search(term):
    return [k for k,v in archive.items() if term.lower() in v['text'].lower()]
def page(key):
    if key not in archive:return False
    if len(core)>=capacity:
        item=core.pop(0);archive[item['key']]=item
    core.append(archive.pop(key));return True
snapshot('Inicio')
write('bebida','Laura prefiere té sin azúcar.');snapshot('Escribir preferencia')
write('reunion','La reunión es el martes.');snapshot('Escribir reunión')
write('ruta','El documento está en /proyecto/notas.md.');snapshot('Escribir ruta y desalojar la más antigua')
found=search('té');snapshot('Buscar té en el archivo',found)
assert page('bebida');snapshot('Cargar la preferencia')
write('bebida','Laura ahora prefiere café.');snapshot('Actualizar la preferencia')
print('estados',len(trace),'archivo final',list(archive),'núcleo final',core,flush=True)

Local lab: index a conversation

The cell downloads the official LoCoMo dataset, selects its first conversation and the first three questions in each category, and creates E5 embeddings and an HNSW index for the 419 text turns. It compares the five approximate neighbors with exact search. In the recorded run all neighbors matched across 15 queries; this does not measure whether the answers are correct. It requires requests, PyTorch, sentence-transformers, NumPy, and hnswlib.

[ ]LoCoMo and episodic indexLocal GPU
import hashlib,requests
from pathlib import Path
Path('memory-lab').mkdir(exist_ok=True)
p=Path('memory-lab/locomo10.json')
if not p.exists():
    r=requests.get('https://raw.githubusercontent.com/snap-research/locomo/3eb6f2c585f5e1699204e3c3bdf7adc5c28cb376/data/locomo10.json',timeout=120);r.raise_for_status();p.write_bytes(r.content)
if hashlib.sha256(p.read_bytes()).hexdigest()!='79fa87e90f04081343b8c8debecb80a9a6842b76a7aa537dc9fdf651ea698ff4':raise ValueError('hash incorrecto')

import json,re,collections,numpy as np,torch,hnswlib
from sentence_transformers import SentenceTransformer
torch.set_num_threads(4)
root='memory-lab/'
dataset=json.load(open(root+'locomo10.json',encoding='utf-8'));conversation=dataset[0];c=conversation['conversation']
sessions=sorted((k for k in c if re.fullmatch(r'session_\d+',k)),key=lambda x:int(x.split('_')[1]))
turns=[]
for i,s in enumerate(sessions):
    for turn in c[s]:turns.append({'id':turn['dia_id'],'session':i+1,'time':c[s+'_date_time'],'speaker':turn['speaker'],'text':turn['text']})
questions=[]
for category in range(1,6):
    questions.extend([q for q in conversation['qa'] if q['category']==category][:3])
model=SentenceTransformer('intfloat/multilingual-e5-small',revision='614241f622f53c4eeff9890bdc4f31cfecc418b3',device='cpu')
texts=[f"{r['time']} {r['speaker']}: {r['text']}" for r in turns]
X=model.encode(['passage: '+s for s in texts],normalize_embeddings=True,convert_to_numpy=True,batch_size=16,show_progress_bar=True)
Q=model.encode(['query: '+q['question'] for q in questions],normalize_embeddings=True,convert_to_numpy=True,batch_size=8)
index=hnswlib.Index(space='cosine',dim=X.shape[1]);index.init_index(max_elements=len(X),ef_construction=100,M=16,random_seed=24)
index.add_items(X,np.arange(len(X)),num_threads=1);index.set_ef(100)
ids,_=index.knn_query(Q,k=5,num_threads=1);exact=np.argsort(-([email protected]),axis=1,kind='stable')[:,:5]
recall=np.mean([len(set(a).intersection(b))/5 for a,b in zip(ids,exact)])
np.savez_compressed(root+'embeddings.npz',X=X,Q=Q)
with open(root+'memory.json','w',encoding='utf-8') as f:json.dump({'sample_id':conversation['sample_id'],'turns':turns,'questions':questions,'hnsw_top5':ids.tolist(),'hnsw_exact_overlap':float(recall)},f,ensure_ascii=False,indent=2)
print('sessions',len(sessions),'turns',len(turns),'questions',len(questions),'HNSW overlap@5',recall,flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Local lab: memories, reflections, and questions

This cell uses the preceding index and Qwen2.5-7B-Instruct quantized to NF4. It asks the model for importance scores for each turn and generates one reflection per session, retaining source identifiers. It compares the truncated end of the conversation, five retrieved turns, and five memories selected by HNSW, recency, importance, and relevance. It also generates a synthetic trace of tools selected by the model. It requires CUDA, bitsandbytes, and accelerate; downloading original weights and processing are expensive. Unparseable scores use the fallback value 5 and are logged. Recency uses distance in session count, not real time; reflections use fixed importance 5.

The metric for categories 1 through 4 is normalized exact match, and for the adversarial category it is an explicit abstention rule. These are not the official LoCoMo metrics. There are only three questions per category from one conversation, so bootstrap intervals are unstable and do not establish which policy is better. Each batch of importance, reflection, and answers is saved to permit resumption.

[ ]Episodic memory and LoCoMo evaluationLocal GPU
import json,re,string,time,os,numpy as np,torch,hnswlib
from sentence_transformers import SentenceTransformer
from transformers import AutoTokenizer,AutoModelForCausalLM,BitsAndBytesConfig
torch.set_num_threads(4)
root='memory-lab/'
data=json.load(open(root+'memory.json',encoding='utf8'));turns=data['turns'];questions=data['questions']
arrays=np.load(root+'embeddings.npz');X=arrays['X'];Q=arrays['Q']
name='Qwen/Qwen2.5-7B-Instruct';rev='a09a35458c702b33eeacc393d103063234e8bc28'
tok=AutoTokenizer.from_pretrained(name,revision=rev);tok.padding_side='left'
config=BitsAndBytesConfig(load_in_4bit=True,bnb_4bit_quant_type='nf4',bnb_4bit_compute_dtype=torch.float16)
model=AutoModelForCausalLM.from_pretrained(name,revision=rev,quantization_config=config,device_map={'':0},dtype=torch.float16).eval()
def generate(prompt,limit=24):
    chat=tok.apply_chat_template([{'role':'user','content':prompt}],tokenize=False,add_generation_prompt=True)
    batch=tok(chat,return_tensors='pt').to('cuda');start=time.perf_counter()
    with torch.no_grad():out=model.generate(**batch,max_new_tokens=limit,do_sample=False,pad_token_id=tok.eos_token_id)
    return {'text':tok.decode(out[0,batch['input_ids'].shape[1]:],skip_special_tokens=True).strip(),
            'input_tokens':batch['input_ids'].shape[1],'output_tokens':out.shape[1]-batch['input_ids'].shape[1],
            'seconds':time.perf_counter()-start}
path=root+'importance.json';ratings=json.load(open(path,encoding='utf8')) if os.path.exists(path) else []
for i in range(len(ratings),len(turns),8):
    subset=turns[i:i+8];prompts=[]
    for r in subset:
        text='Rate the importance of this memory for future conversation from 1 to 10. Reply with only the integer.\nMemory: '+r['speaker']+': '+r['text']
        prompts.append(tok.apply_chat_template([{'role':'user','content':text}],tokenize=False,add_generation_prompt=True))
    batch=tok(prompts,padding=True,return_tensors='pt').to('cuda')
    with torch.no_grad():out=model.generate(**batch,max_new_tokens=4,do_sample=False,pad_token_id=tok.eos_token_id)
    for raw in tok.batch_decode(out[:,batch['input_ids'].shape[1]:],skip_special_tokens=True):
        m=re.search(r'\b(?:10|[1-9])\b',raw);ratings.append({'value':int(m.group()) if m else 5,'raw':raw,'fallback':not bool(m)})
    with open(path,'w',encoding='utf8') as f:json.dump(ratings,f,ensure_ascii=False,indent=2)
    print('importance',len(ratings),'/',len(turns),flush=True)
path=root+'reflections.json';reflections=json.load(open(path,encoding='utf8')) if os.path.exists(path) else []
for session in range(len(reflections)+1,20):
    members=[r for r in turns if r['session']==session]
    text='\n'.join(r['speaker']+': '+r['text'] for r in members)
    tokens=tok.encode(text,add_special_tokens=False)[:1000];text=tok.decode(tokens,skip_special_tokens=True)
    result=generate('Summarize durable facts in these conversation turns. Do not add facts.\n'+text,80)
    reflections.append({'session':session,'text':result['text'],'source_ids':[r['id'] for r in members],'generation':result})
    with open(path,'w',encoding='utf8') as f:json.dump(reflections,f,ensure_ascii=False,indent=2)
    print('reflection',session,flush=True)
encoder=SentenceTransformer('intfloat/multilingual-e5-small',revision='614241f622f53c4eeff9890bdc4f31cfecc418b3',device='cpu')
R=encoder.encode(['passage: '+r['text'] for r in reflections],normalize_embeddings=True,convert_to_numpy=True)
all_vectors=np.concatenate([X,R]);index=hnswlib.Index(space='cosine',dim=X.shape[1]);index.init_index(max_elements=len(all_vectors),ef_construction=100,M=16,random_seed=24)
index.add_items(all_vectors,np.arange(len(all_vectors)),num_threads=1);index.set_ef(100)
all_mem=[{'text':r['time']+' '+r['speaker']+': '+r['text'],'session':r['session'],'id':r['id'],'importance':ratings[i]['value']} for i,r in enumerate(turns)]
all_mem.extend({'text':'Reflection: '+r['text'],'session':r['session'],'id':'reflection-'+str(r['session']),'importance':5} for r in reflections)
def scale(x):
    x=np.asarray(x,dtype=float);return np.zeros_like(x) if x.max()==x.min() else (x-x.min())/(x.max()-x.min())
def select_memory(v):
    candidate=index.knn_query(v.reshape(1,-1),k=50,num_threads=1)[0][0];c=[all_mem[int(i)] for i in candidate]
    relevance=all_vectors[candidate]@v;recency=np.array([np.exp(-.1*(19-r['session'])) for r in c]);importance=np.array([r['importance'] for r in c])
    score=scale(relevance)+scale(recency)+scale(importance)
    return [c[int(i)] for i in np.argsort(-score,kind='stable')[:5]]
def norm(s):
    return ' '.join(w for w in str(s).lower().translate(str.maketrans('','',string.punctuation)).split() if w not in ('a','an','the'))
def score_answer(answer,q):
    if q['category']==5:return int(bool(re.search(r'\b(unknown|no information available|not enough information|cannot determine|not mentioned|not provided|do not know|i don.t know)\b',answer.lower())))
    return int(norm(answer)==norm(q['answer']))
path=root+'benchmark.json';results=json.load(open(path,encoding='utf8')) if os.path.exists(path) else []
done={(r['method'],r['question']) for r in results}
history='\n'.join(r['time']+' '+r['speaker']+': '+r['text'] for r in turns)
history_ids=tok.encode(history,add_special_tokens=False);truncated=tok.decode(history_ids[-3000:],skip_special_tokens=True)
for qi,q in enumerate(questions):
    v=Q[qi];nearest=np.argsort(-(X@v),kind='stable')[:5]
    memories=select_memory(v)
    contexts={'truncado':truncated,'rag':'\n'.join(all_mem[int(i)]['text'] for i in nearest),'memoria':'\n'.join(r['text'] for r in memories)}
    for method,context in contexts.items():
        if (method,q['question']) in done:continue
        result=generate('Answer the question using only this conversation memory. If absent, say UNKNOWN. Return a short answer.\nMemory:\n'+context+'\nQuestion: '+q['question']+'\nAnswer:',24)
        row={'method':method,'category':q['category'],'question':q['question'],'reference':q.get('answer'),'output':result,
             'correct':score_answer(result['text'],q),'retrieved_ids':([turns[int(i)]['id'] for i in nearest] if method=='rag' else [r['id'] for r in memories] if method=='memoria' else [])}
        results.append(row)
        with open(path,'w',encoding='utf8') as f:json.dump(results,f,ensure_ascii=False,indent=2)
        print('qa',qi,method,repr(result['text']),row['correct'],flush=True)
rng=np.random.default_rng(24);summary={}
for method in ('truncado','rag','memoria'):
    summary[method]={}
    for cat in range(1,6):
        a=np.array([r['correct'] for r in results if r['method']==method and r['category']==cat]);boot=a[rng.integers(0,len(a),(2000,len(a)))].mean(axis=1)
        summary[method][str(cat)]={'n':len(a),'mean':float(a.mean()),'ci':np.quantile(boot,[.025,.975]).tolist()}
with open(root+'summary.json','w',encoding='utf8') as f:json.dump(summary,f,ensure_ascii=False,indent=2)
print('summary',summary,'importance fallback',sum(r['fallback'] for r in ratings),flush=True)

# Prueba de llamadas elegidas por el modelo sobre un almacén local sintético.
core=[];archive={};tool_trace=[]
requests=["Store key drink: Laura prefers tea without sugar.","Store key meeting: The meeting is Tuesday.",
          "Store key path: The document is /project/notes.md.","Search the archive for tea.",
          "Move key drink from the archive into core.","Update key drink to: Laura now prefers coffee."]
for request in requests:
    prompt=('Choose one memory tool. Reply only JSON: {"tool":"write|search|page", "key":"...", "text":"..."}. '
            'write adds or updates a key; search checks archive text using text; page moves a key from archive into core. '
            'Core holds two items and the oldest is evicted when full.\nCore: '+json.dumps(core)+'\nArchive: '+json.dumps(archive)+'\nRequest: '+request)
    result=generate(prompt,60);match=re.search(r'\{.*?\}',result['text'],re.S);action=None;outcome='invalid JSON'
    try:
        action=json.loads(match.group()) if match else None
        if not isinstance(action,dict):raise ValueError('not an object')
        tool=action.get('tool');key=str(action.get('key',''));text=str(action.get('text',''))
        if tool=='write' and key and text:
            old=next((r for r in core if r['key']==key),None)
            if old:old['text']=text
            elif key in archive:archive[key]['text']=text
            else:
                if len(core)>=2:
                    item=core.pop(0);archive[item['key']]=item
                core.append({'key':key,'text':text})
            outcome='written'
        elif tool=='search' and text:outcome='matches: '+','.join(k for k,v in archive.items() if text.lower() in v['text'].lower())
        elif tool=='page' and key in archive:
            if len(core)>=2:
                item=core.pop(0);archive[item['key']]=item
            core.append(archive.pop(key));outcome='paged'
        else:outcome='unsupported or missing arguments'
    except (ValueError,TypeError):pass
    tool_trace.append({'request':request,'raw':result,'action':action,'outcome':outcome,
                       'core':json.loads(json.dumps(core)),'archive':json.loads(json.dumps(archive))})
    with open(root+'tool_trace.json','w',encoding='utf8') as f:json.dump(tool_trace,f,ensure_ascii=False,indent=2)
    print('tool',request,repr(result['text']),outcome,flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

On a 12 GiB RTX 3060, all 419 turns, 19 reflections, and 15 questions from the first LoCoMo conversation, three per category, were run for each method. With normalized exact match and the abstention rule corrected below, categories 1, 2, and 3 yielded 0/3 for all three methods. In category 4, truncation scored 0/3 and RAG and memory 1/3 each; in category 5, truncation scored 3/3, RAG 2/3, and memory 3/3. Bootstrapping questions within each category gives intervals [0, 0], [0, 1], or [1, 1] for these results; with only three questions they are unstable and do not establish general superiority. Exact match penalizes equivalent answers phrased differently and should be supplemented by independent semantic review.

The original abstention classifier did not recognize “NEED MORE INFORMATION,” an effectively abstaining answer to an unanswerable question. The next cell adds that expression after seeing the results, preserves the original file, and records the only change: truncation goes from 2/3 to 3/3 in that category. The post hoc correction may favor this sample and must be fixed before evaluating another. In the synthetic tool test, five of six calls were rejected for tool or arguments and the valid search found nothing because no memory had been written: this is a failure observed in this protocol, not a demonstration of successful paging. Latencies were measured with other runs concurrent.

[ ]Recompute abstention without regenerating answersLocal GPU
import json,re,numpy as np
from pathlib import Path
path=Path('memory-lab/benchmark.json')
rows=json.loads(path.read_text(encoding='utf8'))
assert len(rows)==45
changes=[]
for r in rows:
    original=r['correct']
    if r['category']==5 and re.search(r'\bneed more information\b',r['output']['text'],re.I):
        r['correct']=1
    if r['correct']!=original:
        changes.append({'method':r['method'],'question':r['question'],'old':original,'new':r['correct']})
rng=np.random.default_rng(24);summary={}
for method in ('truncado','rag','memoria'):
    summary[method]={}
    for category in range(1,6):
        a=np.array([r['correct'] for r in rows if r['method']==method and r['category']==category])
        boot=a[rng.integers(0,len(a),(2000,len(a)))].mean(axis=1)
        summary[method][str(category)]={'n':len(a),'success':int(a.sum()),'mean':float(a.mean()),'ci':np.quantile(boot,[.025,.975]).tolist()}
out={'changes':changes,'summary':summary}
Path('memory-lab/summary_rescored.json').write_text(json.dumps(out,ensure_ascii=False,indent=2),encoding='utf8')
print(out)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Replace the library with your own HNSW

The preceding benchmark uses hnswlib, although the curriculum also asks you to test your own index. Download the from-scratch implementation as hnsw_from_scratch.py: it is the HNSW cell, pinned by SHA256 902b0676f435f44cb6d3ca1c6e1ec4eb06264951178ccfe8d63d1f8be2e2039f. On the same 419 turns and 19 reflections, with M=8, ef_construction=32, and ef=100, it achieved mean recall@50 of 0.9773 against exact ordering across the 15 questions. The five selected memories match the library order in 14 of 15 cases; the preceding 15 answers therefore cannot simply be attributed to this index.

This cell reuses the LoCoMo evaluation variables and regenerates only answers whose selection changes. For the others it retains the measured answer with explicit provenance: model, prompt, and five memories are identical. For the changed question, the new answer was “mental health” and matched the reference exactly, so the per-category counts for the custom memory did not change in this sample. Generation requires the same 7B model loaded in the preceding cell; it saves results separately from benchmark.json.

[ ]Evaluate memories with HNSW from scratchLocal GPU
import importlib.util,sys,json,numpy as np
from pathlib import Path
spec=importlib.util.spec_from_file_location('own_hnsw','hnsw_from_scratch.py')
own=importlib.util.module_from_spec(spec);sys.modules[spec.name]=own;spec.loader.exec_module(own)
own_index=own.HNSW(M=8,ef_construction=32,seed=20)
for vector in all_vectors:own_index.add(vector)
by_id={r['id']:r for r in all_mem};new_results=[];recalls=[];same=0
for qi,q in enumerate(questions):
    vector=Q[qi];candidates,_=own_index.search(vector,50,ef=100)
    exact=np.argsort(-(all_vectors@vector),kind='stable')[:50]
    recalls.append(len(set(candidates)&set(exact))/50)
    c=[all_mem[i] for i in candidates]
    score=scale(all_vectors[candidates]@vector)+scale([np.exp(-.1*(19-r['session'])) for r in c])+scale([r['importance'] for r in c])
    chosen=[c[int(i)] for i in np.argsort(-score,kind='stable')[:5]]
    selected=[r['id'] for r in chosen]
    previous=next(r for r in results if r['method']=='memoria' and r['question']==q['question'])
    if selected==previous['retrieved_ids']:
        item=dict(previous);item['provenance']='misma selección ordenada, respuesta anterior reutilizada';same+=1
    else:
        context='\n'.join(r['text'] for r in chosen)
        result=generate('Answer the question using only this conversation memory. If absent, say UNKNOWN. Return a short answer.\nMemory:\n'+context+'\nQuestion: '+q['question']+'\nAnswer:',24)
        item={**previous,'output':result,'correct':score_answer(result['text'],q),'retrieved_ids':selected,
              'provenance':'respuesta nueva con selección del HNSW propio'}
    new_results.append(item)
Path('memory-lab/benchmark_own_hnsw.json').write_text(json.dumps(new_results,ensure_ascii=False,indent=2),encoding='utf8')
print('recall@50 medio',float(np.mean(recalls)),'selecciones iguales',same,'de',len(questions))
print('respuestas cambiadas',[(r['question'],r['output']['text'],r['correct']) for r in new_results if r['provenance'].startswith('respuesta nueva')])
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Local lab: compact a ReAct trace

This experiment uses the engine from lesson 13: download it as react_engine.py in the current directory. It is a copy of that lesson’s engine, SHA256 1588574a37dd8e7f9127be6023a9aed4ef4315afba0fdd52da1dfbc9e8a7e9c2. It compares five policies on three fictional file systems, each with three hops. The adapter adds the same demonstration to each call; serialization for counting tokens and estimating prefixes is identical to what is sent. The summary policy concatenates observation excerpts every two old pairs: it is deterministic and does not call a model to summarize. The notes policy writes each read to a file and offers a tool to consult it; the agent decides whether to call it.

With Qwen2.5-0.5B-Instruct FP16 on GPU, temperature zero, and up to eight steps, all five policies solved 0 of 3 tasks. Mean input tokens were 2182.3 for full history, 862.3 for window, 2132 for masking, 1933.7 for summary, and 1458.3 for notes. These are distinct, tiny runs with different stopping points: fewer tokens do not demonstrate a better policy. Bootstrap intervals for success are [0, 0] in this sample and do not prove the true probability is zero. Output tokens, traces, and seconds per case were also recorded.

The ideal_prefill column sums tokens that do not belong to the prefix shared with the preceding call. This is an idealized count of exact prefixes: the server below recomputes everything and does not implement a real prefix cache. It does not measure savings or latency with caching. To investigate effective caching, use a server that implements it and exposes counters, and repeat the same protocol with and without reuse.

Install PyTorch with CUDA support, transformers, and requests; save the server code as memory_server.py and run it in another terminal with python memory_server.py 18973. It listens only on loopback. Stop that process when finished. Do not use the port if it is occupied; change the number in both files. The pinned model downloads the first time.

[ ]Temporary lab serverLocal GPU
import json,sys,time,uuid,torch
from http.server import BaseHTTPRequestHandler,HTTPServer
from transformers import AutoTokenizer,AutoModelForCausalLM
name='Qwen/Qwen2.5-0.5B-Instruct';rev='7ae557604adf67be50417f59c2c2f167def9a775'
tok=AutoTokenizer.from_pretrained(name,revision=rev)
model=AutoModelForCausalLM.from_pretrained(name,revision=rev,dtype=torch.float16).to('cuda').eval()
class Handler(BaseHTTPRequestHandler):
    def respond(self,code,payload):
        data=json.dumps(payload,ensure_ascii=False).encode('utf8');self.send_response(code)
        self.send_header('Content-Type','application/json');self.send_header('Content-Length',str(len(data)));self.end_headers();self.wfile.write(data)
    def do_GET(self):
        if self.path=='/v1/models':self.respond(200,{'object':'list','data':[{'id':'local','object':'model','owned_by':'local'}]})
        else:self.respond(404,{'error':'not found'})
    def do_POST(self):
        if self.path!='/v1/chat/completions':return self.respond(404,{'error':'not found'})
        try:
            body=json.loads(self.rfile.read(int(self.headers.get('Content-Length','0'))))
            if body.get('stream') or body.get('n',1)!=1:raise ValueError('solo n=1 y sin streaming')
            text=tok.apply_chat_template(body['messages'],tokenize=False,add_generation_prompt=True)
            batch=tok(text,return_tensors='pt').to('cuda');temperature=body.get('temperature',0) or 0
            kwargs={'max_new_tokens':body.get('max_tokens',body.get('max_completion_tokens',96)),'do_sample':temperature>0,'pad_token_id':tok.eos_token_id}
            if temperature>0:kwargs['temperature']=temperature
            with torch.no_grad():out=model.generate(**batch,**kwargs)
            generated=out[0,batch['input_ids'].shape[1]:];content=tok.decode(generated,skip_special_tokens=True)
            prompt=int(batch['input_ids'].shape[1]);completion=int(generated.shape[0]);finish='length' if completion>=kwargs['max_new_tokens'] else 'stop'
            self.respond(200,{'id':'chatcmpl-'+uuid.uuid4().hex,'object':'chat.completion','created':int(time.time()),'model':'local',
                              'choices':[{'index':0,'message':{'role':'assistant','content':content},'finish_reason':finish}],
                              'usage':{'prompt_tokens':prompt,'completion_tokens':completion,'total_tokens':prompt+completion}})
        except Exception as e:self.respond(400,{'error':{'message':str(e),'type':'invalid_request_error'}})
    def log_message(self,fmt,*args):pass
if __name__=='__main__':
    port=int(sys.argv[1]);print('HTTP loopback',port,'Qwen 0.5B FP16 GPU',flush=True)
    HTTPServer(('127.0.0.1',port),Handler).serve_forever()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Then run this cell from the same directory as react_engine.py; it writes results to memory-lab. Keep the complete JSON files: they permit review of calls, context, and stopping reason. This protocol does not replace the broader LoCoMo benchmark comparison, nor does it run a real cache.

[ ]Five compaction policiesLocal GPU
import importlib.util,sys,json,time,copy,requests,random
from pathlib import Path
from transformers import AutoTokenizer
root=Path('memory-lab');root.mkdir(parents=True,exist_ok=True)
spec=importlib.util.spec_from_file_location('react_engine','react_engine.py')
engine=importlib.util.module_from_spec(spec);sys.modules[spec.name]=engine;spec.loader.exec_module(engine)
tok=AutoTokenizer.from_pretrained('Qwen/Qwen2.5-0.5B-Instruct',revision='7ae557604adf67be50417f59c2c2f167def9a775')
examples=[{'role':'user','content':'Read /people/ada.txt and then the named city file. Answer the country.'},
          {'role':'assistant','content':'{"action":"read","argument":"/people/ada.txt"}'},
          {'role':'user','content':'Observation: Ada works in Tallinn; read /cities/tallinn.txt.'},
          {'role':'assistant','content':'{"action":"read","argument":"/cities/tallinn.txt"}'},
          {'role':'user','content':'Observation: Tallinn is in Estonia.'},
          {'role':'assistant','content':'{"final":"Estonia"}'}]
def serialize(messages):return tok.apply_chat_template([messages[0]]+examples+messages[1:],tokenize=False,add_generation_prompt=True)
def count(messages):return len(tok(serialize(messages))['input_ids'])
def policy(messages,max_new):
    sent=[messages[0]]+examples+messages[1:]
    r=requests.post('http://127.0.0.1:18973/v1/chat/completions',json={'model':'local','messages':sent,'temperature':0,'max_tokens':max_new},timeout=180)
    r.raise_for_status();body=r.json();u=body['usage']
    return engine.PolicyResponse(body['choices'][0]['message']['content'],u['prompt_tokens'],u['completion_tokens'],serialize(messages))
def compact(history,mode):
    h=copy.deepcopy(history);pairs=[h[i:i+2] for i in range(2,len(h),2)]
    if mode=='todo':return h
    if mode=='ventana':return h[:2]+sum(pairs[-1:],[])
    if mode=='mascara':
        for pair in pairs[:-1]:pair[1]['content']='Observation: [masked old observation]'
        return h[:2]+sum(pairs,[])
    cut=max(0,((len(pairs)-1)//2)*2)
    if cut==0:return h
    old=pairs[:cut];recent=pairs[cut:]
    notes=' | '.join(p[1]['content'][:180] for p in old)
    # El par de nota es insertado por el gestor de contexto, no por el modelo.
    fake=[{'role':'assistant','content':'{"thought":"Context manager note follows."}'},
          {'role':'user','content':'Observation: [extractive context-manager note] '+notes}]
    return h[:2]+fake+sum(recent,[])
def ideal_prefill(events):
    prev=[];cost=0
    for e in events:
        if 'serialized_prompt' not in e:continue
        ids=tok(e['serialized_prompt'])['input_ids'];n=0
        while n<min(len(prev),len(ids)) and prev[n]==ids[n]:n+=1
        cost+=len(ids)-n;prev=ids
    return cost
records=[]
for person,city,country in [('mira','helsinki','Finland'),('lina','lisbon','Portugal'),('toma','oslo','Norway')]:
    fs={f'/people/{person}.txt':f'{person.title()} works in {city.title()}; read /cities/{city}.txt.',
        f'/cities/{city}.txt':f'The country record is /countries/{country.lower()}.txt.',
        f'/countries/{country.lower()}.txt':f'Country: {country}.'}
    question=f'Use read to follow files starting at /people/{person}.txt and answer the country.'
    for mode in ('todo','ventana','mascara','resumen','notas'):
        notes_path=root/f'notes-{person}-{mode}.txt';notes_path.write_text('',encoding='utf8')
        def read(path):
            result=fs.get(path.strip(),'File not found.')
            with open(notes_path,'a',encoding='utf8') as f:f.write(path.strip()+': '+result+'\n')
            return result
        def prepare(history):return compact(history,'ventana' if mode=='notas' else mode)
        tools={'read':read}
        if mode=='notas':tools['notes']=lambda _:notes_path.read_text(encoding='utf8')
        start=time.perf_counter();result=engine.run_agent(question,policy,tools,count,max_steps=8,max_total_tokens=6000,
                    max_context_tokens=1500,max_new_tokens=96,timeout_seconds=600,prepare_context=prepare)
        record={'person':person,'mode':mode,'answer':result['answer'],'expected':country,'success':(result['answer'] or '').strip().lower()==country.lower(),
                'prefill':sum(e.get('input_tokens',0) for e in result['events']),'decode':sum(e.get('output_tokens',0) for e in result['events']),
                'ideal_prefill':ideal_prefill(result['events']),'seconds':time.perf_counter()-start,'result':result}
        records.append(record)
        with open(root/'compaction.json','w',encoding='utf8') as f:json.dump(records,f,ensure_ascii=False,indent=2)
        print(person,mode,result['stop_reason'],repr(result['answer']),record['success'],flush=True)
summary={};rng=random.Random(24)
for mode in ('todo','ventana','mascara','resumen','notas'):
    rows=[r for r in records if r['mode']==mode];a=[int(r['success']) for r in rows]
    boot=sorted(sum(rng.choice(a) for _ in a)/len(a) for _ in range(2000))
    summary[mode]={'n':len(a),'success':sum(a)/len(a),'ci':[boot[49],boot[1949]],'prefill':sum(r['prefill'] for r in rows)/len(a),
                   'ideal_prefill':sum(r['ideal_prefill'] for r in rows)/len(a),'decode':sum(r['decode'] for r in rows)/len(a)}
with open(root/'compaction_summary.json','w',encoding='utf8') as f:json.dump(summary,f,indent=2)
print(summary,flush=True)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Measure effective reuse

The ideal count above does not demonstrate that a server reuses its cache. To observe reuse, download the traces of the 15 runs as compaction-traces.json and replay their prompts with llama-cpp-python 0.3.36 and Qwen2.5-0.5B GGUF Q4_K_M on CPU. The inference object maintains KV state between calls in the same trajectory; this is compared with resetting it before each prompt. We instrument eval: its first call contains the prefill tokens actually evaluated. Each replay generates only one token; it does not replace the original FP16 agent’s decisions or results and does not compare its end-to-end latency. Full traces allow the same ordering and invalidations to be observed again.

Across 95 calls in each condition, total evaluated prefill fell from 25706 tokens without reuse to 6394 with reuse. By policy, without/with cache pairs were: full history 6547/1277, window 2587/907, masking 6396/1547, summary 5801/1570, and notes 4375/1093. This replays fixed prompts with a different weights format, not a second autonomous agent run or an HTTP server with cache. The CPU was shared and individual timings do not establish that one policy is faster in production.

[ ]Effective prefill with and without cache in llama.cppLocal GPU
import json,time,hashlib
from pathlib import Path
from huggingface_hub import hf_hub_download
from llama_cpp import Llama
path=Path('compaction-traces.json')
assert hashlib.sha256(path.read_bytes()).hexdigest()=='257eeac3c9721f2e4a6c17d42466e7359c4bec1ccc38850c9cbc22c5969356ab'
records=json.loads(path.read_text(encoding='utf8'))
model_path=hf_hub_download('Qwen/Qwen2.5-0.5B-Instruct-GGUF','qwen2.5-0.5b-instruct-q4_k_m.gguf',revision='9217f5db79a29953eb74d5343926648285ec7e67')
llm=Llama(model_path=model_path,n_ctx=4096,n_threads=4,verbose=False)
original_eval=llm.eval;calls=[]
def counted(tokens):
    calls.append(len(tokens))
    return original_eval(tokens)
llm.eval=counted
out=[]
for trajectory in records:
    prompts=[e['serialized_prompt'] for e in trajectory['result']['events'] if 'serialized_prompt' in e]
    for caching in (False,True):
        llm.reset()
        for index,prompt in enumerate(prompts):
            if not caching:llm.reset()
            calls.clear();start=time.perf_counter()
            result=llm.create_completion(prompt=prompt,max_tokens=1,temperature=0)
            out.append({'person':trajectory['person'],'mode':trajectory['mode'],'step':index,'cache':caching,
                        'prompt_tokens':result['usage']['prompt_tokens'],'prefill_evaluated':calls[0],
                        'eval_calls':calls.copy(),'output_tokens':result['usage']['completion_tokens'],
                        'seconds':time.perf_counter()-start})
            Path('cache_replay.json').write_text(json.dumps(out,ensure_ascii=False,indent=2),encoding='utf8')
for mode in ('todo','ventana','mascara','resumen','notas'):
    for caching in (False,True):
        rows=[r for r in out if r['mode']==mode and r['cache']==caching]
        print(mode,'caché',caching,'llamadas',len(rows),'tokens de prompt',sum(r['prompt_tokens'] for r in rows),
              'prefill evaluado',sum(r['prefill_evaluated'] for r in rows),'segundos',sum(r['seconds'] for r in rows))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Now run the agent, not just the replay: download the cache lab as cache-live.py alongside react_engine.py and run it with python cache-live.py. It requires requests, transformers, huggingface_hub, and llama-cpp-python 0.3.36. It opens a temporary HTTP server only on loopback, with an automatically chosen free port, and closes it on completion. It uses Qwen2.5-0.5B GGUF Q4_K_M on CPU, not the FP16 from the preceding table; each combination is saved and can be resumed. Each trajectory records success, actual prefill and output tokens, and time; it resets state at the start of each trajectory and, in the no-cache condition, before each call as well.

Across the three tasks, these were success and total tokens for the three runs per condition:

PolicySuccess without / with cachePrefill without / with cacheOutput without / with cache
Full3/3 / 3/31994 / 70291 / 91
Window3/3 / 3/31879 / 71891 / 91
Mask3/3 / 2/31969 / 101491 / 175
Summary3/3 / 3/31994 / 70291 / 91
Notes3/3 / 3/31897 / 72491 / 91

Caching and resetting produced different answers in one masking trajectory even with the same prompt and greedy generation: repeated invalid JSON appeared with caching. We replayed the sequence of three fixed prompts five times per condition: all five runs without cache returned valid final JSON and all five with cache returned two objects, invalid for the parser. The downloadable comparison reads memory-lab/cache_live.json, generated by the preceding lab. This result identifies a reproducible difference in this configuration; it does not by itself identify the cause. Bootstrap intervals with only three tasks are degenerate when all three agree; timings were taken under shared load and cannot rank policies by speed. These five policies use the same goals, but the cache condition can change the trajectory and thus does not always process the same calls.

Exercises

CodeRecency, importance, and relevance
Implement retrieve_memories(memories, query_emb, now, weights, decay, k). Each memory has id, time, importance, and embedding. Compute recency decay**max(0, now-time), importance, and cosine; min-max normalize each component among the candidates, assigning zero if constant. weights contains the three weights in that order. Return (id, score) sorted descending, breaking ties by input order. A vector of zero norm has cosine zero.
def retrieve_memories(memories, query_emb, now, weights, decay, k):
  pass
Shift+Enter to run
CodeCompact without losing the system message
Implement compact(messages, budget, summarize_fn). messages starts with a system message; each message is a dictionary with role and content. Approximate token counts with space-separated words. If it fits already, return a copy without calling the summarizer. Otherwise, mask role='observation' messages before the last two messages with '[observación omitida]' (observation omitted); if it still does not fit, summarize those old messages once and retain the system and last two messages. If even that exceeds budget, raise ValueError.
def compact(messages, budget, summarize_fn):
  pass
Shift+Enter to run
NumericThirty steps
A trajectory adds exactly 1500 tokens in each of 30 steps. Ignore system, output, and summarization cost. How many prefill tokens are processed without cache if each step resends the entire history?
Quiz
A person changes their preference from tea to coffee. Which policy reduces the chance of retrieving the old preference as current?
Quiz
Why can an agent fail even when the relevant fact remains in a 128k-token window?
Key idea
Context is a limited resource, and external memory is a policy for writing, retrieval, and updating that must be evaluated.