Software Engineer Encyclopedia
0%
Domain 13 · MLOps, LLMOps & Production AI · Topic 13.2

MLOps وLLMOps ودورة حياة النموذج

MLOps and LLMOps Model Lifecycle

Model registry, serving, drift, online/offline evaluation, LLM tracing, cost, routing and rollback.

  • Professional Engineering
  • ~18 min read
  • 20 sections
  • 11 code examples
  • 1 diagrams
  • 7 questions
  • Priority L2 · Important
  • MLflow · OpenTelemetry · Prometheus · Grafana

بعد الدرس ده هتقدر

  • تفرّق بين data drift وconcept drift وعطل الـ pipeline.
  • تحسب PSI وتفسّره صح.
  • تختار بين shadow وcanary وA/B وتجهّز rollback.
  • تحدد اللي لازم يتسجل مع كل نسخة موديل.

المتطلبات قبل ما تبدأ

DevOps + ML + LLM/RAG — المجال ده بيشغّلهم في الإنتاج.

مستوى التعمق المطلوب

PRACTICALتخدم موديل في الإنتاج وتراقبه وتقيّمه، وتكتشف لما أداؤه يقل أو البيانات تتغير.

01

Model Lifecycle و Registry و Versioning

Every prediction needs provenance
Deep dive

Model lifecycle يبدأ من dataset version و code commit و training config إلى artifact و evaluation و registry و deployment. Registry يخزن lineage و metadata و approval/alias حسب النظام. لا تروج artifact مجهول المصدر. versioning يشمل model weights و preprocessing و feature schema و tokenizer/embedding model و prompt templates عند LLMs.

استخدم immutable artifact IDs، signed provenance عند الإمكان، و environment manifests. rollback يجب أن يرجع إلى model + preprocessing + config متوافقين، لا weights وحدها.

02

دورة حياة الموديل

Model lifecycle
Basics
Data vNversionedTraintracked runEvaluatevs championRegistrystaged → prodDeploycanary/shadowMonitordrift, qualityretrain trigger: drift / new labels / schedule
Every model version is traceable from data to production, و production signals trigger the next version
03

Serving و Deployment و CPU/GPU

Operate inference with capacity limits
Practical

Serving قد يكون batch أو online API أو streaming. اختَر CPU/GPU حسب model size، throughput، latency، batching، quantization، و cost. GPU utilization المنخفض مع latency مرتفعة قد يعني bottleneck في preprocessing/network/queueing. راقب cold start و memory fragmentation و OOM.

Deployment strategy: canary أو blue/green، shadow traffic عند عدم تنفيذ side effects، gradual rollout، و rollback. اختبر model artifact compatibility و input schema. افصل readiness عن liveness؛ model لم يحمل بعد لا يجب أن يستقبل traffic.

04

Monitoring و Drift و Online Evaluation

Observe data and model outcomes
Deep dive

راقب input schema violations، missingness، distribution drift، prediction distribution، latency، errors، و delayed ground-truth metrics. Data drift تغير input distribution؛ concept drift تغير mapping؛ performance drift تراجع outcome. لا تعِد التدريب تلقائيًا عند كل drift alert؛ تحقق من source data و label quality والـ business impact.

Offline eval يقيس على frozen dataset، online eval يقيس في production عبر feedback/A-B/shadow مع safeguards. لا تعرض user group لتجربة غير آمنة لمجرد A/B. راقب model slices والـ confidence calibration.

Drift Investigation Before Retraining

عند drift alert، افحص upstream schema، source mix، seasonality، missingness، feature pipeline version، و population changes. بعد ذلك افحص delayed labels و metric slices. قد يكون alert بسبب legitimate business shift أو broken ingestion. Retraining على corrupted data يثبت المشكلة بدل حلها.

اكتب decision record: retrain / rollback / adjust threshold / fix pipeline / no action، مع evidence والـ owner. نفّذ candidate evaluation قبل promotion، ولا تجعل auto-retraining ينشر model دون gates.

Drift Monitoring: اكتشف إن الموديل بقى قديم قبل ما المستخدم يكتشف

