Step 6 of 16
Use AIContextProvider for scoped memory, then reduce and compact growing conversation context.
แยก session history จาก long-term memory และคุม context growth ก่อน conversation เริ่มยาวครับ
Level: Advanced
Session history ช่วยคุยต่อ ส่วน memory เลือกข้อมูลที่ควรใช้ข้าม session ครับ ใน Agent Framework คุณสร้าง AIContextProvider เพื่อให้ context ก่อน model run และเก็บข้อมูลหลัง interaction
เพิ่ม memory ที่มี user consent, tenant scope, retention และ delete path พร้อมคุม history ไม่ให้โตแบบไร้ขอบเขตครับ
ตัวอย่าง Knowledge Support Agent อาจจำ language preference และ team name แต่ไม่ควรจำ access token, password หรือข้อมูลที่ user ไม่อนุญาต ข้อมูลทุกชิ้นต้องมี owner, retention และ delete path
using Microsoft.Agents.AI;
sealed class UserPreferenceContext : AIContextProvider
{
protected override ValueTask<AIContext> ProvideAIContextAsync(
InvokingContext context,
CancellationToken cancellationToken = default)
{
return ValueTask.FromResult(new AIContext
{
Instructions = "The user prefers concise C# examples."
});
}
protected override ValueTask StoreAIContextAsync(
InvokedContext context,
CancellationToken cancellationToken = default)
=> ValueTask.CompletedTask;
}
ลงทะเบียนผ่าน ChatClientAgentOptions.AIContextProviders ครับ Provider ที่ใช้ production ควรอ่าน state ด้วย user identity จาก trusted request context ไม่ควรรับ user ID จาก prompt
Conversation ที่ยาวขึ้นทำให้ latency และ token cost เพิ่ม รวมทั้งผล retrieval เก่ามีโอกาสปะปน ใช้แนวทางต่อไปนี้:
Microsoft samples มี chat reduction และ compaction pipeline สำหรับกรณีนี้ครับ หลัง compaction ต้องทดสอบว่า system instructions, pending approval และ citation identifiers ยังอยู่ครบ
สร้างสอง users และสอง sessions แล้วพิสูจน์ว่า memory ไม่รั่วข้ามขอบเขต ทดสอบ serialize/deserialize, expiry, delete request และ concurrent update ด้วย
สร้าง test matrix สำหรับ blank memory, saved preference, revoked consent, expired data และ concurrent sessions วัด prompt tokens ก่อนกับหลังเปิด memory เพื่อให้เห็นต้นทุนที่เพิ่มครับ
Memory ทุก field ต้องมี purpose, source, owner, created time, expiry และ deletion behavior อย่าใช้ model output เป็น durable fact ทันที ให้ validate หรือขอ user confirmation ก่อน persist
ส่ง context provider, memory store, consent flow, deletion test, isolation test และ token-growth report