أهداف التعلم
أنظمة LLM تحتاج مراقبة تتجاوز HTTP status code. هتتعلم تتبع request عبر retrieval و tools و model providers، قياس الجودة والتكلفة والـ latency، وإطلاق نسخة جديدة بأمان مع rollback. افترض معرفة API و RAG و logging basics.
Distributed Tracing للـ AI Request
اعمل trace واحد للطلب مع spans فرعية: authentication، retrieval، prompt construction، model call، tool call، validation، response. اربطها بـ request_id و trace_id، وسجل model/prompt/retriever versions. span لازم يوضح duration و status و safe attributes من غير أسرار أو نصوص حساسة.
في agent workflow، trace الأدوات وترتيبها وعدد retries وسبب التوقف. من غير trace قد ترى أن الرد استغرق 12 ثانية لكن لا تعرف هل السبب vector DB أو provider queue أو tool timeout.
Metrics: Quality و Latency و Cost
قسّم latency إلى time-to-first-token و total latency، وراقب p50/p95/p99 لا المتوسط فقط. قِس input/output tokens، تكلفة كل provider/model، cache hit rate، retry rate، timeout rate، refusal rate، و tool success. اربط المقاييس بنوع المهمة والـ tenant مع cardinality منضبطة.
الجودة تشمل groundedness أو citation correctness أو task success أو structured-output validity حسب الاستخدام. لا تختزلها في thumbs-up. ابنِ evaluation set ممثلًا مع مراجعة بشرية، واستخدم automated graders كإشارة مساعدة بعد معايرتها، لا كحقيقة مطلقة.
Versioning للـ Prompt و Dataset و Model
سجّل prompt template version، model/provider version إن توفر، retrieval/index version، tool schema version، evaluation dataset version، و application commit. لا تضع prompt أو user content الحساس في tags العامة. التغييرات الصغيرة في system prompt قد تغير behavior؛ تعامل معها كإصدار يحتاج تقييمًا.
أنشئ regression suite تغطي happy paths و edge cases و prompt injection و tool errors و structured outputs. استخدم fixed evaluation inputs، وسجّل توزيع النتائج بدل رقم متوسط فقط.
Canary و Shadow و Rollback
Shadow mode يرسل نسخة جديدة بالتوازي دون أن تتحكم في الرد للمستخدم، ويقارن النتائج والتكلفة وال latency. Canary يوجّه نسبة محدودة من traffic للنسخة الجديدة وفق guardrails. لا توسع النسبة إلا إذا ظلت الجودة والـ SLOs ضمن الحدود.
Rollback يجب أن يعيد prompt/model/config/index المتوافقين، وليس container image وحده. حدد مسبقًا شروط الإيقاف مثل ارتفاع timeout أو انخفاض task success أو زيادة cost per successful task. احذر أن traffic الصغير لا يكشف كل الشرائح النادرة.
Shadow و Canary rollouts لتغييرات الـ AI
Shadow: النسخة الجديدة بتستقبل نفس الطلبات بالتوازي، ردها ما بيوصلش للمستخدم، وبنقارن (جودة بـ judge، latency، تكلفة، معدل رفض). مفيد جدًا للـ AI لأن «الجودة» محتاجة مقارنة على traffic حقيقي. التكلفة: بتدفع مرتين على العينة دي — خليها sample (مثلًا 5–10%) وما تعملش shadow لأي tool له أثر (shadow agent ما ينفعش يبعت إيميل!).
Canary: نسبة صغيرة من المستخدمين بتشوف النسخة الجديدة فعلًا. التقسيم يكون sticky (نفس المستخدم يفضل على نفس النسخة) بـ hash ثابت، عشان المحادثة ما تتنقلش بين نسخ.
public sealed class AiReleaseRouter(IOptionsMonitor<AiRolloutOptions> opts)
{
// Deterministic, sticky bucket in [0, 10000): same user -> same version for the whole rollout.
private static int Bucket(string key)
{
Span<byte> h = stackalloc byte[32];
SHA256.HashData(Encoding.UTF8.GetBytes(key), h);
return (int)(BinaryPrimitives.ReadUInt32LittleEndian(h) % 10_000);
}
public AiRelease Choose(string tenantId, string userId, string feature)
{
var o = opts.CurrentValue.For(feature);
if (o.KillSwitchToStable) return o.Stable;
if (o.TenantOverrides.TryGetValue(tenantId, out var pinned)) return pinned; // enterprise pins
var b = Bucket($"{feature}:{o.Candidate.Version}:{tenantId}:{userId}");
return b < o.CanaryBasisPoints ? o.Candidate : o.Stable; // e.g. 500 = 5%
}
public bool ShouldShadow(string tenantId, string userId, string feature)
{
var o = opts.CurrentValue.For(feature);
return o.ShadowBasisPoints > 0 && Bucket($"shadow:{feature}:{tenantId}:{userId}") < o.ShadowBasisPoints;
}
}قرار الترقية مش «الـ dashboard شكله كويس». اكتب الـ guardrail metrics قبل البدء: معدل الأخطاء، p95، تكلفة/request، thumbs-down rate، escalation rate، و score الـ online judge على عينة. ولو أي واحد عدّى الحد، rollback تلقائي (الـ kill switch يرجّع للـ stable). وخلي فترة كل مرحلة كفاية تغطي دورة استخدام (مثلًا يوم عمل كامل) قبل ما توسّع من 5% لـ 25% لـ 100%.
Drift و Quality Degradation
راقب تغير query distribution، language mix، token lengths، retrieval hit rate، empty context، model refusal، و human feedback. تغير input distribution لا يعني تلقائيًا أن النموذج أصبح سيئًا، لكنه trigger للتحقيق. قارن offline evaluation على نافذة زمنية مع online outcomes.
عندما تتوفر labels متأخرة، اربطها بال prediction/request IDs لتقييم الأداء الفعلي. لا تستخدم user feedback وحده دون تحليل selection bias؛ من يرسل feedback قد لا يمثل كل المستخدمين.
Resilience و Fallbacks
ضع timeout لكل dependency، retry محدودًا مع exponential backoff و jitter، circuit breaker عند فشل provider، وحدود concurrency و queue. لا تعمل retries غير محدودة لطلبات مكلفة أو غير idempotent. استخدم idempotency key عند tool actions التي تغير state.
Fallback قد يكون نموذجًا أصغر أو search-only أو رسالة توضح عدم التوفر. لا تجعل fallback يخفض security controls أو authorization. إذا تعذر التحقق من structured output، ارفضه أو اطلب إصلاحًا مضبوطًا بدل تمريره إلى business logic.
Privacy و Security في Telemetry
عامل prompts و retrieved documents و tool arguments كبيانات قد تحتوي أسرارًا أو PII. استخدم redaction قبل logging، access control للسجلات، retention محدد، encryption، و sampling. لا تسجل API keys أو access tokens أو raw database rows.
قيّم prompt injection و data exfiltration و unsafe tool invocation. trace مفيد للتحقيق لكنه يصبح مخزنًا حساسًا؛ صمم سياسة الاحتفاظ والصلاحيات بنفس جدية قاعدة البيانات.
SLOs و Incident Runbooks
اكتب SLO لكل use case: availability، latency، task success، أو freshness. Error budget يساعد على موازنة سرعة الإطلاق مع الاستقرار. لا تختَر SLO عشوائيًا؛ استخدم توقعات المنتج وقدرة النظام وقياسات baseline.
Runbook يحدد symptom، dashboard، خطوات التشخيص، mitigation، escalation، rollback، وطريقة توثيق incident. بعد الحادث اعمل blameless postmortem يركز على أسباب النظام وإجراءات منع التكرار.
مشروع تشغيل متكامل
أضف observability إلى RAG assistant: trace كامل، metrics للتكلفة وال latency، evaluation set، prompt versioning، canary configuration، privacy redaction، و runbook. نفّذ fault injection: provider timeout، vector store outage، malformed JSON، prompt injection، وارتفاع token usage.
- عرّف 3 SLOs و alert thresholds من baseline.
- قارن إصدار prompt جديدًا في shadow mode.
- اكتب شروط rollback واختبرها.
- تحقق أن logs لا تحتوي secrets أو PII خامًا.
- اكتب incident report لسيناريو provider outage.
هل HTTP 200 يعني أن إجابة AI صحيحة؟
هل يمكن عمل retry لكل tool call؟
LLM Tracing بإيدك: Spans، تكلفة لكل Tenant، و SLO
request واحد لتطبيق RAG = retrieval + rerank + نداء موديل (أو أكتر) + tools. لما المستخدم يقول «الرد اتأخر» أو الفاتورة تتضاعف، الـ logs العادية مش بتجاوب: محتاج trace بيربط كل الخطوات دي بـ id واحد، وكل خطوة (span) شايلة مدتها والـ tokens بتاعتها ونسخة الـ prompt والموديل. الكود ده بيولّد traces لـ 500 request وبيطلّع منها الإجابات اللي بتحتاجها فعلًا.
import random, statistics
from collections import defaultdict
random.seed(4)
PRICE = {"small": (0.15, 0.60), "large": (2.50, 10.00)} # ILLUSTRATIVE $ per 1M tokens (input, output)
def make_trace(i):
tenant = random.choices(["acme", "globex", "initech"], weights=[6, 3, 1])[0]
prompt_version = "v7" if i < 300 else "v8" # v8 was released after request 300
model = "large" if tenant == "initech" or random.random() < 0.15 else "small"
ctx_tokens = int(random.gauss(2500, 600)) + (1800 if prompt_version == "v8" else 0) # v8 stuffs more context
out_tokens = int(random.gauss(220, 60))
spans = [
{"name": "retrieval", "ms": random.gauss(80, 20)},
{"name": "rerank", "ms": random.gauss(120, 30)},
{"name": "llm", "ms": 300 + out_tokens * (9 if model == "large" else 4) + random.gauss(0, 150),
"model": model, "input_tokens": max(ctx_tokens, 200), "output_tokens": max(out_tokens, 20)},
]
if random.random() < 0.04: # 4%: the vector store is slow
spans[0]["ms"] += 2500
grounded = random.random() < (0.93 if prompt_version == "v7" else 0.95)
return {"trace_id": f"t{i:04d}", "tenant": tenant, "prompt_version": prompt_version, "spans": spans, "grounded": grounded}
traces = [make_trace(i) for i in range(500)]
def total_ms(t): return sum(s["ms"] for s in t["spans"])
def cost(t):
s = t["spans"][2]; pin, pout = PRICE[s["model"]]
return (s["input_tokens"] * pin + s["output_tokens"] * pout) / 1e6
def pct(values, q): return sorted(values)[int(len(values) * q)]
# 1) where does the time go?
print("latency by stage (ms):")
for name in ("retrieval", "rerank", "llm"):
v = [s["ms"] for t in traces for s in t["spans"] if s["name"] == name]
print(f" {name:<10} p50={pct(v, .5):7.0f} p95={pct(v, .95):7.0f}")
all_ms = [total_ms(t) for t in traces]
print(f" {'end-to-end':<10} p50={pct(all_ms, .5):7.0f} p95={pct(all_ms, .95):7.0f}")
# 2) who is the slow tail? attribute p95+ requests to their dominant span
slow = [t for t in traces if total_ms(t) >= pct(all_ms, .95)]
blame = defaultdict(int)
for t in slow:
blame[max(t["spans"], key=lambda s: s["ms"])["name"]] += 1
print(f"\nslowest 5% of requests — dominant stage: {dict(blame)}")
# 3) who is spending the money?
by_tenant = defaultdict(float)
for t in traces: by_tenant[t["tenant"]] += cost(t)
total = sum(by_tenant.values())
print("\ncost by tenant:")
for tenant, c in sorted(by_tenant.items(), key=lambda kv: -kv[1]):
n = sum(1 for t in traces if t["tenant"] == tenant)
print(f" {tenant:<8} requests={n:>3} ({n / len(traces):4.0%}) cost=${c:.4f} ({c / total:4.0%}) per request=${c / n:.5f}")
# 4) did the prompt release change anything?
print("\nby prompt version:")
for v in ("v7", "v8"):
g = [t for t in traces if t["prompt_version"] == v]
print(f" {v} n={len(g)} grounded={sum(t['grounded'] for t in g) / len(g):.1%} "
f"avg input tokens={statistics.mean(t['spans'][2]['input_tokens'] for t in g):6.0f} "
f"avg cost=${statistics.mean(cost(t) for t in g):.5f} p95 latency={pct([total_ms(t) for t in g], .95):.0f}ms")
# 5) SLO: 95% of requests under 2.5 s
SLO_MS, TARGET = 2500, 0.95
good = sum(ms <= SLO_MS for ms in all_ms) / len(all_ms)
budget = 1 - TARGET
print(f"\nSLO: {TARGET:.0%} of requests under {SLO_MS} ms -> actual {good:.1%}; error budget used: {(1 - good) / budget:.0%}")latency by stage (ms):
retrieval p50= 79 p95= 129
rerank p50= 119 p95= 170
llm p50= 1277 p95= 2564
end-to-end p50= 1487 p95= 3137
slowest 5% of requests — dominant stage: {'retrieval': 17, 'llm': 8}
cost by tenant:
acme requests=305 ( 61%) cost=$0.5845 ( 44%) per request=$0.00192
initech requests= 45 ( 9%) cost=$0.4631 ( 35%) per request=$0.01029
globex requests=150 ( 30%) cost=$0.2803 ( 21%) per request=$0.00187
by prompt version:
v7 n=300 grounded=93.3% avg input tokens= 2506 avg cost=$0.00196 p95 latency=3400ms
v8 n=200 grounded=96.0% avg input tokens= 4292 avg cost=$0.00370 p95 latency=2904ms
SLO: 95% of requests under 2500 ms -> actual 87.4%; error budget used: 252%1 و2 — الوقت: الـ LLM هو أكبر جزء في الحالة العادية، لكن بص على الـ slow tail: جزء كبير من أبطأ 5% السبب فيهم الـ retrieval مش الموديل. من غير spans كنت هتتهم الموديل وتغيّره، والمشكلة في الـ vector store.
3 — الفلوس: tenant بنسبة صغيرة من الطلبات مسؤول عن نصيب أكبر بكتير من التكلفة، لأنه دايمًا على الموديل الكبير. دي المعلومة اللي بتبني عليها pricing و quotas — وبتطلع بس لو كل span عليه tenant و model و tokens.
4 — الـ release: الـ prompt v8 حسّن الـ groundedness حوالي 3 نقط، وفي المقابل الـ input tokens زادت بأكتر من 70% والتكلفة لكل request قربت تتضاعف. هل يستاهل؟ ده قرار product — لكن من غير prompt_version على الـ trace مكنتش هتعرف إن فيه trade-off أصلًا. (وفرق بالحجم ده على 200–300 عيّنة جوه هامش الضوضاء — لازم eval set أكبر قبل ما تصدّقه.)
5 — الـ SLO: الـ error budget بيحوّل «النظام بطيء شوية» لرقم: استهلكت قد إيه من المسموح. هنا الاستهلاك 252% — يعني الـ SLO مكسور بوضوح، والقاعدة المتفق عليها ساعتها: توقف الـ releases وتشتغل على الأداء (وأول مرشح هو ذيل الـ retrieval اللي ظهر في رقم 2).
نفس الفكرة بـ OpenTelemetry في .NET
لم يتم عمل compile لهذا الكود. ActivitySource هو API الـ tracing القياسي في .NET، و UseOpenTelemetry() من Microsoft.Extensions.AI بيسجّل spans ومقاييس الـ tokens حسب OpenTelemetry GenAI semantic conventions — أسماء الـ attributes في الـ conventions دي لسه بتتطور، فراجع النسخة اللي عندك.
public sealed class AnswerService(IChatClient chat, IRetriever retriever, ITenantContext tenant)
{
private static readonly ActivitySource Source = new("MyApp.Rag");
public async Task<string> AnswerAsync(string question, CancellationToken ct)
{
using var root = Source.StartActivity("rag.answer");
root?.SetTag("tenant.id", tenant.TenantId); // low-cardinality business dimensions
root?.SetTag("prompt.version", PromptCatalog.AnswerV8.Version);
IReadOnlyList<Chunk> chunks;
using (var span = Source.StartActivity("rag.retrieve"))
{
chunks = await retriever.SearchAsync(question, top: 5, ct);
span?.SetTag("rag.chunks.returned", chunks.Count);
span?.SetTag("rag.top_score", chunks.Count > 0 ? chunks[0].Score : 0);
}
// The chat span (model, input/output tokens, duration) is emitted by .UseOpenTelemetry() on the client.
ChatResponse response = await chat.GetResponseAsync(PromptCatalog.AnswerV8.Build(question, chunks), cancellationToken: ct);
root?.SetTag("rag.answer.abstained", response.Text.Contains("I don't know"));
return response.Text;
}
}
// Registration: builder.Services.AddOpenTelemetry().WithTracing(t => t.AddSource("MyApp.Rag").AddOtlpExporter());نص الـ prompts والردود فيه بيانات مستخدمين. ما تسجّلوش في الـ spans افتراضيًا: سجّل الأحجام والنسخ والـ ids، وفعّل تسجيل المحتوى في بيئات محددة بس، بـ redaction و retention قصير وصلاحيات وصول. تسريب من نظام الـ observability هو تسريب بيانات عادي.
الـ p95 latency زاد 40% بعد release. عندك traces بـ spans. أول حاجة تعملها؟
خريطة تغطية الأهداف
الأهداف العشرة المدرجة في خريطة المنهج تم تناولها عبر الأقسام والتمارين أعلاه. التغطية تعني وجود شرح أو نشاط تعليمي، ولا تعني الإتقان أو الاعتماد أو الجاهزية الإنتاجية دون تنفيذ المشروع والاختبارات.
OpenTelemetry للـ LLM calls: spans و attributes وإيه اللي يتسجل
request واحد لـ «اسأل المستندات» بيعدّي على: API ← auth ← retrieval (embedding + DB) ← rerank ← LLM call (ممكن أكتر من واحد) ← tools ← output guard. لما الـ p95 يبقى 9 ثواني أو التكلفة تتضاعف، السؤال الوحيد المفيد: أنهي span؟ ده اللي الـ distributed tracing بيجاوبه.
OpenTelemetry GenAI semantic conventions: OTel عنده conventions لـ AI calls (أسماء زي gen_ai.operation.name، gen_ai.request.model، gen_ai.response.model، gen_ai.usage.input_tokens، gen_ai.usage.output_tokens). الـ conventions دي لسه بتتطور (status «development» وقت الكتابة) فالأسماء ممكن تتغير — ثبّت نسخة وراجع الـ spec قبل ما تبني dashboards عليها. الفايدة إن أدوات زي Azure Monitor/Application Insights وأدوات LLM observability بتفهم نفس الأسماء.
public static class LlmTelemetry
{
public static readonly ActivitySource Source = new("Contoso.Ai", "1.0.0");
private static readonly Meter Meter = new("Contoso.Ai", "1.0.0");
public static readonly Histogram<long> Tokens = Meter.CreateHistogram<long>("gen_ai.client.token.usage", "{token}");
public static readonly Histogram<double> Ttft = Meter.CreateHistogram<double>("app.gen_ai.time_to_first_token", "s");
public static readonly Counter<double> CostUsd = Meter.CreateCounter<double>("app.gen_ai.cost", "USD");
}
public sealed class TracedChatClient(IChatClient inner, IPriceTable prices, ITenantContext tenant) : IChatClient
{
public async Task<ChatResponse> GetResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null,
CancellationToken ct = default)
{
var model = options?.ModelId ?? "default";
using var span = LlmTelemetry.Source.StartActivity($"chat {model}", ActivityKind.Client);
span?.SetTag("gen_ai.operation.name", "chat");
span?.SetTag("gen_ai.request.model", model);
if (options?.AdditionalProperties?.TryGetValue("prompt_version", out var pv) == true) span?.SetTag("app.prompt.version", pv);
span?.SetTag("tenant.id", tenant.TenantId); // low cardinality on spans is fine; NOT on metrics labels per user
var response = await inner.GetResponseAsync(messages, options, ct);
var inTok = response.Usage?.InputTokenCount ?? 0;
var outTok = response.Usage?.OutputTokenCount ?? 0;
span?.SetTag("gen_ai.response.model", response.ModelId);
span?.SetTag("gen_ai.usage.input_tokens", inTok);
span?.SetTag("gen_ai.usage.output_tokens", outTok);
var cost = prices.Cost(response.ModelId ?? model, inTok, outTok); // your price table, versioned
var tags = new TagList { { "gen_ai.request.model", model }, { "tenant.tier", tenant.Tier } };
LlmTelemetry.Tokens.Record(inTok, tags); LlmTelemetry.Tokens.Record(outTok, tags);
LlmTelemetry.CostUsd.Add(cost, tags);
return response;
}
// GetStreamingResponseAsync: record TTFT when the first update arrives (omitted for brevity)
public IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(IEnumerable<ChatMessage> m, ChatOptions? o = null, CancellationToken ct = default) => inner.GetStreamingResponseAsync(m, o, ct);
public object? GetService(Type t, object? key = null) => inner.GetService(t, key);
public void Dispose() => inner.Dispose();
}ملاحظات مهمة: (1) IChatClient من Microsoft.Extensions.AI، والمكتبة عندها middleware جاهز للـ OpenTelemetry (UseOpenTelemetry()) — استخدمه بدل ما تكتب كل حاجة، وأضف فوقه الـ attributes الخاصة بيك (tenant، prompt version، cost). (2) Cardinality: الـ tenant ID كـ attribute على الـ span مقبول؛ كـ label على metric مع آلاف الـ tenants ممكن يفجّر تكلفة الـ metrics backend. استخدم tier على الـ metrics، والـ per-tenant cost من الـ traces/logs أو من ledger. (3) المحتوى: الـ prompts والـ completions فيها PII؛ ما تسجلهاش افتراضيًا. لو محتاجها للـ debugging: sampling + redaction + retention قصير + صلاحيات وصول.
أدوات LLM observability: إمتى تحتاج أداة مخصصة
الـ APM العادي (Application Insights، Grafana/Tempo، Datadog…) بيجاوب «فين الوقت راح» و«فين الأخطاء». أدوات الـ LLM observability (مثلًا Langfuse أو Arize Phoenix، وفيه غيرهم) بتضيف حاجات خاصة: عرض الـ prompt/completion في سياقه، ربط الـ trace بنسخة الـ prompt، تقييمات (scores) على كل trace، datasets من traces حقيقية، ومقارنة نسخ.
| السؤال | APM عام | أداة LLM |
|---|---|---|
| p95 latency لكل span | ✓ ممتاز | ✓ |
| نسخة الـ prompt X بتجيب جودة أقل من Y؟ | صعب | ✓ (scores + versions) |
| حوّل 50 محادثة فاشلة لـ eval dataset | ✗ | ✓ |
| تكلفة لكل feature/tenant | ممكن بـ custom metrics | ✓ غالبًا built-in |
| Alerting/on-call ناضج | ✓ | متفاوت |
القرار العملي: OTel هو الـ contract. ابعت لنفس الـ traces للـ APM بتاعك (الحقيقة التشغيلية) ولأداة الـ LLM لو محتاجها (الحقيقة الجودية) عن طريق OTel Collector بـ two exporters. كده ما تتربطش بـ vendor، وتقدر تغيّر الأداة من غير ما تلمس الكود. لو بتستضيف أداة open-source بنفسك، افتكر إنها هتخزن prompts فيها بيانات عملاء: نفس متطلبات الأمان والـ retention بتاعة الـ DB الأساسية.
receivers:
otlp:
protocols: { grpc: {}, http: {} }
processors:
batch: {}
attributes/redact:
actions:
- { key: gen_ai.prompt, action: delete } # never ship raw prompts by default
- { key: user.email, action: delete }
exporters:
otlphttp/apm: { endpoint: "https://apm.example.internal" }
otlphttp/llm: { endpoint: "https://llm-observability.example.internal/api/public/otel" }
service:
pipelines:
traces:
receivers: [otlp]
processors: [attributes/redact, batch]
exporters: [otlphttp/apm, otlphttp/llm]الـ prompt والـ model كـ release artifacts
الفكرة: تغيير الـ prompt أو الـ model أو الـ temperature أو الـ retrieval config بيغيّر سلوك المنتج زي ما تغيير الكود بيغيّره — بالظبط. فلازم يعدّي على نفس المسار: version، review، eval، rollout تدريجي، rollback. اللي بيبوّظ ده: prompt بيتعدّل من admin UI في الإنتاج من غير أثر.
id: rag-answer
version: 14 # immutable; a change = new version
model:
provider: azure-openai # or anthropic / openai / local
deployment: chat-large-2026-05 # pin a dated model version, never "latest"
temperature: 0.2
max_output_tokens: 700
retrieval:
embed_model: provider/model@2026-05
k_dense: 50
k_sparse: 50
rerank: cross-encoder/ms-marco-MiniLM-L-6-v2@<sha>
context_token_budget: 6000
prompt_file: prompts/rag-answer/v14.md
prompt_sha256: 3b1f…e9 # CI verifies the file matches the hash
eval:
dataset: evals/rag-golden@2026-11-10
gates: { faithfulness_min: 0.90, answer_correct_min: 0.82, p95_ms_max: 6000, cost_per_req_usd_max: 0.012 }
owner: team-knowledgeالـ manifest ده بيتقرا وقت التشغيل من مكان واحد (config store أو مع الـ deployment نفسه)، وكل trace بيسجّل id@version. النتيجة: أي إجابة في الإنتاج تقدر ترجع لـ «اتولدت بأنهي prompt وأنهي model وأنهي retrieval config».
Git: review و history و CI ببلاش، لكن تعديل الـ prompt محتاج deploy. DB/config store: تعديل أسرع للـ PMs، لكن لازم تبني versioning و approval و audit بنفسك. حل وسط شائع: الـ prompts في git، والـ «نسخة النشطة لكل tenant/flag» في config store بيشاور على version موجود ومتقيّم.
Cost و latency budgets: حدود بتتطبق في الكود
Latency budget بيتوزّع على المراحل: لو الـ SLO هو p95 < 6s للإجابة الكاملة و< 1.5s لأول token، يبقى retrieval + rerank مثلًا ≤ 600ms، والباقي للـ generation. كل مرحلة ليها timeout أقل من الـ budget بتاعها، والـ CancellationToken بيتمرر في كل الطبقات عشان لو المستخدم قفل الصفحة ما نكملش ندفع.
Cost budget على تلات مستويات: (1) per-request: max_output_tokens وحد للـ context tokens وحد لعدد tool iterations للـ agent. (2) per-tenant/day أو شهر: quota حسب الخطة. (3) per-feature: ميزانية شهرية مملوكة لفريق.
public sealed class TenantBudgetGuard(IConnectionMultiplexer redis, IPlanCatalog plans)
{
// Reserve an estimate BEFORE the call, settle the real cost AFTER. Prevents a burst of
// parallel requests from all passing a "spent < limit" check at the same time.
public async Task<Reservation?> TryReserveAsync(string tenantId, decimal estimateUsd)
{
var db = redis.GetDatabase();
var key = $"budget:{tenantId}:{DateTime.UtcNow:yyyyMM}";
var limit = plans.MonthlyAiBudgetUsd(tenantId);
// micro-dollars as integers: atomic INCRBY, no float drift
var micros = (long)(estimateUsd * 1_000_000m);
var after = await db.StringIncrementAsync(key, micros);
await db.KeyExpireAsync(key, TimeSpan.FromDays(40), ExpireWhen.HasNoExpiry);
if (after > (long)(limit * 1_000_000m))
{
await db.StringDecrementAsync(key, micros); // roll back the reservation
return null; // caller degrades: smaller model / cached / 429
}
return new Reservation(key, micros);
}
public Task SettleAsync(Reservation r, decimal actualUsd) =>
redis.GetDatabase().StringIncrementAsync(r.Key, (long)(actualUsd * 1_000_000m) - r.Micros);
}
public sealed record Reservation(string Key, long Micros);Failure mode: الـ budget في Redis بس، و Redis اتمسح ← الـ tenants بقى عندهم ميزانية كاملة تاني. الـ Redis هنا للـ enforcement السريع؛ مصدر الحقيقة للفوترة هو الـ metering ledger في الـ DB (هتشوفه في درس Billing)، ودوريًا بيتعمل reconcile بينهم.
Caching في الـ LLM apps: prompt caching و exact cache و semantic cache
| النوع | بيعمل إيه | المكسب | الخطر |
|---|---|---|---|
| Provider prompt caching | الـ provider بيعيد استخدام حسابات الـ prefix الثابت (system prompt، tools، مستندات طويلة) بين الطلبات | تكلفة و latency أقل على الـ input tokens المتكررة، والإجابة نفسها بتتولد عادي | تقريبًا مفيش خطر صحة؛ لازم الـ prefix يكون ثابت بالظبط (ترتيب الرسائل!). التفاصيل والأسعار بتختلف لكل provider — راجع التوثيق |
| Exact response cache | نفس الطلب الطبيعي (normalized) ← نفس الرد | صفر تكلفة على التكرار | إجابة قديمة بعد تحديث المستندات؛ cross-tenant لو الـ key ناقص |
| Semantic cache | سؤال «مشابه» ← رد سؤال سابق | hit rate أعلى | «مشابه» مش «نفس»: «إلغاء الطلب قبل الشحن» vs «بعد الشحن» قريبين جدًا في الـ embedding وإجابتهم عكس بعض |
public static class ResponseCacheKey
{
// Everything that can change the answer must be in the key.
public static string For(string tenantId, AiRelease release, string normalizedQuestion,
string aclFingerprint, string corpusVersion) =>
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(
$"{tenantId}|{release.Id}@{release.Version}|{aclFingerprint}|{corpusVersion}|{normalizedQuestion}")));
// corpusVersion bumps when the tenant's documents change -> old entries stop matching
}متى ما تعملش semantic cache؟ في أي domain فيه فرق كبير بين أسئلة متقاربة (قانوني، مالي، طبي، سياسات)، أو لما الإجابات personalized. لو عملته: threshold عالي جدًا، فقط للأسئلة العامة، ومع eval على أزواج «قريبة لكن مختلفة».
Model routing و fallbacks و circuit breakers
Routing: مش كل request محتاج أقوى نموذج. classification، extraction بسيط، تلخيص قصير ← نموذج صغير. reasoning متعدد الخطوات أو كتابة حساسة ← نموذج كبير. الـ router ممكن يكون rules (حسب الـ feature)، أو classifier صغير، أو cascade (جرّب الصغير، ولو الثقة قليلة اطلع للكبير).
Fallback: provider تاني أو نموذج تاني لما الأساسي يفشل. لازم يكون مُقيَّم مسبقًا على نفس الـ eval (fallback غير مُقيَّم = مفاجأة جودة وقت الأزمة)، والـ prompt ممكن يحتاج نسخة مخصوصة له.
Circuit breaker: لو الأساسي بيفشل باستمرار، ما تستناش timeout كامل في كل request — افتح الـ circuit وروح للـ fallback فورًا لفترة، وبعدين جرّب تاني.
import random
random.seed(11)
# Two simulated providers/models. Numbers are illustrative, not real prices or SLAs.
MODELS = {
"large": dict(cost_in=3.0, cost_out=15.0, p_fail=0.03, lat=(900, 250), quality=0.92), # $ per 1M tokens
"small": dict(cost_in=0.25, cost_out=1.25, p_fail=0.02, lat=(350, 90), quality=0.80),
}
OUTAGE = range(400, 520) # the "large" provider is down for a window of requests
def call(model, i, tin, tout):
m = MODELS[model]
if model == "large" and i in OUTAGE: return None, 10_000 # times out after 10 s
if random.random() < m["p_fail"]: return None, 2_000 # 5xx / 429 after 2 s
lat = max(80, random.gauss(*m["lat"])) + tout * (6 if model == "large" else 3)
cost = (tin * m["cost_in"] + tout * m["cost_out"]) / 1e6
ok = random.random() < m["quality"]
return dict(cost=cost, ok=ok), lat
# A workload: 30% of requests are "hard"; 25% repeat an earlier question exactly.
REQS = []
for i in range(1000):
if REQS and random.random() < 0.25:
REQS.append(dict(random.choice(REQS), i=i))
else:
REQS.append(dict(i=i, q=f"q{i}", hard=random.random() < 0.30, tin=random.randint(800, 3000), tout=random.randint(80, 400)))
def run(strategy):
cache, breaker_open_until, fails = {}, -1, []
lat, cost, good, errors = [], 0.0, 0, 0
for r in REQS:
i = r["i"]
if strategy["cache"] and r["q"] in cache: # exact-match response cache
lat.append(5); good += cache[r["q"]]; continue
order = ["large"]
if strategy["route"] and not r["hard"]: order = ["small"] # cheap model for easy requests
if strategy["fallback"]: order = order + [m for m in ("small", "large") if m not in order]
total, done = 0, None
for m in order:
if strategy["breaker"] and m == "large" and i < breaker_open_until:
continue # skip a known-bad dependency fast
res, l = call(m, i, r["tin"], r["tout"]); total += l
if m == "large" and strategy["breaker"]:
fails = (fails + [res is None])[-20:]
if len(fails) == 20 and sum(fails) >= 10: breaker_open_until, fails = i + 50, []
if res: done = res; break
lat.append(total)
if done:
cost += done["cost"]; quality = done["ok"] if not (r["hard"] and m == "small") else (random.random() < 0.55)
good += quality
if strategy["cache"]: cache[r["q"]] = quality
else:
errors += 1
lat.sort()
return dict(cost=cost, p50=lat[len(lat)//2], p95=lat[int(len(lat)*.95)], err=errors, good=good)
STRATS = {
"baseline (large only)": dict(route=False, fallback=False, breaker=False, cache=False),
"+ fallback to small": dict(route=False, fallback=True, breaker=False, cache=False),
"+ fallback + circuit breaker": dict(route=False, fallback=True, breaker=True, cache=False),
"+ routing easy->small": dict(route=True, fallback=True, breaker=True, cache=False),
"+ routing + exact cache": dict(route=True, fallback=True, breaker=True, cache=True),
}
print(f"{'strategy':32s}{'cost $':>9s}{'p50 ms':>9s}{'p95 ms':>9s}{'errors':>8s}{'good answers':>14s}")
for name, s in STRATS.items():
random.seed(99) # same randomness for every strategy
r = run(s)
print(f"{name:32s}{r['cost']:9.3f}{r['p50']:9.0f}{r['p95']:9.0f}{r['err']:8d}{r['good']:14d}")strategy cost $ p50 ms p95 ms errors good answers
baseline (large only) 7.967 2533 10000 142 780
+ fallback to small 8.054 2564 11145 4 888
+ fallback + circuit breaker 8.011 2372 3488 4 886
+ routing easy->small 2.903 1275 3300 4 809
+ routing + exact cache 2.239 1082 3287 4 821قراءة الجدول (الأرقام محاكاة توضيحية، مش أسعار حقيقية):
- Fallback لوحده قلّل الأخطاء جدًا وقت انقطاع الـ provider، لكن الـ p95 زاد: كل request بيستنى timeout الـ 10 ثواني الأول قبل ما يروح للبديل.
- Circuit breaker صلّح ده: بعد ما يلاحظ الفشل المتكرر بيروح للبديل على طول، فالـ p95 نزل بشكل كبير.
- Routing خفّض التكلفة بشكل ضخم، لكن عدد الإجابات الجيدة نزل لأن جزء من الطلبات الصعبة اتصنّف غلط وراح للنموذج الصغير. ده الـ trade-off الحقيقي: الـ router نفسه محتاج eval (precision لتصنيف «صعب»).
- Cache نزّل التكلفة والـ latency أكتر على الأسئلة المتكررة.
builder.Services.AddHttpClient("llm-primary", c => c.BaseAddress = new(cfg["Llm:Primary:Endpoint"]!))
.AddResilienceHandler("llm", b =>
{
b.AddTimeout(TimeSpan.FromSeconds(30)); // total, includes retries
b.AddRetry(new HttpRetryStrategyOptions
{
MaxRetryAttempts = 2,
BackoffType = DelayBackoffType.Exponential,
UseJitter = true,
ShouldHandle = args => ValueTask.FromResult(
args.Outcome.Result?.StatusCode is HttpStatusCode.TooManyRequests or >= HttpStatusCode.InternalServerError)
});
b.AddCircuitBreaker(new HttpCircuitBreakerStrategyOptions
{
FailureRatio = 0.5, MinimumThroughput = 20,
SamplingDuration = TimeSpan.FromSeconds(30), BreakDuration = TimeSpan.FromSeconds(30)
});
b.AddTimeout(TimeSpan.FromSeconds(12)); // per attempt
});
// The fallback (second provider) lives one level up, in the chat service: on BrokenCircuitException
// or timeout, call the pre-evaluated fallback release and tag the span app.fallback=true.Retry على 429 من غير احترام Retry-After ومن غير jitter = كل الـ instances بترجع تضرب الـ provider في نفس اللحظة وتطوّل الانقطاع. و retry على request طويل streaming في نصه = بتدفع مرتين. خلي الـ retries قليلة، بـ jitter، وعلى الأخطاء المؤقتة بس.
Knowledge check
ليه tenant_id كـ label على metric ممكن يبقى مشكلة؟
Shadow deployment لـ agent جديد عنده tool بيبعت إيميلات. إيه الصح؟
Provider prompt caching بيغيّر إيه؟
تمارين محلولة
1: عدّل المعمل بحيث الـ router يصنّف 10% من الطلبات الصعبة غلط بدل الوضع الحالي. إيه المتوقع؟
الحل: ده بيمثّل router أدق. الطلبات الصعبة اللي بتروح للصغير بتقل، فعدد الإجابات الجيدة يقرب من الـ baseline والتكلفة ترتفع شوية عن «routing» الحالي. الفكرة: دقة الـ router نفسها metric لازم تتقاس بـ eval مصنّف، وتوازن بين التوفير والجودة.
2: صمّم alert rules لـ feature «اسأل المستندات»
الحل: (1) error rate > 2% لمدة 10 دقايق. (2) p95 TTFT > 2s. (3) نسبة الـ fallback > 20% (الأساسي بيتعب). (4) تكلفة الساعة > 3× المتوسط (loop أو abuse). (5) retrieval.result_count == 0 > 10%. (6) thumbs-down rate ضعف المتوسط الأسبوعي. كل alert مربوط بـ runbook.
3: فريق المنتج عايز يعدّل الـ prompt من لوحة admin فورًا. إزاي توافق من غير ما تكسر الـ release discipline؟
الحل: اللوحة بتنشئ version جديد (immutable) مش تعديل في مكانه، الـ CI/eval job بيتشغل تلقائيًا على الـ version، ولو عدّى الـ gates يتاح كـ candidate للـ canary بنفس الـ router. audit لمين عمل إيه. يعني السرعة موجودة لكن على نفس المسار.
Mini project: AI release pipeline
للـ CAPSTONE/: (1) manifest YAML للـ release زي اللي فوق مع hash check في CI. (2) AiReleaseRouter بـ canary 5% sticky و kill switch. (3) Dashboard فيه: p50/p95/TTFT، tokens وتكلفة لكل tier، fallback rate، thumbs-down rate — مقسّم حسب app.prompt.version. (4) تجربة: اعمل version جديد بيبوظ الجودة عمدًا وأثبت إن الـ gate أو الـ canary metrics بيمسكوه قبل الـ 100%.
أسئلة إنترفيو: Junior → Senior → Staff
(Junior) إيه الفرق بين trace و metric و log؟
(Senior) إزاي تعمل canary لتغيير prompt والجودة مش رقم واحد؟
(Senior) التكلفة اتضاعفت فجأة. خطوات التحقيق؟
(Staff) صمّم platform داخلي للـ LLM calls لـ 15 فريق في الشركة.
المراجع والقراءة الإضافية
الدرس بيشرح الفكرة نفسها؛ الروابط دي للتحقق والتعمق والرجوع لتفاصيل الـ API. (محتاجة إنترنت.)
التوثيق الرسمي — Official documentation
مصادر تعليمية ومتقدمة — Third-party & advanced reading
خريطة التغطية: 10 عنصر من الـ Roadmap ومكان شرحه في الدرس
خلصت الدرس وحليت الأسئلة؟ علّم عليه عشان يتحسب في تقدّمك.