الكود العادي بيفضل شغال زي ما هو لحد ما حد يغيّره. الموديل لأ: هو اتدرّب على عالم معيّن، والعالم بيتغير. الأداء بينزل في صمت — مفيش exception ومفيش 500. ده الفرق الجوهري بين تشغيل software وتشغيل ML.

النوعاللي اتغيرمثالبتكتشفه إزاي
Data driftتوزيع الـ inputsعملاء جدد من شريحة عمرية مختلفةمقارنة توزيع الـ features — من غير labels
Concept driftالعلاقة بين الـ input والـ outputنفس نمط الشراء بقى معناه احتيالمحتاج labels: راقب المقاييس الفعلية لما توصل
Upstream changeالـ pipeline نفسهحقل بقى بالقرش بدل الجنيهdata validation على الـ schema والـ ranges
Pythondrift.py — PSI per feature against the training reference, plus a two-sample KS testExecuted ✓
import numpy as np
from scipy.stats import ks_2samp

rng = np.random.default_rng(3)

def psi(reference, current, bins=10):
    """Population Stability Index. Bin edges come from the REFERENCE quantiles, so each bin holds ~10% of it."""
    edges = np.quantile(reference, np.linspace(0, 1, bins + 1))
    edges[0], edges[-1] = -np.inf, np.inf
    ref = np.histogram(reference, edges)[0] / len(reference)
    cur = np.histogram(current, edges)[0] / len(current)
    ref, cur = np.clip(ref, 1e-4, None), np.clip(cur, 1e-4, None)      # avoid log(0)
    return float(np.sum((cur - ref) * np.log(cur / ref)))

# reference = the data the model was trained on
train = {"age": rng.normal(35, 8, 20000), "basket_value": rng.lognormal(4.0, 0.5, 20000), "sessions_per_week": rng.poisson(3, 20000).astype(float)}

# three "weeks" of production traffic
weeks = {
    "week 1 (stable)":          {"age": rng.normal(35, 8, 5000),   "basket_value": rng.lognormal(4.0, 0.5, 5000),  "sessions_per_week": rng.poisson(3, 5000).astype(float)},
    "week 2 (new campaign)":    {"age": rng.normal(29, 7, 5000),   "basket_value": rng.lognormal(4.0, 0.5, 5000),  "sessions_per_week": rng.poisson(3, 5000).astype(float)},
    "week 3 (unit bug x100)":   {"age": rng.normal(35, 8, 5000),   "basket_value": rng.lognormal(4.0, 0.5, 5000) * 100, "sessions_per_week": rng.poisson(3, 5000).astype(float)},
}

def level(v):
    return "ok" if v < 0.1 else ("watch" if v < 0.25 else "ALERT")

for name, data in weeks.items():
    print(name)
    for feature in train:
        value = psi(train[feature], data[feature])
        ks = ks_2samp(train[feature], data[feature])
        print(f"   {feature:<18} PSI={value:6.3f}  {level(value):<6} KS stat={ks.statistic:.3f}  p={ks.pvalue:.1e}")
ConsoleOutput — captured from a real run
week 1 (stable)
   age                PSI= 0.001  ok     KS stat=0.011  p=6.8e-01
   basket_value       PSI= 0.002  ok     KS stat=0.013  p=5.1e-01
   sessions_per_week  PSI= 0.002  ok     KS stat=0.012  p=5.9e-01
week 2 (new campaign)
   age                PSI= 0.688  ALERT  KS stat=0.324  p=0.0e+00
   basket_value       PSI= 0.003  ok     KS stat=0.017  p=2.2e-01
   sessions_per_week  PSI= 0.001  ok     KS stat=0.004  p=1.0e+00
week 3 (unit bug x100)
   age                PSI= 0.003  ok     KS stat=0.017  p=2.0e-01
   basket_value       PSI= 8.283  ALERT  KS stat=1.000  p=0.0e+00
   sessions_per_week  PSI= 0.002  ok     KS stat=0.011  p=7.6e-01

PSI بيقسّم الـ feature لشرائح حسب بيانات التدريب، وبيقارن نسبة كل شريحة دلوقتي بنسبتها وقت التدريب. العُرف الشائع: أقل من 0.1 مستقر، 0.1–0.25 يستاهل متابعة، أكتر من 0.25 تغيّر كبير. دي قواعد تقريبية مش قوانين — عايرها على بياناتك.

