# Agent context engineering aur long-term memory: window, versions, state

> Context engineering task aur token budget ke hisaab se instructions, tool history aur evidence assemble karta hai; long-term memory confirmation, versions aur deletion rules se cross-session preferences manage karta hai।

- URL: https://dmxsf.com/hi/wiki/applications/context-and-memory/
- [DMXSF](https://dmxsf.com/hi/about/)
- मध्यम
- अपडेट किया गया: 2026-11-21
- Tags: Agents, Tool use, Prompting

## यह पृष्ठ पूरा करने पर आप

- Ek model call ke inputs, outputs aur template costs ko source-wise todo।
- History ko complete tool groups se trim karein; causal links aur unfinished state bachayein।
- Updates, out-of-order copies aur deletions source, permission aur version se handle karein।
- Aise regression cases design karein jo assembly errors ko final-state errors se alag karein।

Context engineering tay karta hai ki model har step par kaun si info dekh sakta hai. Long-term memory tay karta hai ki kaun si authorized info cross-session save hogi, aur kab wapas milegi. Reliable agent instructions, current request, tool results aur purani memory ke sources alag record karta hai, task budget ke hisaab se pack karta hai, aur execute se pehle badalne wali business state dobara padhta hai।

## Ek model call mein kaun se states hote hain

[Berkeley Scalable AI ke context engineering aur Harness lectures](https://scalable-ai.eecs.berkeley.edu/F2026/) context ko system-assembly ka input maante hain. Meeting-room booking assistant misaal: current request, memory-retrieved preferences aur room system ki state - sabki alag zimmedari:

| Layer | Kya rakhta hai | Kis step mein |
| --- | --- | --- |
| Instructions | System rules, tool conventions, format constraints | Model samajhne wale tasks aur outputs ko constrain |
| Current task | Is-turn ki explicit demands, confirmed details | Authorized range mein agla step |
| Work history | Is-turn ke tool calls, responses, pending items | Resume par causal chain recover |
| Cross-session memory | Pehle confirmed preferences, sources, versions, expiry | Current request ke missing conditions ke defaults |
| Business state | Live room occupancy, participants, booking results | Submit se pehle verify, baad mein final-state confirm |

User pichhli baar morning chahta tha, is baar afternoon bol raha hai - is baar afternoon lo. Cache kahe ki afternoon khaali hai, phir bhi submit se pehle booking service ka latest result final hai. Assistant ko mila naya text evidence judgment support kar sakta hai, par long-term persistence usually explicit rules aur confirmation maangta hai।

## Pehle budget, phir context

Available window $W$; rendered fixed instructions + tool descriptions + is-turn request + template overhead = $F$; output ke liye reserve $R$. History, summaries aur retrieval bache budget share karte hain:

$$
B = W-F-R
$$

Ginti asli model ke tokenizer, chat template aur tool serialization format se karo. Fixed blocks already budget paar karein to pehle tool definitions, output budget ya is-turn input dekho; history phenkne se fixed overhead solve nahi hota. Debug ke liye usage source-wise record karo; replay mein template aur tokenizer versions bhi save karo।

Priority: unfinished tasks ke anchors aur recent complete interaction rounds. Tool call + uska result ko ek logical group samjho - sirf result bacha ke call params kho dena, ya sirf call bacha ke "abhi execute nahi hua" samajhna, dono kharab. Multi-tool concurrency mein results ko apne-apne call IDs se match karna chahiye. Purane groups keyword/vector-retrievable summary (original citations ke saath) mein compress ho sakte hain. Retrieval items chunte waqt dates, dedup, roles, permissions dekho; do lagbhag-same lambe snippets wahi budget kha jaate hain jo history bachane mein ja sakta tha।

## Long-term memory ke key operations: update aur delete

[Berkeley Advanced LLM Agents ke memory aur planning lecture](https://rdi.berkeley.edu/llm-agents-mooc/slides/language_agents_YuSu_Berkeley.pdf) batata hai external memory reasoning ke saath kaise chalti hai. Product ke cross-session preferences usually key, scope, source aur version ke saath hone chahiye. Same account ke same preference par pehle confirmed + authorized record chuno, phir version compare karo. Source priority external app tay karti hai; ranking scores sirf retrieval ke liye।

Typical write flow: pehle candidate fact extract, phir verify - long-term preference hai ya is-turn ki temporary condition. Persist karte waqt stable record key + version; repeated sync same operation ID se idempotent. Delete par purani copies invalidate; append-only log mein higher-version deletion marker save karke, retention policy se original values aur derived indexes clean karein. Warna naya record delete karne ke baad retrieval purani value phir se dikha degi. Tools ke real results hamesha live read hote hain - memory records unhe override nahi karte।

Ek practical read path: pehle user/account scope validate, phir latest confirmed version padho, source aur validity context mein do. Memory deleted/expired ho to is-turn input par ya user se poochho. Write path mein bhi alag validation - taaki temporary option chupke se permanent preference na ban jaye।

### Summary rebuild mein kaun se invariants bachane hain

Summary ko derived data samjho - source message range aur version ke saath mark karo. User preference delete kare to purani summaries aur semantic index bhi invalidate. Warna main DB khaali lauta raha hoga, model derived text se purani preference wapas nikaal lega. Persisted session restore karte waqt pehle same snapshot par, phir naye events append. Do writes same purane version par base hon to storage layer conflict detect kare - baad wala write confirmed naye fact ko chupke se overwrite na kare।

Summary mein task continue karne layak fields rakhein: unfinished calls ke IDs, kiye gaye promises, user ke explicit limits. Complete reads ko conclusion + source mein summarize; unfinished writes ko traceable state machine chahiye. Yeh bhi regression ka hissa hai: budget different templates, tool lists ya tokenizer versions ke baad badla ya nahi।

## Experiment: full tool rounds aur latest preference

Teen logical groups ke costs self-written token counts hain. Experiment window-trimming ko back-to-front continuous retention se mimic karta hai, aur version rules ko out-of-order copied confirmed records se verify karta hai. Sirf standard library; Apple M2 Max par Python 3.12.14. Yahan ki strategy mechanism explain karti hai; real systems cross-turn retrieval aur summary ke liye jagah chhod sakte hain।

```python
from __future__ import annotations

from collections.abc import Iterable
from dataclasses import dataclass

@dataclass(frozen=True)
class Record:
    version: int
    value: str | None

def resolve(current: str | None, confirmed: Iterable[Record]) -> str | None:
    """Prefer the current value or the latest trusted record."""
    if current is not None:
        return current
    latest = max(confirmed, key=lambda record: record.version, default=None)
    return latest.value if latest is not None else None

def recent_groups(costs: list[int], budget: int) -> list[int]:
    """Take the latest contiguous whole groups within the available budget."""
    if budget < 0 or any(cost <= 0 for cost in costs):
        raise ValueError("budget must be nonnegative and costs positive")
    start = len(costs)
    while start and costs[start - 1] <= budget:
        start -= 1
        budget -= costs[start]
    return list(range(start, len(costs)))

costs = [18, 22, 8]
for budget, expected in [(25, [2]), (30, [1, 2])]:
    kept = recent_groups(costs, budget)
    assert kept == expected
    print("kept rounds:", budget, kept)

records = [Record(3, None), Record(1, "morning"), Record(2, "evening")]
current = resolve("afternoon", records)
deleted = resolve(None, records)
assert current == "afternoon" and deleted is None
assert resolve(None, records[1:]) == "evening"
print("this-turn override:", current)
print("read after delete:", deleted or "empty")
```

```text
kept rounds: 25 [2]
kept rounds: 30 [1, 2]
this-turn override: afternoon
read after delete: empty
```

Note: numbers original run se hain; sample values Hindi/Latin transliteration mein badle gaye।

Neeche widget window budget aur whole-group trimming ko khud drag karne layak banata hai: W, F, R adjust karke history budget aur bachne wale tool groups dekhein, phir memory read rule try karein(is turn ki jeet; deletion marker wapas nahi aate). 

Chhote budget par recent short round ke baad pichhla tool group poora fit nahi hota - sirf short round bachta hai. Budget badha to dono groups saath. Out-of-order aayi memory bhi highest version leti hai; highest version deletion marker ho to purani preference wapas nahi aati. Asli assembler ko is-turn actions ke unfinished states bhi explicitly track karne chahiye - taaki must-keep calls ko discardable history mein na daal dein।

## Replay se pata kaise chalta hai: retrieval galat tha ya merge

Fixed initial DB snapshots se shuru karke, same tasks par purana vs naya assembler compare karein. Pehle context test, phir poora task. Har assembly par selected/dropped message IDs, preference source + version, budget aur model output record - failures chhote scope mein reproduce hon।

| Test scenario | Expected behaviour | Signal |
| --- | --- | --- |
| Is-turn explicitly purani preference override kare | Is-turn params use; koi long-term write nahi | Chuna value aur uska source |
| Copied records ka order shuffled | Highest confirmed version padho | Retrieved version aur last write |
| Preference delete ho gayi | App default ya user se poochho | Delete ke baad stale hits ki ginti |
| Tool group budget se exactly paar | Poora rakho ya poora hatao | Orphan calls aur results ki ginti |
| Do accounts ke same key names | Sirf current account scope retrieve | Cross-scope hits |
| External state plan ke baad badla | Execute se pehle dobara padho aur judge | Final-state success aur duplicate writes |

Retrieval hit rate "target evidence selected hua?" ka jawab deta hai; final-state success rate "system ne sahi use aur execute kiya?" ka. Same budget par ablation - jaise sirf snippet selector badlo - model aur memory strategy ek saath na badlein. Ek failure kai stages mein lag raha ho to pehle fixed sahi evidence ke saath replay karo, phir dekho ab bhi fail hota hai।

## Summary aur exercises

- Context budget asli-rendered token counts se allocate; trim unit = complete tool group।
- Long-term preferences scoped + versioned confirmed records mein; delete/update par purani copies invalidate।
- Pehle assembly aur merge test, phir final-state checks se poora app।

### Quick self-test

**1. Budget kis representation par ginna chahiye?**

- [x] Rendered model input aur reserved output tokens par।
- [ ] Raw strings ke characters par।

> Templates, serialization aur tokenization actual cost badal dete hain।

**2. Successfully-executed tool group kaise trim karein?**

- [ ] Sirf call rakho, result chhodo।
- [x] Call ID se pair karo; poora group rakho ya poora hatao।

> Pairing tool-state ki galat samajh se bachati hai।

**3. Highest version deletion marker ho to kya?**

- [x] Preference invalidate karo; params is-turn input ya default se lo।
- [ ] Agle purane version par gir jaao।

> Rollback deleted preference ko wapas zinda kar degi।

**4. Current request afternoon select karti hai, memory morning kehti hai - kaise test karein?**

- [ ] Agle baar bhi afternoon default ho jaaye aisa karo।
- [x] Check karo sirf is baar afternoon use hua, aur koi long-term write nahi hua।

> Current condition is-turn params override kar sakti hai; persistent state banane ki zaroorat nahi।

### Ek cross-session regression case design karein

Pichhle turn mein assistant ne morning meeting room book ki. Is baar user afternoon chunta hai, par afternoon room execute se pehle book ho jaata hai. Fixed starting state, memory-update ki zaroorat hai ya nahi, aur do final-state assertions likhein।

<details>
<summary>Reference answers</summary>

Save: pichhle turn ki morning preference, is-turn ki afternoon demand, aur booking system ke pehle-baad snapshots. Current condition purani preference override karti hai - naya long-term preference nahi likha jaata. Execute se pehle re-query; occupancy milne par user se alternative poochho ya ruk jao. Final-state assertions: koi occupancy conflict nahi, aur user authorization ke bina morning par shift nahi hua।

</details>

## Aage padhein

- [Berkeley Scalable AI Fall 2026](https://scalable-ai.eecs.berkeley.edu/F2026/) ke context engineering aur Harness design lectures।
- [Yu Su ke memory aur planning lecture notes](https://rdi.berkeley.edu/llm-agents-mooc/slides/language_agents_YuSu_Berkeley.pdf)।
- [Agents aur tool calling](https://dmxsf.com/hi/wiki/applications/agents-and-tool-calling/), [RAG](https://dmxsf.com/hi/wiki/applications/rag/) aur [agent evaluation](https://dmxsf.com/hi/wiki/applications/agent-evaluation/)।

## सहायक कोड

[Agent context and memory: budget and precedence](https://github.com/dmxsf/dmxsf/tree/main/labs/applications/context-and-memory): Keep tool groups whole and verify overrides and deletion on versioned records.

- सहायक रिपॉज़िटरी में चलाएँ (--quick से तेज़ जाँच): `uv run dmxsf run applications/context-and-memory`
- [प्रयोग स्क्रिप्ट देखें](https://github.com/dmxsf/dmxsf/blob/main/labs/applications/context-and-memory/run.py)
- [प्रयोग विवरण](https://github.com/dmxsf/dmxsf/blob/main/labs/applications/context-and-memory/README.en.md)
- [`context_memory.py`](https://github.com/dmxsf/dmxsf/blob/main/src/dmxsf/applications/context_memory.py)
- [सूची में देखें](https://dmxsf.com/hi/code/#context-and-memory)

## अक्सर पूछे जाने वाले सवाल

### Context window = long-term memory?

Nahi. Context window ek model call ka input + output rakhta hai; long-term memory application store karti hai aur zaroorat par window mein retrieve hoti hai।

### Purani preference aur is-turn ki demand conflict karein to kaunsa?

Explicit is-turn demand jeet-ti hai. Temporary conditions tabhi long-term preference banti hain jab business validation aur clear confirmation ho।

### Tool call aur uska result saath trim kyun?

Poora call + corresponding result causal chain maintain karta hai. Aadha chhodne par model params kho deta hai, ya samajhta hai call abhi execute nahi hui।
