Step 13 of 16
Apply context budgets, token guards, deduplication, safe caching, and repeatable performance tests.
เปิด trace หา stage ที่ช้า ลด duplicate context และใช้ cache ที่ไม่ข้าม tenant หรือ permission ครับ
Level: Advanced
RAG ช้ามักเกิดก่อน model เริ่มตอบครับ เปิด trace แยกเวลา query rewrite, embedding, vector search, rerank และ generation แล้วแก้ stage ที่ใช้เวลาสูง
กำหนด latency, token และ cost budgets พร้อม load test ที่จับ regression ของ agent กับ retrieval pipeline ครับ
สร้าง budget ก่อนประกอบ prompt:
record ContextBudget(
int MaxChunks,
int MaxCharactersPerChunk,
int MaxTotalCharacters);
static IReadOnlyList<string> ApplyBudget(
IEnumerable<string> chunks,
ContextBudget budget)
{
var selected = new List<string>();
var used = 0;
foreach (var chunk in chunks.Take(budget.MaxChunks))
{
var value = chunk[..Math.Min(chunk.Length, budget.MaxCharactersPerChunk)];
if (used + value.Length > budget.MaxTotalCharacters) break;
selected.Add(value);
used += value.Length;
}
return selected;
}
Character count เป็น guard เบื้องต้นครับ Production ควรนับ token ด้วย tokenizer ที่เข้ากับ embedding และ generation model เพิ่ม hard rejection ก่อน embedding กับ defensive truncation ที่ boundary
Cache ต้องมี key ที่รวม tenant, permissions, index version, model และ retrieval settings ครับ ห้ามคืน cached result ข้าม authorization scope ตั้ง TTL ตาม freshness ของข้อมูล และบันทึก cache hit แยกจาก vector-search hit
สร้าง query ชุดเดียวกับ quality evaluation แล้ววัด cold กับ warm run เก็บ P50, P95, retrieved characters, prompt tokens และ completion tokens ตั้ง performance budget ใน CI หรือ scheduled test เพื่อจับ regression ก่อนผู้ใช้พบ
เพิ่ม concurrency test ที่จำลอง session หลาย tenants พร้อมกันครับ วัด provider throttling, vector-store pool usage, queue depth และ retry amplification แยกจาก single-user latency
สร้าง report ที่แยก time-to-first-token, total generation, retrieval, tool และ queue time ตรวจว่า cancellation หยุด downstream calls และ cache invalidation ทำงานหลัง index alias เปลี่ยน
ตั้ง hard ceilings สำหรับ prompt tokens, completion tokens, retrieved bytes, tool calls ต่อ run, retries, total deadline และ estimated cost เมื่อเกิน budget ให้คืน partial-safe response หรือ explicit error แทนการปล่อย request ค้าง
ส่ง load-test scenario, budget configuration, dashboard queries, cache isolation tests และ before/after performance report