Step 3 of 16
Continue multi-turn conversations and safely serialize, restore, scope, and version session state.
เพิ่ม AgentSession หลัง agent รันได้ครับ จากนั้นค่อย persist และแยกขอบเขตของแต่ละ user
Level: Intermediate
AIAgent กำหนด behavior ส่วน AgentSession เก็บ state ของ conversation ครับ ถ้าไม่ส่ง session แต่ละ call จะเริ่ม context ใหม่ จึงควรสร้าง session ต่อหนึ่ง conversation และผูกกับ user หรือ tenant ที่ถูกต้อง
สร้าง conversation API ที่ตรวจ ownership ก่อนโหลด session และ resume ได้หลัง process restart ครับ
AgentSession session = await agent.CreateSessionAsync();
Console.WriteLine(await agent.RunAsync(
"My service is called Payroll API.", session));
Console.WriteLine(await agent.RunAsync(
"What service did I mention?", session));
ห้ามแชร์ session เดียวให้ผู้ใช้หลายคนครับ ขอบเขตที่ปลอดภัยคือ tenantId + userId + conversationId และ authorization ต้องตรวจทุกครั้งก่อนโหลด session
Agent Framework รองรับการ serialize session เพื่อพัก conversation แล้วกลับมาทำต่อ:
using System.Text.Json;
JsonElement state = await agent.SerializeSessionAsync(session);
await File.WriteAllTextAsync(
"session.json",
JsonSerializer.Serialize(state));
var saved = JsonSerializer.Deserialize<JsonElement>(
await File.ReadAllTextAsync("session.json"));
AgentSession restored = await agent.DeserializeSessionAsync(saved);
Console.WriteLine(await agent.RunAsync("Continue the checklist.", restored));
File เหมาะกับการเรียน แต่ production ควรใช้ durable store พร้อม encryption, expiry และ optimistic concurrency ครับ เก็บ provider name, framework version และ schema version ข้าง session state ด้วย เพื่อรองรับ migration เมื่อ package เปลี่ยน
สร้าง application contract แยกจาก storage implementation:
interface IAgentSessionStore
{
Task<StoredSession?> GetAsync(
string tenantId, string userId, Guid conversationId,
CancellationToken cancellationToken);
Task SaveAsync(
StoredSession session, string expectedVersion,
CancellationToken cancellationToken);
}
บันทึก state หลัง agent run สำเร็จ และก่อนคืน response ให้ client หากมี approval request ให้ persist ทั้ง session และ pending action ก่อนรอ user เพื่อลดโอกาสที่ process restart แล้วข้อมูลหาย
แยก conversation history ออกจาก long-term memory:
ทดสอบ create, resume, expired session และ concurrent writes สร้างสอง tenants ที่ใช้ conversation ID เหมือนกัน แล้วพิสูจน์ว่าอ่านข้าม tenant ไม่ได้ครับ Restart API ระหว่างสอง turns เพื่อยืนยันว่าระบบไม่ได้พึ่ง in-memory state
กำหนด encryption at rest, TTL, deletion request, maximum history size และ migration policy ห้ามใช้ session ID เป็น authorization proof เพียงอย่างเดียว
ส่ง session-store interface, persistent adapter, ownership tests, concurrency test และ schema-version note
บทถัดไปจะต่อ agent เข้ากับ application code ผ่าน function tools ครับ