أسبوع 2: الحملة جابت عملاء أصغر سنًا. الـ age بس اللي اتحرك. ده data drift حقيقي: الموديل ممكن يفضل كويس وممكن لأ — لازم تتابع الأداء الفعلي على الشريحة الجديدة.

أسبوع 3: PSI ضخم على basket_value. ده مش تغيّر في العالم — ده bug في الـ pipeline (وحدة غلط). الـ drift monitoring هو غالبًا أول حاجة بتكشف أعطال البيانات.

ليه مش p-value لوحده؟ في أسبوع 2 وأسبوع 3 الـ p-value صفر في الحالتين — يعني الاختبار بيقول «فيه فرق» وبس. لكن الحالتين مختلفتين جدًا: تحرّك في متوسط العمر (KS 0.32، PSI 0.69) مقابل توزيع اتنقل بالكامل (KS 1.0، PSI 8.3). الـ p-value بيجاوب «هل فيه فرق؟» مش «قد إيه؟»، ومع عيّنات بالملايين حتى فرق تافه عمليًا بيدّي p صغير. عشان كده الـ alerting بيتبني على حجم التغيّر.

الـ drift مش الأداء

PSI عالي معناه «الـ inputs اتغيرت»، مش «الموديل بقى وحش». والعكس: concept drift ممكن يحصل والـ inputs شكلها ثابت تمامًا. الحقيقة الوحيدة هي المقاييس على labels حقيقية — حتى لو بتوصل متأخرة. الـ drift إنذار مبكر مش حكم.

05

LLMOps: Prompt و RAG و Trace Versions

Version the whole AI system, not only the model
Deep dive

LLM app version تتكون من provider/model version، system prompt، tool schemas، retrieval settings، embedding model، chunker/parser versions، reranker، safety policies، و output validator. أي تغيير في واحدة قد يغير behavior. اربط traces بكل هذه versions.

راقب token usage، p95 latency، cost، retrieval quality، tool success، refusal rate، citations، و fallback. MLflow أو Langfuse أو OpenTelemetry قد تساعد حسب stack؛ لا تعتمد على vendor dashboard وحده إذا تحتاج cross-service trace.

06

Model Fallbacks و Routing و PII Redaction

Resilience with privacy invariants
Practical

Fallback model قد يختلف في context window أو tools أو structured output؛ تحقق من compatibility قبل التحويل. لا تسمح لل fallback بتجاوز privacy region أو safety controls. Routing by task يحتاج eval per route. PII redaction يجب أن يحافظ على semantics اللازمة، ويكون reversible only where legally and technically justified.

في حالة provider outage، fallback إلى deterministic search أو queue/retry أو human path أفضل من جواب مخترع. ضع circuit breaker و budget، وسجل السبب دون raw sensitive payload.

07

MLOps Capstone و Runbook

Promote, monitor, rollback and learn
Practical

جهز pipeline: dataset validation → training/eval → artifact registry → approval → deployment → canary → monitoring → promotion/rollback. للـ LLM/RAG: ingestion version → index build → retrieval eval → prompt/model eval → security tests → staged rollout.

Runbook يجيب: كيف أعرف إن النموذج متدهور؟ كيف أوقف route؟ كيف أرجع model/index/prompt؟ كيف أتعامل مع data deletion؟ كيف أتحقق من التكلفة؟ وكيف أعيد إنتاج incident؟ ضع owner و SLO و escalation path.

Definition of Doneكل release له lineage، eval report، security sign-off، cost/latency budget، dashboard، canary، rollback، و incident runbook.
08

Release Promotion و Rollback Strategy

Promote artifacts with evidence
Deep dive

Promotion pipeline: register candidate → automated validation → offline eval → security/privacy review → staging shadow → canary → production alias. لا تجعل registry alias يتحرك قبل موافقة gates. Rollback يعيد model/index/prompt/config bundle المتوافق. للـ RAG، index version يجب أن يتوافق مع embedding model و chunker metadata.

احتفظ previous known-good bundle، migration notes، و rollback owner. بعد rollback تحقق من traffic routing و cache invalidation و telemetry labels.

