8 Application engineering 6 / 8
  1. अध्याय विषय-सूची
  2. Pehla Agent
  3. Prompt engineering
  4. Structured output aur function calling
  5. RAG system banane ka hands-on guide
  6. Agents aur tool calling
  7. Agent context engineering aur long-term memory
  8. Agent evaluation
  9. MCP aur tool ecosystem
सभी अध्याय →

अध्याय 8 · Application engineering 8.6

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।

मध्यम पढ़ने का समय: 10 मिनट अपडेट किया गया सहायक कोड ↓

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

  • 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।
इस पृष्ठ पर
  1. Ek model call mein kaun se states hote hain
  2. Pehle budget, phir context
  3. Long-term memory ke key operations: update aur delete
  4. Summary rebuild mein kaun se invariants bachane hain
  5. Experiment: full tool rounds aur latest preference
  6. Replay se pata kaise chalta hai: retrieval galat tha ya merge
  7. Summary aur exercises
  8. Quick self-test
  9. Ek cross-session regression case design karein
  10. Aage padhein
  11. अक्सर पूछे जाने वाले सवाल

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 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:

LayerKya rakhta haiKis step mein
InstructionsSystem rules, tool conventions, format constraintsModel samajhne wale tasks aur outputs ko constrain
Current taskIs-turn ki explicit demands, confirmed detailsAuthorized range mein agla step
Work historyIs-turn ke tool calls, responses, pending itemsResume par causal chain recover
Cross-session memoryPehle confirmed preferences, sources, versions, expiryCurrent request ke missing conditions ke defaults
Business stateLive room occupancy, participants, booking resultsSubmit 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 WW; rendered fixed instructions + tool descriptions + is-turn request + template overhead = FF; output ke liye reserve RR. History, summaries aur retrieval bache budget share karte hain:

B=W−F−RB = 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 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।

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")
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 scenarioExpected behaviourSignal
Is-turn explicitly purani preference override kareIs-turn params use; koi long-term write nahiChuna value aur uska source
Copied records ka order shuffledHighest confirmed version padhoRetrieved version aur last write
Preference delete ho gayiApp default ya user se poochhoDelete ke baad stale hits ki ginti
Tool group budget se exactly paarPoora rakho ya poora hataoOrphan calls aur results ki ginti
Do accounts ke same key namesSirf current account scope retrieveCross-scope hits
External state plan ke baad badlaExecute se pehle dobara padho aur judgeFinal-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?

  • 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।
  • 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?

  • 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।
  • 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।

Reference answers

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।

Aage padhein

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

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।