09

Operational Runbook و Incident Response

What to do when AI degrades
Practical

Runbook يغطي provider outage، latency spike، cost spike، model quality regression، embedding mismatch، data drift، PII incident، و cross-tenant leak. لكل incident: detection signal، severity، containment، rollback/disable switch، communication، evidence preservation، recovery validation، و postmortem.

لا تعالج quality incident بتغيير prompt في production مباشرة دون eval. اعمل canary على golden set ثم traffic صغير. في privacy incident، أوقف exposure أولًا ثم اتبع legal/security process.

PythonWhat to do when AI degrades
incident_actions = [
  "disable unsafe tool route",
  "switch to approved fallback or read-only mode",
  "preserve trace IDs and release versions",
  "verify tenant ACL and cache isolation",
  "rollback to last evaluated bundle",
  "run golden regression before re-enable",
]
10

Model/Prompt/Index Bundle Compatibility

Version the full deployed system
Deep dive

في RAG، deployment bundle ليس model وحده: parser version، chunker version، embedding model/dimensions، index schema، reranker، prompt template، generator model، output schema، و ACL policy. قد يتغير index قبل model أو العكس فيسبب mismatch. استخدم compatibility manifest واختبر staged index build قبل alias switch.

Rollback يتطلب استعادة bundle متوافق كاملًا، أو على الأقل معرفة versions المتوافقة. لا تحذف old index فور switch؛ احتفظ به خلال rollback window وفق storage/privacy policy.

11

استراتيجيات النشر للموديلات

Shadow, canary, A/B, rollback — and what makes ML releases different
Practical
الاستراتيجيةبتشتغل إزايبتجاوب علىالخطر على المستخدم
Shadowالموديل الجديد بياخد نسخة من الـ traffic الحقيقي، ورده بيتسجل ومش بيتبعت للمستخدمهل بيشتغل على بيانات حقيقية؟ latency؟ بيختلف عن القديم قد إيه؟صفر
Canary1–5% من المستخدمين على الجديد، وتزوّد تدريجيًاهل فيه أعطال أو تدهور واضح؟محدود
A/B testتقسيم عشوائي ثابت وقياس مقياس businessهل الجديد أحسن فعلًا للمنتج؟متوسط
Rollbackالـ serving بيشاور على alias، والرجوع = تغيير الـ alias للنسخة السابقة——

اللي بيتسجل مع كل نسخة موديل

JSONmodel_card.json — the minimum a registry entry needs to make a model reproducible and reversible
{
  "name": "churn-classifier",
  "version": 14,
  "stage": "candidate",
  "code_commit": "9f2c1ab",
  "training_data": { "snapshot": "customers_2026_10_01", "rows": 412338, "sha256": "…" },
  "features_schema_version": 3,
  "hyperparameters": { "C": 0.5, "class_weight": "balanced" },
  "metrics": { "pr_auc_validation": 0.47, "pr_auc_test": 0.46, "brier": 0.11 },
  "decision_threshold": 0.07,
  "python": "3.12.3",
  "dependencies_lock": "requirements.lock@sha256:…",
  "approved_by": null
}

القاعدة: موديل = كود + بيانات + إعدادات. لو أي واحدة من التلاتة مش مسجلة، مش هتقدر تعيد بناء الموديل ولا تفهم ليه نسخة 14 أحسن من 13. والـ threshold جزء من الموديل: نفس الـ weights بـ threshold مختلف = سلوك مختلف في الإنتاج.

موديل جديد عدّى كل الـ offline metrics وأحسن من القديم. أأمن خطوة أولى في الإنتاج؟

PSI بتاع feature مهمة طلع 0.4 والموديل لسه بيرد عادي. أول تصرف؟

Deployment Patterns: Shadow, Canary, Blue-Green and Rollback

Shadow deployment يشغل candidate على traffic حقيقي دون التأثير في user outcome، ويفيد في latency/schema/quality comparison إذا labels لاحقة. Canary يوجه نسبة صغيرة من traffic إلى candidate مع guardrails. Blue-green يشغل بيئتين ويسمح بالتبديل السريع. Batch scoring يحتاج versioned output tables و atomic publish.

Rollback يجب أن يعيد model + preprocessing + schema + threshold + routing config المتوافقة. في LLM/RAG bundle يشمل prompt و embedding/index/reranker versions. حدد rollback triggers مسبقًا مثل error rate، p95، safety violations، و critical slice regression.

PythonReduce blast radius during model releases
release_plan = {
  'stage_1': 'offline evaluation',
  'stage_2': 'shadow traffic',
  'stage_3': '5 percent canary',
  'stage_4': 'gradual rollout',
  'rollback_on': ['safety invariant breach', 'p95 SLO breach', 'critical quality regression'],
}
print(release_plan)
12

اختبر فهمك

Knowledge Check
Practical
لماذا لا يكفي model version وحده للـ RAG rollback؟
لأن parser/chunker/embedding/index/reranker/prompt/schema قد تكون تغيرت ويجب استرجاع bundle متوافق.
هل drift alert يعني إعادة تدريب تلقائي؟
لا. تحقق من data quality و source changes والـ labels والأداء قبل قرار retraining.

اختبار الإتقان المهني

لماذا rollback في RAG يحتاج bundle متوافقًا؟
لأن parser/chunker/embedding/index/reranker/prompt/model versions مترابطة، وإرجاع model وحده قد يسبب mismatch.
لماذا لا ينبغي أن يكون drift alert سببًا تلقائيًا لإعادة التدريب؟
لأن السبب قد يكون schema break أو seasonality أو upstream corruption أو legitimate population shift.
ما الفرق بين shadow و canary deployment؟
Shadow يشغل candidate دون التأثير في user outcome؛ canary يوجه نسبة صغيرة من traffic الفعلي إليه.
13

Experiment Tracking, Registry and Artifact Lineage

Make every model build explainable
Deep dive

Experiment tracking يسجل parameters، metrics، code revision، dataset snapshot، environment، artifacts، و evaluation report. Registry يضيف lifecycle stages/aliases، approval، ownership، و deployment metadata. لا تكتفِ بحفظ weights؛ من دون preprocessing و data version و schema و threshold قد لا يمكن إعادة inference.

Model card/manifest يجب أن يذكر intended use، limitations، training data summary، evaluation slices، safety risks، و owner. افصل artifact immutable عن mutable deployment alias. promotion عملية محكومة بالـ gates وليست مجرد تغيير tag.

PythonMake every model build explainable
model_manifest = {
  'model_version': 'churn-2026-11-12.3',
  'code_commit': 'immutable-commit-sha',
  'dataset_snapshot': 'warehouse://snapshot/8421',
  'preprocessing_version': 'features-v5',
  'metrics_report': 'eval://run/991',
  'owner': 'ml-platform-team',
}
print(model_manifest['model_version'])
14

Monitoring Drift, Delayed Labels and Feedback Loops

Monitor inputs, predictions and outcomes
Deep dive

Monitoring layers: service health (availability/latency/errors)، data quality (schema/missingness/freshness)، input drift، prediction drift، outcome metrics after labels arrive، و business impact. Delayed labels require cohorts/time windows; recent predictions cannot be judged using labels not yet matured. Feedback loops arise when predictions affect user behavior and therefore future training data.

Retraining trigger لا ينبغي أن يكون drift threshold فقط. تحقق من upstream pipeline، seasonality، label delay، policy changes، و population mix. سجل retraining decision مع evidence، وقيّم candidate offline ثم shadow/canary قبل promotion.

PythonMonitor inputs, predictions and outcomes
monitoring_layers = [
  'service: p95, errors, saturation',
  'data: freshness, nulls, schema',
  'model: prediction distribution, drift',
  'outcomes: delayed-label quality by cohort',
  'business: conversion, loss, review burden',
]
print(len(monitoring_layers))
15

Incident Response and Model Governance

Operate models as owned production systems
Deep dive

كل model/service له owner، risk tier، SLO، on-call route، runbook، data classification، release history، و retirement plan. Incident runbook يفرق بين provider outage، bad deployment، data corruption، drift، security incident، و cost runaway. containment قد يعني disable tool، switch model، serve deterministic fallback، pause ingestion، or rollback index.

Governance تشمل approval للبيانات والنماذج، access review، auditability، retention، explainability requirements حسب المجال، و documented limitations. لا تجعل model auto-retrain/auto-deploy دون release gates. بعد incident اكتب postmortem blameless مع corrective actions قابلة للقياس.

PythonOperate models as owned production systems
incident_checklist = [
  'identify affected model/prompt/index versions',
  'contain unsafe actions and isolate affected tenants',
  'preserve traces and immutable evidence',
  'rollback or switch to approved fallback',
  'replay only idempotent operations after reconciliation',
  'add regression test and owner for each action',
]
print('Runbook steps:', len(incident_checklist))
16

Integrated Capstone: Enterprise Knowledge Assistant

From architecture to a production-ready AI product
Deep dive

المشروع النهائي يجمع محطات AI Engineering كلها: Knowledge Assistant لمؤسسة عندها سياسات وفواتير وإجراءات داخل مستندات PDF/Office. المستخدم يسأل بالعربية أو الإنجليزية، والنظام يرجع إجابة مدعومة بمصادر وصفحات، مع احترام tenant isolation و document ACL. بعض الطلبات تحتاج workflow مثل إنشاء support ticket أو طلب موافقة؛ لا تنفذ refund أو تعديلًا ماليًا تلقائيًا.

الـ architecture المقترحة: ASP.NET Core هو public API و Identity/authorization و tenant boundary و workflow coordinator؛ Python ingestion workers مسؤولة عن parsing/OCR/chunking/embedding jobs؛ PostgreSQL يخزن metadata و application state، و vector/lexical retrieval layer يخدم البحث؛ LLM provider behind adapter؛ MCP tools تكشف عمليات ضيقة؛ queue + durable workflow للعمليات الطويلة. لا تجعل Python أو LLM مصدر الحقيقة للـ business state.

المبدأ الهندسي: كل boundary لها contract، timeout، telemetry، retry policy، owner، و test. كل model/prompt/index/parser/chunker version مسجل في deployment manifest. كل evidence لها provenance و ACL، وكل side effect له idempotency key و approval عند الحاجة.

TextFrom architecture to a production-ready AI product
Client -> ASP.NET Core API -> AuthN/AuthZ + Tenant Context
ASP.NET Core -> Application Use Case -> Retrieval Port -> Hybrid Search
Retrieval -> ACL Filter -> Evidence Bundle -> LLM Adapter
LLM -> Structured Answer + Evidence IDs -> Citation/Policy Validator -> Client
Python Ingestion Worker -> Parse/OCR -> Normalize -> Chunk -> Embed -> Versioned Index
Agent -> Narrow MCP Tool -> Server-side Authorization -> Business Service
Workflow Store + Queue -> Checkpoints / Approval / Idempotent Commands
17

Capstone Contracts and Data Model

Make ownership and provenance explicit
Deep dive

كيانات أساسية: Tenant، User، Document، DocumentVersion، IngestionJob، Chunk، EmbeddingProfile، IndexBuild، Conversation، AnswerTrace، EvidenceReference، ToolExecution، Workflow، Approval، و EvaluationRun. Document يرتبط بـ Tenant و ACL؛ Chunk يرتبط بـ DocumentVersion و page/section/offsets و content hash و parser/chunker versions. لا تستخدم document ID وحده دون tenant scope في كل query.

API contracts مقترحة: POST /api/knowledge/ask لطرح سؤال؛ POST /api/documents لرفع مستند؛ GET /api/ingestion-jobs/{id} لمتابعة ingestion؛ GET /api/answers/{id}/sources لعرض evidence؛ POST /api/workflows/{id}/approve للموافقة؛ GET /api/admin/evaluations/{runId} لنتائج التقييم. لا تجعل upload request ينتظر OCR/embedding؛ أعد job ID واعمل async processing.

في ‎.NET، DTOs و validation في API/Application، use-case orchestration في Application، provider/vector/queue clients في Infrastructure، و domain rules للـ approval والـ tenant ownership في Domain/Application حسب ownership. Python service له internal API أو queue contract، ولا يتصل مباشرة بقاعدة بيانات business الأساسية إلا عبر contract مصرح.

C#Make ownership and provenance explicit
public sealed record AskRequest(string Question, string ConversationId);
public sealed record EvidenceDto(
    string EvidenceId, string DocumentId, int Page,
    string Title, string Snippet);
public sealed record AskResponse(
    string Answer, IReadOnlyList<EvidenceDto> Sources,
    string ModelVersion, string PromptVersion, string TraceId);

// TenantId and UserId come from authenticated claims, never from the request body.
18

Capstone Evaluation Plan and Release Gates

Prove quality before exposing users
Deep dive

ابنِ gold set من 150–300 سؤالًا كبداية تعليمية، مع توزيع: answerable، unanswerable، multi-hop، exact identifiers، Arabic/English/mixed، tables، outdated documents، conflicting versions، و cross-tenant adversarial cases. لكل سؤال، حدّد expected evidence IDs، required answer facts، abstention expectation، و risk level. استخدم human review لتثبيت labels؛ لا تعتمد على LLM judge وحده.

قيّم ingestion coverage و OCR quality، retrieval Recall@5/10 و MRR، reranker gain، citation support، answer correctness/completeness، abstention precision/recall، schema validity، tool argument correctness، و tenant isolation. Operational gates: p95 latency، availability، tokens/task، cost/success، queue age، ingestion freshness. Security invariants مثل zero cross-tenant retrieval و zero unapproved write actions تكون hard gates لا averages.

نفّذ offline evaluation، ثم shadow traffic، ثم canary لعدد محدود من المستخدمين، ثم rollout تدريجي. أي تغيير في parser/chunker/embedding/index/prompt/model/tool schema يتطلب evaluation bundle جديدًا. احتفظ rollback bundle متوافقًا كاملًا.

PythonProve quality before exposing users
release_gates = {
    'cross_tenant_evidence_leaks': 0,
    'unapproved_write_actions': 0,
    'citation_support_rate_min': 0.95,
    'retrieval_recall_at_10_min': 0.90,
    'schema_validity_min': 1.00,
    'p95_latency_seconds_max': 4.0,
    'cost_per_successful_answer_usd_max': 0.03,
}
assert release_gates['cross_tenant_evidence_leaks'] == 0
assert release_gates['unapproved_write_actions'] == 0
19

Capstone Build Sequence, Failure Drills and Portfolio Evidence

A project is complete when it can be operated
Deep dive

Build sequence: (1) define use cases/risk and golden set; (2) implement ‎.NET auth/tenant API and metadata schema; (3) build Python ingestion with deterministic parser/chunker and idempotent jobs; (4) add lexical retrieval baseline; (5) add embeddings/vector search and reranker only if evaluation improves; (6) implement grounded answer schema/citations/abstention; (7) add MCP read-only tools; (8) add approval-gated workflow; (9) instrument traces/cost/latency; (10) CI evaluation gates and staged deployment.

Failure drills: corrupt PDF، OCR language mismatch، duplicate upload، index build interrupted، document deleted during retrieval، ACL revoked mid-conversation، provider 429/timeout، malformed model JSON، unknown citation ID، MCP server restart، duplicate workflow message، approval payload changed، و rollback to previous model/index bundle. لكل drill اكتب expected behavior، telemetry signal، و recovery runbook.

Portfolio evidence: architecture diagram، ADRs لقرارات RAG vs long context و hosted vs local و agent vs deterministic workflow؛ dataset/evaluation card؛ API/OpenAPI docs؛ threat model؛ test reports؛ cost/latency benchmark؛ deployment manifest؛ incident runbook؛ demo قصير يوضح citations و tenant isolation. اشرح trade-offs والأشياء التي لم تنفذها بعد بصدق.

PythonA project is complete when it can be operated
failure_drills = [
  'duplicate_document_upload', 'ocr_language_mismatch', 'index_build_interrupted',
  'acl_revoked', 'provider_429_and_timeout', 'invalid_model_json',
  'unknown_citation_id', 'mcp_restart', 'duplicate_workflow_delivery',
  'approval_payload_mutated', 'model_index_rollback',
]
print('Required failure drills:', len(failure_drills))
20

خريطة Cloud ML: إيه الخدمة اللي تختارها؟

Separate training and MLOps from foundation-model application platforms
Deep dive

دي مقارنة للمسؤولية العامة، مش أسعار أو قائمة features. أسماء المنتجات والواجهات تتغير؛ راجع التوثيق الرسمي وقت الاختيار. وجود model catalog لا يعني أن نفس المنصة أفضل لتدريب موديل مخصص أو استضافة application API.

السحابةCustom ML و MLOpsGenAI و Agentsنقطة بداية
Microsoft AzureAzure Machine Learning: custom training، experiments، registry، pipelines و managed endpoints.Microsoft Foundry (الاسم الحالي لـ Azure AI Foundry في docs): models/inference، evaluation و tracing لبناء GenAI applications/agents.ابدأ Azure ML لو تحتاج training/lifecycle؛ Foundry قد يكفي لتطبيق GenAI يستخدم model جاهز.
Google CloudVertex AI docs/SDKs تغطي custom training و pipelines و registry و serving؛ بعض توثيق المنصة يظهر تحت Gemini Enterprise Agent Platform.المنصة تجمع model/agent capabilities؛ راجع مسار المنتج الحالي لكل مهمة.قارن مسار البيانات والتدريب والنشر والتسمية الحالية للـ APIs.
AWSAmazon SageMaker AI لتدريب وتقييم ونشر ML و foundation models ضمن lifecycle مُدار.اختار خدمة GenAI المناسبة في AWS حسب الحاجة؛ لا تفترض أن SageMaker AI يغطي كل واجهات التطبيقات التوليدية.مناسب عند الحاجة لتدريب مخصص أو تكامل lifecycle مع IAM والتخزين والتشغيل الموجود.

ابدأ بالـ workload: هل هتدرّب؟ تستخدم API لموديل جاهز؟ تحتاج GPU endpoint أو batch؟ من يملك data governance و identity؟ ما region/retention؟ وما تكلفة request ناجح عند حمل واقعي؟ اعمل proof of concept على نفس dataset و SLO و deployment effort.

راجع الأسماء والواجهات

Google Cloud يعرض بعض المحتوى حاليًا باسم Gemini Enterprise Agent Platform، و Microsoft غيّر Azure AI Foundry إلى Microsoft Foundry. أسماء SDKs و endpoints قد لا تتزامن مع اسم المنتج؛ استخدم صفحات الهجرة الرسمية.

تمرين اختيار منصة وحله

تطبيق ‎.NET يستعمل موديل جاهز و RAG بلا تدريب: قارن model platform في السحابة القائمة مع local inference؛ خلّي ACL و business rules في التطبيق. ما تضفش خدمة تدريب ما دام مفيش custom training lifecycle.

Classifier يتدرب دوريًا على بيانات الشركة ويحتاج batch/online: قارن Azure ML و Google Cloud ML platform و SageMaker AI على IAM و lineage و compute و endpoints و monitoring و rollback.

↗

المراجع والقراءة الإضافية

References & further reading

الدرس بيشرح الفكرة نفسها؛ الروابط دي للتحقق والتعمق والرجوع لتفاصيل الـ API. (محتاجة إنترنت.)

خريطة التغطية: 22 عنصر من الـ Roadmap ومكان شرحه في الدرس
New sectionModel Serving§01
New sectionModel Versioning§01
New sectionModel Registry§01
New sectionModel Monitoring§04
New sectionData Drift§04
New sectionModel Performance Monitoring§04
SuggestedModel Serving§01
SuggestedModel Versioning§01
SuggestedModel Registry§01
SuggestedModel Monitoring§04
SuggestedData Drift§04
SuggestedModel Performance Monitoring§04
SuggestedOffline and Online Evaluation§04
SuggestedLLM Evaluation Datasets§04
SuggestedRegression Testing for Prompts§04
SuggestedLLM Tracing§04
SuggestedToken, Latency and Cost Monitoring§04
SuggestedModel Fallbacks and Routing§04
SuggestedAI Deployment§03
SuggestedPII Redaction§04
SuggestedGPU vs CPU Inference§03
SuggestedOptional tools: MLflow, Langfuse, OpenTelemetry, Prometheus, Grafana§04

خلصت الدرس وحليت الأسئلة؟ علّم عليه عشان يتحسب في تقدّمك.

محتويات الدرس