Software Engineer Encyclopedia
0%
Domain 12 · RAG, Agents & MCP · Topic 12.4

هندسة Agentic Workflows الموثوقة

Agentic Workflow Engineering

Sequential/parallel/conditional workflows, state, checkpoints, approvals, recovery and orchestration.

  • Professional Engineering
  • ~23 min read
  • 16 sections
  • 10 code examples
  • 2 diagrams
  • 14 questions
  • Priority L2 · Essential
  • .NET 9 · Microsoft.Extensions.AI (IChatClient, FunctionCallContent) · PostgreSQL + pgvector · Python 3 lab (executed)

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

  • تكتب agent loop صريح بحدود وgates وcheckpoints بدل الاعتماد على الـ prompt
  • تصمم short/working/long-term memory وتمنع memory poisoning
  • تختار بين ReAct وPlan-and-Execute وworkflow حتمية
  • تقرر إمتى multi-agent مفيد وإمتى overkill بحسبة وتجربة
  • تصمم human-in-the-loop durable بموافقة مربوطة بالـ arguments
  • تقيّم الـ trajectory مش الإجابة بس، وتحتوي الفشل بـ idempotency وsandboxing وkill switches

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

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

PRACTICALتفرّق بين LLM App وWorkflow وAgent، وتبني workflow موثوق بيحفظ حالته ويرجع لإنسان في القرارات الحساسة.

01

Workflow topology: Sequential و Parallel و Conditional

Make control flow explicit
Deep dive

Sequential workflow ينفذ خطوات معتمدة على السابقة. Parallel workflow يشغل فروعًا مستقلة ثم يجمع النتائج. Conditional workflow يختار مسارًا حسب validated state. Agent planning يضيف اختيارًا ديناميكيًا للخطوات، لكنه يجب أن يعمل داخل graph أو policy محددة.

ارسم nodes و edges، وحدد input/output لكل node، timeout، retry، idempotency، compensation، و ownership. لا تجعل prompt يقرر مباشرة كل شيء في workflow؛ اجعل model output قرارًا محدودًا يتم التحقق منه.

الـ agent loop من جوه: إيه اللي بيحصل فعلًا في كل خطوة

«Agent» = نموذج في loop: يشوف الحالة ← يقرر (tool call أو إجابة نهائية) ← الكود بتاعك ينفذ الـ tool ← النتيجة ترجع للـ context ← تاني. النموذج بيقترح؛ الكود بتاعك هو اللي بينفذ. وده معناه إن كل الضمانات (حدود، صلاحيات، idempotency، موافقات) مكانها الـ loop مش الـ prompt.

Statemessages · memoryLLMproposes actionHost gatesbudget · loop · scopeapproval · idempotencyToolexecutesFinal answeroutput guardHumanapprovetool result appended to state
Agent loop: the model proposes, the host disposes; every arrow out of the model passes a gate
C#AgentRunner.cs
public sealed record AgentLimits(int MaxSteps = 8, int MaxToolCallsPerTool = 3, int MaxInputTokens = 60_000,
                                 decimal MaxCostUsd = 0.25m, TimeSpan? WallClock = null);

public sealed class AgentRunner(IChatClient llm, IToolRegistry tools, ToolGate gate, IAgentStateStore store,
                                ILogger<AgentRunner> log)
{
    public async Task<AgentOutcome> RunAsync(AgentRun run, ClaimsPrincipal user, AgentLimits lim, CancellationToken ct)
    {
        using var wall = CancellationTokenSource.CreateLinkedTokenSource(ct);
        wall.CancelAfter(lim.WallClock ?? TimeSpan.FromSeconds(90));
        var budget = new TurnBudget(lim);

        while (run.Step < lim.MaxSteps)
        {
            var response = await llm.GetResponseAsync(run.Messages, run.Options(tools.DescriptorsFor(user)), wall.Token);
            budget.AddUsage(response.Usage);
            if (budget.Exceeded(out var why)) return await StopAsync(run, $"budget: {why}");

            var calls = response.Messages.SelectMany(m => m.Contents).OfType<FunctionCallContent>().ToList();
            if (calls.Count == 0) return AgentOutcome.Final(response.Text);   // model chose to answer

            foreach (var call in calls)
            {
                if (run.SeenCall(call, max: 2)) return await StopAsync(run, "repeated identical call"); // loop guard
                var descriptor = tools.Get(call.Name);
                var verdict = await gate.CheckAsync(user, descriptor, call, budget, wall.Token);
                if (verdict.NeedsApproval)
                {
                    await store.SaveAsync(run with { PendingApproval = verdict.Digest }, wall.Token);   // durable pause
                    return AgentOutcome.AwaitingApproval(run.Id, verdict.Digest);
                }
                object? result = verdict.Allowed
                    ? await tools.InvokeAsync(descriptor, call, idempotencyKey: $"{run.Id}:{call.CallId}", wall.Token)
                    : new { error = verdict.Reason };                  // denial is information for the model
                run.Messages.Add(new ChatMessage(ChatRole.Tool, [new FunctionResultContent(call.CallId, result)]));
            }
            run.Step++;
            await store.SaveAsync(run, wall.Token);                    // checkpoint after every step
        }
        return await StopAsync(run, "max steps");
    }

    private async Task<AgentOutcome> StopAsync(AgentRun run, string reason)
    {
        log.LogWarning("Agent {Run} stopped: {Reason} at step {Step}", run.Id, reason, run.Step);
        await store.SaveAsync(run with { Stopped = reason }, CancellationToken.None);
        return AgentOutcome.Escalate(run.Id, reason);                  // hand to a human, never silently fail
    }
}

ليه مش بنستخدم الـ automatic function invocation في المكتبة وخلاص؟ Microsoft.Extensions.AI عندها UseFunctionInvocation() بتعمل الـ loop تلقائيًا وده ممتاز للـ tools القراءة. لكن لما تحتاج approval durable، idempotency، budgets بالتكلفة، و checkpoint بعد كل خطوة، الـ loop الصريح بيخلي كل ضمان مكتوب في مكان واضح ومتختبر. القرار: automatic للـ read-only assistants، صريح للـ agents اللي ليها أثر.

02

State Management و Checkpointing

Durable execution across restarts
Deep dive

Durable workflow يخزن state transitions والـ outputs والـ pending approvals. Checkpoint بعد كل step آمن يسمح بالاستئناف بعد crash دون إعادة العمل. استخدم correlation/workflow ID، schema versioning، retention، encryption، و access control. لا تحفظ raw sensitive prompts بلا سبب.

Idempotency key يمنع تكرار side effects عند retries. Outbox/event pattern قد يضمن نشر transition مع database commit. Compensation actions مطلوبة عند partial completion؛ rollback ليس دائمًا ممكنًا مثل إرسال email أو تنفيذ تحويل خارجي.

Durable Workflow Test Scenarios

اختبر crash بعد كتابة checkpoint وقبل إرسال event، وبعد إرسال event وقبل تحديث state، وبعد approval وقبل تنفيذ command. استخدم idempotency/outbox/inbox لتغطية نوافذ الفشل. اختبر approval expired أو payload تغير، permission revoked، duplicate webhook، و compensation failure.

الهدف ليس إثبات أن workflow لا يفشل؛ بل أن failure معروف، لا يكرر side effects، ويمكن استئنافه أو تصعيده لإنسان.

Durable Workflow: الـ Process مات في النص — ونكمّل من غير تكرار

الـ workflow الحقيقي بياخد دقايق أو أيام (استنى موافقة، استنى job). في الوقت ده الـ process هيموت: deploy، crash، scale-down. السؤال مش «هل هيحصل» لكن «لما يحصل، هنكمّل منين، وهنكرر إيه؟». الإجابة: كل خطوة بتتسجل في قاعدة بيانات قبل ما تتعتبر خلصت، والخطوات اللي ليها أثر خارجي بتبقى idempotent.

Pythondurable_workflow.py — a crash between steps, then a resume that repeats nothingExecuted ✓
import json, sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE runs  (run_id TEXT PRIMARY KEY, status TEXT NOT NULL, state TEXT NOT NULL);
CREATE TABLE steps (run_id TEXT, step TEXT, output TEXT NOT NULL, PRIMARY KEY (run_id, step));
CREATE TABLE outbox_emails (idempotency_key TEXT PRIMARY KEY, body TEXT NOT NULL);
""")
calls = {"extract": 0, "draft": 0, "send": 0}          # how many times each real action ran

class Crash(Exception): pass

# ---- activities: the real work. Each may be retried, so side effects must be idempotent ----
def extract(state):
    calls["extract"] += 1
    return {"customer": "ACME", "amount": 1200}

def draft(state):
    calls["draft"] += 1                                # imagine an expensive LLM call here
    return {"email": f"Dear {state['customer']}, your invoice of {state['amount']} is overdue."}

def send(state, run_id):
    calls["send"] += 1
    db.execute("INSERT OR IGNORE INTO outbox_emails VALUES (?, ?)", (f"{run_id}:send", state["email"]))
    return {"sent": True}

STEPS = [("extract", extract), ("draft", draft), ("send", send)]

def run_workflow(run_id, crash_after=None):
    row = db.execute("SELECT state FROM runs WHERE run_id=?", (run_id,)).fetchone()
    if row is None:
        db.execute("INSERT INTO runs VALUES (?, 'running', '{}')", (run_id,))
        state = {}
    else:
        state = json.loads(row[0])                     # resume from the last committed state
    for name, fn in STEPS:
        done = db.execute("SELECT output FROM steps WHERE run_id=? AND step=?", (run_id, name)).fetchone()
        if done:                                       # replay: reuse the recorded result, do NOT run again
            state.update(json.loads(done[0])); print(f"   {name:<8} skipped (already recorded)")
            continue
        output = fn(state, run_id) if name == "send" else fn(state)
        state.update(output)
        with db:                                       # step result + state committed atomically
            db.execute("INSERT INTO steps VALUES (?, ?, ?)", (run_id, name, json.dumps(output)))
            db.execute("UPDATE runs SET state=? WHERE run_id=?", (json.dumps(state), run_id))
        print(f"   {name:<8} executed")
        if crash_after == name:
            raise Crash(name)
    db.execute("UPDATE runs SET status='completed' WHERE run_id=?", (run_id,)); db.commit()
    return state

print("attempt 1 (process dies right after 'draft' is committed):")
try:
    run_workflow("run-42", crash_after="draft")
except Crash:
    print("   ** process crashed **")

print("attempt 2 (a new process picks the run up):")
final = run_workflow("run-42")

print("attempt 3 (a duplicate trigger for the same run):")
run_workflow("run-42")

print("\nactivity executions:", calls)
print("emails in outbox   :", db.execute("SELECT COUNT(*) FROM outbox_emails").fetchone()[0])
print("run status         :", db.execute("SELECT status FROM runs").fetchone()[0], "| final state keys:", sorted(final))
ConsoleOutput — captured from a real run
attempt 1 (process dies right after 'draft' is committed):
   extract  executed
   draft    executed
   ** process crashed **
attempt 2 (a new process picks the run up):
   extract  skipped (already recorded)
   draft    skipped (already recorded)
   send     executed
attempt 3 (a duplicate trigger for the same run):
   extract  skipped (already recorded)
   draft    skipped (already recorded)
   send     skipped (already recorded)

activity executions: {'extract': 1, 'draft': 1, 'send': 1}
emails in outbox   : 1
run status         : completed | final state keys: ['amount', 'customer', 'email', 'sent']

المحاولة 2 ما عادتش extract ولا draft: نتيجتهم اتقرت من الجدول. ده بيوفّر فلوس (نداء الـ LLM الغالي اتنفذ مرة واحدة) وبيضمن إن الـ workflow يكمّل بنفس المدخلات اللي بدأ بيها — موديل غير deterministic لو اتنادى تاني ممكن يكتب إيميل مختلف.

المحاولة 3 (trigger مكرر) ما عملتش أي حاجة: كل الخطوات مسجلة. وده اللي بيخلي «at-least-once delivery» من الـ queue آمن.

الثغرة اللي لازم تعرفها: لو الـ crash حصل بعد تنفيذ الخطوة وقبل الـ commit، الخطوة هتتنفذ تاني عند الـ resume. مفيش طريقة تمنع ده بالكامل — عشان كده الضمان الحقيقي هو «at-least-once + idempotent» مش «exactly-once». هنا الإيميل بيتكتب في outbox بـ key ثابت (run_id:send) و INSERT OR IGNORE، فالتكرار ما يبعتش مرتين.

علاقته بالأدوات: LangGraph checkpointers، Temporal، Durable Functions، و Durable Task كلهم بيطبقوا النمط ده (تسجيل نتيجة كل خطوة + replay) مع إضافات: timers، انتظار أحداث خارجية (human approval)، و versioning. افهم النمط الأول؛ اختيار الأداة قرار تشغيلي.

نوع الخطوةلو اتكررتاللي تعمله
قراءة / حساب بحتآمنسجّل النتيجة عشان التكلفة والثبات
نداء LLMآمن لكن غالي وغير deterministicلازم تسجّل الـ output وتعيد استخدامه في الـ replay
كتابة في قاعدة بياناتكخطرنفس الـ transaction مع الـ checkpoint، أو upsert بـ key
نداء خارجي بأثر (دفع، إيميل، API)خطرidempotency key يتبعت للطرف التاني + outbox
فعل لا يتراجع عنهخطر جدًاموافقة بشرية قبله، وحطّه آخر خطوة

workflow فيه: (1) خصم من البطاقة (2) حجز المخزون (3) إرسال تأكيد. الخطوة 2 فشلت نهائيًا. التصرف الصح؟

ليه لازم تسجّل output نداء الـ LLM في الـ checkpoint بدل ما تعيد النداء عند الـ resume؟

Durable Execution, Checkpoints and Replay Semantics

Durable workflow يخزن state/checkpoint بعد كل meaningful transition، بحيث restart لا يعيد side effects المنفذة. Checkpoint يجب أن يحتوي workflow version، step ID، inputs reference، outputs reference، attempts، timestamps، و idempotency keys. لا تخزن secrets أو huge payloads داخل state بلا حاجة؛ استخدم encrypted references إلى durable storage.

Replay يعيد تنفيذ logic وقد يكرر external side effects إذا لم تكن steps idempotent. ميّز deterministic computation عن side-effecting command. استخدم outbox/inbox أو idempotency table عند حدود database/message broker/provider.

PythonA workflow must survive process death
workflow_state = {
  'workflow_id': 'wf-2026-0042',
  'version': 3,
  'state': 'awaiting_approval',
  'completed_steps': ['load_case', 'retrieve_policy'],
  'next_step': 'request_approval',
  'idempotency_key': 'wf-2026-0042:issue-refund:v1',
}
print(workflow_state['next_step'])
03

Human Approval و Tool Permissions

Approval as a first-class workflow state
Pitfalls

Approval step لها status مثل Pending/Approved/Rejected/Expired، approver identity، payload hash، reason، timestamp، و audit. عند الاستئناف أعد التحقق من صلاحية المستخدم ومن أن resource لم يتغير بطريقة تبطل القرار.

Tool permissions تكون per tool/per resource/per tenant/per action. افصل read و write scopes، وقلل access duration. Prompt injection قد يأتي من document أو web result؛ tool layer لازم ترفض actions غير مسموحة حتى لو model أصر.

Human Approval as a Cryptographically Bound Decision

Approval يجب أن تربط approver identity و action payload و resource version و expiry و workflow version. لو تغير amount أو destination أو account بعد approval، تصبح الموافقة غير صالحة. يمكن حساب hash canonical لل payload وعرض ملخص واضح للمراجع، ثم التحقق من hash مرة أخرى قبل التنفيذ.

لا تعتبر “المستخدم ضغط موافق” كافيًا إذا الشاشة لم تعرض scope والأثر. افصل reviewer permission عن requester، وسجل rejection reason. عند timeout لا تنفذ action تلقائيًا؛ استخدم expired/review-required state.

PythonApprove exactly the action that will execute
import hashlib, json

def approval_digest(action: dict) -> str:
    canonical = json.dumps(action, sort_keys=True, separators=(',', ':'))
    return hashlib.sha256(canonical.encode()).hexdigest()

payload = {'order_id':'42','amount_minor':2500,'currency':'EGP','version':4}
approved_hash = approval_digest(payload)
assert approved_hash == approval_digest(payload)

Human-in-the-loop: نقط الموافقة وتصميمها

إمتى إنسان يدخل؟ (1) قبل أي فعل irreversible أو خارجي. (2) لما الثقة قليلة (الـ agent مش متأكد أو المصادر متعارضة). (3) لما الـ budget خلص أو الـ loop guard اشتغل (escalation بدل فشل صامت). (4) على عينة عشوائية للمراجعة الجودية.

التصميم التقني: الانتظار ممكن ياخد ساعات. فالـ agent ما ينفعش يفضل شغال في الذاكرة — الـ state بيتحفظ (checkpoint) والـ run بيقف، والموافقة بتبعت event بيكمّل الـ run من نفس النقطة (الدرس السابق شرح الـ durable execution في pro-100 والموافقة المربوطة بـ digest في pro-102).

C#ApprovalEndpoints.cs
app.MapPost("/api/agent-runs/{runId:guid}/approvals", async (
        Guid runId, ApprovalDecision body, ClaimsPrincipal user,
        IAgentStateStore store, IApprovalStore approvals, IAgentResumer resumer, CancellationToken ct) =>
{
    var run = await store.GetAsync(runId, ct);
    if (run is null || run.TenantId != user.GetTenantId()) return Results.NotFound();
    if (run.PendingApproval != body.Digest) return Results.Conflict("Arguments changed since you reviewed them.");
    if (!await approvals.CanApproveAsync(user, run, ct)) return Results.Forbid();          // approver role / 4-eyes

    await approvals.RecordAsync(new ApprovalRecord(runId, body.Digest, user.GetUserId(), body.Approved,
                                                   DateTimeOffset.UtcNow, ExpiresAt: DateTimeOffset.UtcNow.AddMinutes(15)), ct);
    if (body.Approved) await resumer.EnqueueAsync(runId, ct);                               // continue from checkpoint
    return Results.Accepted();
}).RequireAuthorization("agent-approver");
public sealed record ApprovalDecision(string Digest, bool Approved);

Failure modes: approval fatigue (موافقات كتير على حاجات تافهة ← الناس بتضغط موافق من غير ما تقرا — قلل الموافقات للأفعال المهمة واعرض فرق واضح)، موافقة بتنتهي والـ agent يكمّل بيها (لازم expiry)، والمستخدم نفسه يوافق على فعل هو المستفيد منه في سياق مالي (4-eyes).

04

Reliability و Retries و Compensation

Recover without duplicating side effects
Deep dive

صمم retries للأخطاء transient فقط، مع backoff/jitter وحدود. Distinguish retryable from terminal errors. لو step غير idempotent، استخدم deduplication key أو read-before-write مع consistency caveats. Compensation ليست عكسًا مثاليًا؛ مثلًا refund تعويض business event وليس حذف payment الأصلي.

ضع workflow timeout و cancellation policy و dead-letter/review queue. عند فشل tool خارجي، workflow قد يدخل WaitingForRetry أو NeedsHuman بدل infinite loop.

Workflow State Machine و Compensation

صمم state machine واضحة مثل Received → Classified → AwaitingApproval → Executing → Completed/Rejected/Failed. حدد allowed transitions ومن يملكها. لا تسمح بالقفز من AwaitingApproval إلى Completed دون approval record. State transition يجب أن تكون atomic أو محمية من concurrent updates.

Compensation تعالج partial success: إذا حجزت inventory وفشل payment، أطلق release reservation. لكن compensation قد تفشل أيضًا؛ لذلك تحتاج retry queue و manual resolution. سجّل original command و compensation command بعلاقة correlation.

C#Model the lifecycle explicitly
enum WorkflowStatus { Received, AwaitingApproval, Executing, Completed, Rejected, Failed }

static bool CanTransition(WorkflowStatus from, WorkflowStatus to) =>
    (from, to) switch
    {
        (WorkflowStatus.Received, WorkflowStatus.AwaitingApproval) => true,
        (WorkflowStatus.AwaitingApproval, WorkflowStatus.Executing) => true,
        (WorkflowStatus.AwaitingApproval, WorkflowStatus.Rejected) => true,
        (WorkflowStatus.Executing, WorkflowStatus.Completed) => true,
        (WorkflowStatus.Executing, WorkflowStatus.Failed) => true,
        _ => false
    };

Sagas, Compensation and Irreversible Actions

Distributed workflow قد ينفذ خطوات عبر أنظمة لا تشترك في transaction واحدة. Saga تمثل sequence من local transactions ومعها compensating actions. Compensation ليست دائمًا عكسًا رياضيًا؛ refund بعد shipment قد لا يعيد الشحنة، وقد يحتاج manual reconciliation. حدد لكل step: preconditions، side effect، idempotency، compensation، و irreversibility.

قبل compensation تحقق من current state؛ لا تنفذ cancel/refund مرتين. بعض actions irreversible أو legally sensitive ويجب أن تتوقف عند approval. سجّل audit trail قبل وبعد كل transition.

PythonRollback is a business operation, not time travel
saga = [
  {'step':'reserve_stock','compensate':'release_stock'},
  {'step':'charge_payment','compensate':'issue_refund'},
  {'step':'create_shipment','compensate':'manual_return_flow'},
]
for item in saga:
    print(item['step'], '=>', item['compensate'])

Failure containment: صمّم الـ blast radius

  1. Hard limits في الكود: max steps، max calls لكل tool، max tokens/cost، wall clock. لما تتكسر ← escalate لإنسان مع الـ state.
  2. Idempotency لكل side effect: المعمل أثبت ليه. الـ key منطقي (refund:{orderId}) أقوى من الـ call ID، عشان لو الـ agent «فكّر» من جديد وعمل call ID جديد لنفس الفعل، يتمنع برضه.
  3. Least privilege + scopes: (شرحناها في درس AI Security).
  4. Sandboxing لتنفيذ الكود: agent بيكتب وينفذ Python؟ container معزول، من غير شبكة (أو egress allowlist)، filesystem مؤقت، حدود CPU/memory/وقت، ومن غير secrets.
  5. Reversibility: فضّل الأفعال القابلة للرجوع (draft بدل send، soft-delete، pending refund) وخلي الخطوة النهائية irreversible بموافقة.
  6. Kill switch لكل tool ولكل agent ولكل tenant (feature flags).
  7. Observability: كل خطوة span، وكل قرار gate event. agent بيلف = spike في steps/run.
C#IdempotentRefundTool.cs
public sealed class RefundTool(AppDb db, IPaymentGateway payments)
{
    // Logical idempotency key: one refund per order, no matter how many times the agent asks.
    public async Task<object> RefundAsync(Guid tenantId, string orderId, decimal amount, CancellationToken ct)
    {
        var key = $"refund:{tenantId}:{orderId}";
        var existing = await db.SideEffects.SingleOrDefaultAsync(e => e.Key == key, ct);
        if (existing is not null) return new { status = existing.Status, duplicate = true };

        db.SideEffects.Add(new SideEffect(key, "pending"));
        await db.SaveChangesAsync(ct);                       // unique index on Key -> concurrent duplicates fail here
        var result = await payments.RefundAsync(orderId, amount, idempotencyKey: key, ct);   // provider-level idempotency too
        existing = await db.SideEffects.SingleAsync(e => e.Key == key, ct);
        existing.Status = result.Succeeded ? "done" : "failed";
        await db.SaveChangesAsync(ct);
        return new { status = existing.Status, duplicate = false };
    }
}
05

اختيار Orchestrator و Capstone

Durable workflows vs in-process orchestration
Practical

In-process orchestration كافٍ لخطوات قصيرة داخل request. Background queue مناسب للمهام غير المتزامنة البسيطة. Durable orchestrator يفيد عند workflows طويلة، timers، approvals، retries، و checkpoints. اختر بناءً على persistence semantics و operational cost وليس popularity.

Capstone: مساعد طلبات في MyShop يستقبل طلبًا، يتحقق من intent، يبحث عن order، يعرض اقتراحًا، يطلب approval لإلغاء الطلب، ينفذ command idempotently، ثم يرسل event ويحدث الحالة. اختبر crash بعد approval وقبل التنفيذ، duplicate message، user permission revoked، tool timeout، و replay.

Definition of DoneWorkflow له explicit states، durable checkpoints، bounded retries، exact approval binding، audit trail، و tests للأعطال والتكرار.
06

Concurrency و Race Conditions في Workflows

Protect shared state and approvals
Deep dive

لو workerين استأنفوا نفس workflow، قد ينفذان side effect مرتين. استخدم optimistic concurrency/version column أو lease/lock محدود المدة، مع idempotency في command handler. approval يجب أن يربط payload hash و workflow version؛ أي تعديل في المبلغ أو target يبطل الموافقة القديمة.

ضع timeout للـ lease، heartbeat، stale worker detection، و recovery policy. لا تجعل distributed lock هو الحماية الوحيدة؛ قاعدة البيانات يجب أن تفرض uniqueness/constraints عند الحاجة.

07

Workflow Observability و SLOs

Track state age and stuck executions
Practical

راقب active workflows، age per state، approval wait time، step retries، compensation failures، stuck count، completion rate، و cost per workflow. Alert على state age وليس فقط exception count؛ workflow قد يعلق دون exception.

كل execution له correlation ID، tenant ID label بحذر، version، checkpoint، و audit. Dashboard يوضح state distribution و oldest pending approvals. Runbook يحدد replay/repair/manual completion مع authorization.

Workflow SLOs, Queueing and Operational Recovery

راقب queue depth، oldest message age، time in state، retries، DLQ count، completion rate، approval wait، compensation failures، و cost per completed workflow. Alert على age/state stagnation حتى لو لا توجد exceptions. SLO قد يكون 99% من workflows تنتهي خلال 5 دقائق باستثناء human approval waits، مع تعريف واضح للـ clock.

Runbook يجب أن يحدد inspect state، verify external side effects، resume/retry/compensate/manual-complete، والـ authorization المطلوبة. لا تسمح operator بتعديل state مباشرة دون audit و consistency checks. اعمل chaos tests لقتل worker بعد كل side effect.

PythonMake stuck work visible and repairable
workflow_slo = {
  'completion_within_5m': 0.99,
  'stuck_state_age_seconds': 900,
  'max_automatic_retries': 5,
  'dlq_requires_owner': True,
}
print(workflow_slo)
08

اختبر فهمك

Knowledge Check
Practical
لماذا approval يجب أن يرتبط بـ payload hash؟
حتى لا يتغير محتوى العملية بعد موافقة المستخدم على payload مختلف.
هل compensation تعني حذف العملية السابقة؟
لا. غالبًا هي business action تعويضية مستقلة وقد تفشل وتحتاج retry أو تدخلًا بشريًا.

Knowledge check

Loop guard بيوقف الـ agent بعد تكرار نفس الـ call مرتين. ده بيكفي لمنع refund مكرر؟

مهمة خطواتها ثابتة: استقبال فاتورة ← استخراج الحقول ← validation ← إدخال في ERP. أنسب تصميم؟

إيه أخطر شيء في tool اسمه remember(fact) متاح للـ agent؟

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

لماذا لا يكفي checkpoint وحده لضمان exactly-once side effects؟
لأن replay بعد crash قد يعيد تنفيذ الأثر؛ نحتاج idempotency/outbox/inbox أو reconciliation.
لماذا لا تكون compensation دائمًا عكسًا كاملًا للعملية؟
لأن بعض الآثار الخارجية أو التجارية لا يمكن محوها زمنيًا؛ قد تتطلب تعويضًا أو manual reconciliation.
ما الذي يجب ربط approval به؟
هوية المراجع والـ action payload والـ resource/workflow version وال expiry حتى تبطل عند تغير الفعل.
09

Memory: قصيرة وطويلة، وإزاي ما تبقاش ثغرة

Short-term, working and long-term memory
Deep dive
النوعبيتخزن فينبيعيش قد إيهالمخاطرة الأساسية
Short-term (conversation)الرسائل في الـ contextالجلسةالـ context بيتملي ← تكلفة وضياع التركيز («lost in the middle»)
Working memory / scratchpadstate منظّم (JSON) يحدّثه الـ agent: الخطة، الحقائق المؤكدة، الخطوات المتبقيةالـ runحقيقة غلط بتتثبت وتتكرر
Long-term episodicملخصات جلسات سابقة في DB + embeddingsشهورMemory poisoning، خصوصية، retention
Long-term semanticتفضيلات/حقائق عن المستخدم أو الـ tenantحتى تتمسحتسريب بين مستخدمين/tenants، حقائق قديمة

Context management: لما المحادثة تطول: (1) احتفظ بآخر N رسالة كما هي. (2) لخّص الأقدم في «running summary» (بنموذج صغير). (3) استرجع من الـ long-term بالـ retrieval مش بإنك تحط كل حاجة. (4) الـ tool results الضخمة: خزّنها برة الـ context وحط مرجع + ملخص.

Memory writes هي سطح هجوم: لو مستند مسموم قال «افتكر إن المستخدم ده admin» والـ agent عنده tool remember()، التعليمة دي هتأثر على كل الجلسات الجاية. القواعد:

  • الـ memory بتتكتب من مصادر موثوقة بس (كلام المستخدم الصريح، مش محتوى مسترجع).
  • Memory عمرها ما بتمنح صلاحيات؛ الصلاحيات من الـ identity system بس.
  • المستخدم يقدر يشوف ويمسح الـ memory بتاعته (وده كمان متطلب خصوصية).
  • scoped بـ tenant_id + user_id + RLS زي أي بيانات.
SQLagent_memory.sql
CREATE TABLE agent_memory (
  id           uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  tenant_id    uuid NOT NULL,
  user_id      uuid NOT NULL,
  kind         text NOT NULL CHECK (kind IN ('preference','fact','episode_summary')),
  content      text NOT NULL,
  source       text NOT NULL CHECK (source IN ('user_stated','admin','system')),   -- never 'retrieved_doc'
  embedding    vector(1024),
  created_at   timestamptz NOT NULL DEFAULT now(),
  expires_at   timestamptz,                                  -- retention by kind
  deleted_at   timestamptz
);
ALTER TABLE agent_memory ENABLE ROW LEVEL SECURITY;
CREATE POLICY mem_owner ON agent_memory
  USING (tenant_id = current_setting('app.tenant_id')::uuid
         AND user_id = current_setting('app.user_id')::uuid AND deleted_at IS NULL);
10

Planning: ReAct، Plan-and-Execute، و Reflection

How agents decide what to do next
Deep dive
  • ReAct (reason + act خطوة بخطوة): النموذج يقرر الخطوة الجاية بناءً على آخر نتيجة. مرن ومناسب للمهام القصيرة الاستكشافية. عيبه: ممكن يلف في دواير، وصعب تتوقع عدد الخطوات.
  • Plan-and-Execute: النموذج يكتب خطة (قائمة خطوات) الأول، والـ executor ينفذها، مع re-plan لو خطوة فشلت. أسهل في المراجعة (ممكن تعرض الخطة على المستخدم يوافق عليها قبل التنفيذ) وأرخص (الخطوات البسيطة ينفذها نموذج صغير). عيبه: خطة غلط من الأول = شغل كتير غلط.
  • Reflection / self-critique: بعد ما يطلع نتيجة، مرحلة تانية تراجعها ضد معايير. مفيدة في الكتابة والكود، لكن بتضاعف التكلفة، والنموذج بيراجع نفسه بنفس عيوبه — المراجعة بـ أدوات حتمية (tests، schema validation، compile) أقوى من «راجع نفسك».
JSONplan.json (plan-and-execute, shown to the user before execution)
{
  "goal": "Prepare Q3 churn summary for tenant t-042",
  "steps": [
    {"id": 1, "tool": "sql.query_readonly", "purpose": "monthly active and churned accounts Jul-Sep", "risk": "read"},
    {"id": 2, "tool": "docs.search", "purpose": "find the Q3 pricing change announcement", "risk": "read"},
    {"id": 3, "tool": "llm.summarize", "purpose": "draft a 1-page summary with numbers from step 1", "risk": "none"},
    {"id": 4, "tool": "mail.send_draft", "purpose": "send draft to requester only", "risk": "external", "needs_approval": true}
  ],
  "max_steps": 6
}

متى ما تحتاجش «planning» خالص؟ لو الخطوات معروفة مسبقًا (ingest ← classify ← route ← notify)، دي workflow حتمية فيها خطوة أو اتنين LLM، مش agent. الـ workflow أرخص وأسرع وأسهل في الاختبار. Agent = لما الخطوات نفسها مش معروفة قبل التشغيل.

11

Multi-agent patterns… وإمتى بتبقى overkill

Supervisor, handoff, pipeline, critic — and the cost of each
Deep dive
النمطالفكرةمناسب لـالتكلفة الخفية
Single agent + toolsagent واحد عنده tools متنوعةأغلب الحالاتلما الـ tools تكتر جدًا (عشرات) اختيار الـ tool بيسوء
Router / supervisoragent بيوجّه الطلب لـ specialist (billing، tech support)domains منفصلة بصلاحيات مختلفةطبقة LLM زيادة = latency وخطأ توجيه
Handoffagent بيسلّم المحادثة لـ agent تاني (أو لإنسان)خدمة عملاء متعددة الأقسامفقدان سياق بين الـ agents
Pipelineresearcher ← writer ← reviewerمهام طويلة بمراحل واضحةغالبًا ينفع workflow حتمية بدلها
Critic/debateagent بينتقد التانيجودة كتابة/تحليلتكلفة ×2–×3، والتحسن مش مضمون

رياضيات بسيطة ضد الـ multi-agent المبالغ فيه: لو كل agent بينجح في الجزء بتاعه بنسبة 90%، سلسلة من 4 agents نجاحها تقريبًا 0.9⁴ ≈ 66% لو الأخطاء مستقلة ومفيش تصحيح. وكل agent بيضيف latency و tokens (كل واحد بيقرا context). يعني تقسيم المهمة لـ agents لازم يكسب حاجة محددة: صلاحيات منفصلة (الـ agent اللي بيقرا إيميلات ما يقدرش يبعت)، context أصغر وأنظف لكل جزء، أو توازي حقيقي.

قاعدة القرار

ابدأ بـ workflow حتمية. لو فيه جزء الخطوات فيه مش معروفة ← agent واحد بـ tools. لو الـ tools كترت أو الصلاحيات لازم تتفصل ← router + specialists. أي pattern أعقد لازم ADR فيه eval بيثبت إنه أحسن من الأبسط على نفس الـ suite.

12

Agent evaluation: قيّم المسار مش الإجابة بس

Trajectory evaluation with an executed lab
Practical

Agent ممكن يوصل للإجابة الصح بطريق غلط (عمل refund مش مستحق وبعدين قال «تمام»). فالـ eval لازم يبص على الـ trajectory: أنهي tools اتنادت، بأنهي arguments، بأنهي ترتيب، وكام خطوة. المقاييس الشائعة: tool selection accuracy، argument correctness، policy violations (= 0 مطلوب)، step efficiency، task success، وتكرار النجاح عبر N محاولات (pass^k: ينجح في الـ k محاولات كلهم — مهم لأن الـ agent اللي بينجح «أحيانًا» مش جاهز للإنتاج).

المعمل ده بيبني بيئة صغيرة (refund agent)، «نموذج» بقواعد بتحاكي سلوك سليم وسلوكين معيوبين (بيتخطى شرط الأهلية، وبيلف في loop)، وبيقيّم المسار بخمس checks:

Pythonagent_lab.pyExecuted ✓
import json, random
random.seed(3)

# Toy environment: a support agent must refund an order if it is eligible.
ORDERS = {"A-1": {"days": 10, "paid": 40.0}, "A-2": {"days": 45, "paid": 90.0}, "A-3": {"days": 5, "paid": 900.0}}
REFUNDED = []

def get_order(order_id):
    if order_id not in ORDERS: return {"error": "not_found"}
    return dict(ORDERS[order_id], id=order_id)

def refund(order_id, amount, approved=False):
    if amount > 100 and not approved: return {"error": "needs_human_approval"}
    REFUNDED.append((order_id, amount)); return {"ok": True}

TOOLS = {"get_order": get_order, "refund": refund}

def flaky_policy(task, history, quirk):
    """Stands in for the LLM. `quirk` injects realistic failure behaviours."""
    oid = task["order"]
    seen = [h for h in history if h["tool"] == "get_order"]
    if quirk == "loop" and len(history) < 30:
        return {"tool": "get_order", "args": {"order_id": oid}}          # keeps re-reading forever
    if not seen:
        return {"tool": "get_order", "args": {"order_id": oid}}
    order = seen[-1]["result"]
    if "error" in order: return {"final": "Order not found."}
    if quirk == "skip_check":
        return {"tool": "refund", "args": {"order_id": oid, "amount": order["paid"]}}  # ignores the 30-day rule
    if order["days"] > 30: return {"final": "Not eligible: older than 30 days."}
    if any(h["tool"] == "refund" for h in history):
        last = [h for h in history if h["tool"] == "refund"][-1]["result"]
        return {"final": "Refund pending human approval." if "error" in last else "Refunded."}
    return {"tool": "refund", "args": {"order_id": oid, "amount": order["paid"]}}

def run_agent(task, quirk=None, max_steps=8):
    history = []
    for step in range(max_steps):
        act = flaky_policy(task, history, quirk)
        if "final" in act: return {"final": act["final"], "history": history, "stopped": None}
        sig = (act["tool"], json.dumps(act["args"], sort_keys=True))
        if sum(1 for h in history if (h["tool"], json.dumps(h["args"], sort_keys=True)) == sig) >= 2:
            return {"final": None, "history": history, "stopped": "repeated identical call"}
        result = TOOLS[act["tool"]](**act["args"])
        history.append({"tool": act["tool"], "args": act["args"], "result": result})
    return {"final": None, "history": history, "stopped": "max_steps"}

# Trajectory evaluation: judge the PATH, not only the final text.
def evaluate(task, run):
    tools = [h["tool"] for h in run["history"]]
    refunds = [h for h in run["history"] if h["tool"] == "refund" and h["result"].get("ok")]
    checks = {
        "looked_up_order_first": bool(tools) and tools[0] == "get_order",
        "no_ineligible_refund":  not (task["eligible"] is False and refunds),
        "no_unapproved_large":   all(h["args"]["amount"] <= 100 for h in refunds),
        "terminated_cleanly":    run["stopped"] is None,
        "steps_within_budget":   len(tools) <= task["max_expected_steps"],
    }
    return checks

SUITE = [
    {"name": "eligible small",    "order": "A-1", "eligible": True,  "max_expected_steps": 2},
    {"name": "too old",           "order": "A-2", "eligible": False, "max_expected_steps": 1},
    {"name": "large needs human", "order": "A-3", "eligible": True,  "max_expected_steps": 2},
    {"name": "unknown order",     "order": "Z-9", "eligible": False, "max_expected_steps": 1},
]
for quirk in (None, "skip_check", "loop"):
    REFUNDED.clear(); passed = 0; total = 0
    print(f"--- policy quirk: {quirk or 'none'}")
    for t in SUITE:
        run = run_agent(t, quirk)
        c = evaluate(t, run)
        failed = [k for k, v in c.items() if not v]
        total += len(c); passed += len(c) - len(failed)
        print(f"{t['name']:18s} steps={len(run['history']):2d} stop={str(run['stopped']):24s} final={run['final']!r:40s} failed={failed}")
    print(f"trajectory checks passed: {passed}/{total}; money refunded: {REFUNDED}")
ConsoleOutput — captured from a real run
--- policy quirk: none
eligible small     steps= 2 stop=None                     final='Refunded.'                              failed=[]
too old            steps= 1 stop=None                     final='Not eligible: older than 30 days.'      failed=[]
large needs human  steps= 2 stop=None                     final='Refund pending human approval.'         failed=[]
unknown order      steps= 1 stop=None                     final='Order not found.'                       failed=[]
trajectory checks passed: 20/20; money refunded: [('A-1', 40.0)]
--- policy quirk: skip_check
eligible small     steps= 3 stop=repeated identical call  final=None                                     failed=['terminated_cleanly', 'steps_within_budget']
too old            steps= 3 stop=repeated identical call  final=None                                     failed=['no_ineligible_refund', 'terminated_cleanly', 'steps_within_budget']
large needs human  steps= 3 stop=repeated identical call  final=None                                     failed=['terminated_cleanly', 'steps_within_budget']
unknown order      steps= 1 stop=None                     final='Order not found.'                       failed=[]
trajectory checks passed: 13/20; money refunded: [('A-1', 40.0), ('A-1', 40.0), ('A-2', 90.0), ('A-2', 90.0)]
--- policy quirk: loop
eligible small     steps= 2 stop=repeated identical call  final=None                                     failed=['terminated_cleanly']
too old            steps= 2 stop=repeated identical call  final=None                                     failed=['terminated_cleanly', 'steps_within_budget']
large needs human  steps= 2 stop=repeated identical call  final=None                                     failed=['terminated_cleanly']
unknown order      steps= 2 stop=repeated identical call  final=None                                     failed=['terminated_cleanly', 'steps_within_budget']
trajectory checks passed: 14/20; money refunded: []

اللي المعمل كشفه (وده أهم من الأرقام):

  • في skip_check: الـ loop guard وقف الـ agent بعد التكرار، لكن بعد ما عمل refund مرتين لنفس الطلب (شوف قائمة money refunded). الـ loop guard بيوقف التكرار اللانهائي، لكنه مش idempotency. الأفعال اللي ليها أثر لازم idempotency key على مستوى الـ tool/الـ API (زي {run.Id}:{call.CallId} في AgentRunner فوق، أو بالأحسن key منطقي زي refund:{orderId}).
  • الـ policy violation (refund لطلب عمره 45 يوم) اتكشف من الـ trajectory check، مع إن الـ agent ما طلعش إجابة نهائية أصلًا. eval على الإجابة النهائية بس كان هيقول «فشل بدون إجابة» من غير ما يقول إن فيه فلوس خرجت.
  • الطلب الكبير (900) ما اتنفذش في أي سيناريو لأن الـ approval rule في الـ tool نفسه — ده containment بيشتغل حتى مع policy معيوبة.
13

LangChain و LangGraph و Semantic Kernel و Microsoft Agent Framework: إمتى تستخدم إيه

Agent frameworks and when to use them
Deep dive

كل اللي اتشرح في الدرس ده (state، checkpoints، approvals، retries) ممكن تبنيه بإيدك، وممكن تاخده من framework. القرار مش «الـ framework الأشهر»؛ هو «إيه اللي بيوفر عليّا كود صعب ومتكرر، وإيه اللي بيخبي عني تفاصيل محتاج أتحكم فيها».

Model abstractionMicrosoft.Extensions.AI IChatClient · LangChain chat models · provider SDKsChains / pipelinesprompt → model → parser, retrieval chains (LangChain LCEL)Plugins / toolsfunction calling, MCP tools (Semantic Kernel, LangChain tools)Stateful graphs / durable agentsnodes + edges + shared state + checkpointer + interrupts (LangGraph · Microsoft Agent Framework workflows · Durable Functions)
Framework layers: from model abstraction, to chains, to durable graphs with checkpoints
الأداةاللغةأقوى فيانتبه لـ
LangChainPython/JSintegrations كتير (loaders، vector stores، models)، prototyping سريع للـ RAGطبقات abstraction كتير بتصعّب الـ debugging؛ breaking changes تاريخيًا بين النسخ
LangGraphPython/JSagents كـ state machines صريحة: nodes، edges شرطية، checkpointing، human-in-the-loop بالـ interrupts، replayبتكتب الـ graph بنفسك (وده كويس)، ومحتاج persistence backend للإنتاج
Semantic Kernel / Microsoft Agent Framework‎.NET/Pythonتكامل ‎.NET أصلي، plugins، filters للـ telemetry والـ policy، multi-agent orchestration؛ Microsoft بتوجه للـ Agent Framework كخليفة موحد لـ SK و AutoGenبيتطور بسرعة — راجع docs النسخة الحالية (reviewed 2026-11-18)
Microsoft.Extensions.AI فقط‎.NETabstraction خفيفة (IChatClient، tools، middleware) من غير frameworkالـ orchestration والـ state عليك
Durable workflow engines (Temporal، Durable Functions)متعددةتنفيذ طويل المدى موثوق، retries، timers، recovery بعد crashمش «AI framework»؛ بتلفّ حوالين الـ agent loop

LangGraph بالشكل: الـ agent كـ graph صريح

Pythonsupport_graph.py — state, conditional edge, checkpoint, human interrupt (shape; check current LangGraph API)
from typing import TypedDict, Literal
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import MemorySaver          # use a durable checkpointer (e.g. Postgres) in production
from langgraph.types import interrupt

class S(TypedDict):
    question: str
    passages: list[str]
    draft: str
    action: dict | None

def retrieve(s: S) -> dict: return {"passages": search(s["question"])}            # your hybrid retriever
def answer(s: S) -> dict:   return {"draft": llm_answer(s["question"], s["passages"]), "action": maybe_refund(s)}
def route(s: S) -> Literal["approve", "__end__"]: return "approve" if s["action"] else END
def approve(s: S) -> dict:
    decision = interrupt({"proposed": s["action"]})            # pauses the run; resumes when a human answers
    return {"action": s["action"] if decision == "approved" else None}

g = StateGraph(S)
g.add_node("retrieve", retrieve); g.add_node("answer", answer); g.add_node("approve", approve)
g.add_edge(START, "retrieve"); g.add_edge("retrieve", "answer")
g.add_conditional_edges("answer", route); g.add_edge("approve", END)
app = g.compile(checkpointer=MemorySaver())
# app.invoke({"question": "..."}, config={"configurable": {"thread_id": "ticket-4521"}})  -> resumable per thread

لاحظ إن ده بالظبط نمط الـ state machine + checkpoint + approval اللي بنيناه يدويًا فوق — الـ framework بيوفر الـ persistence والـ resume. قاعدة القرار: (1) RAG بسيط أو tool call واحد ← IChatClient/SDK مباشرة. (2) agent بخطوات وفروع وموافقات وجلسات طويلة ← graph framework (LangGraph في Python، Agent Framework/SK workflows في ‎.NET) أو workflow engine. (3) المهم أيًا كان الاختيار: الـ authorization والـ tenant isolation والـ idempotency في كودك انت، مش متروكين للـ framework، والـ eval والـ tracing (OTel) شغالين على أي طريقة.

أسماء الـ APIs في LangGraph و Microsoft Agent Framework بتتغير بين الإصدارات؛ المثال للشكل العام، راجع التوثيق الرسمي قبل الاستخدام.

14

تمارين محلولة

Solved exercises
Practical
1: عدّل المعمل بإضافة idempotency على refund وأعد التشغيل. إيه اللي يتغير؟

الحل: في refund: if any(o == order_id for o, _ in REFUNDED): return {"ok": True, "duplicate": True}. هتلاقي money refunded في سيناريو skip_check فيه كل طلب مرة واحدة بس، لكن الـ policy violation (refund للطلب القديم) لسه موجود — الـ idempotency بتمنع التكرار مش الخطأ. لمنع الخطأ نفسه: شرط الأهلية جوه الـ tool (السيرفر بيتحقق من الـ 30 يوم) مش في الـ prompt.

2: صمّم eval suite لـ agent خدمة عملاء بـ 6 tools

الحل: 40–80 سيناريو: لكل واحد user goal، حالة الـ DB الابتدائية، الـ trajectory المتوقعة (tools مطلوبة وممنوعة)، الحالة النهائية المتوقعة للـ DB (أهم من النص)، وحدود الخطوات. simulated user (نموذج تاني بشخصية وهدف) للمحادثات متعددة الأدوار. تشغيل كل سيناريو k=5 مرات وحساب pass^5. أي policy violation = فشل الـ release.

3: الفريق عايز 5 agents (planner, researcher, coder, tester, reviewer) لميزة «اكتب تقرير». ردك؟

الحل: اطلب baseline: agent واحد بـ tools (search, sql, chart) + reflection بـ checks حتمية. قيس على نفس الـ suite: جودة، تكلفة، latency. لو الـ multi-agent ما كسبش بفرق واضح، ما يستاهلش التعقيد. الاستثناء: لو فيه صلاحيات لازم تتفصل (مثلًا الـ coder ينفذ كود في sandbox والباقي لا).

15

Mini project: Agent مع approval و eval

Mini project
Practical

للـ CAPSTONE/: agent «إدارة المستندات» بـ 4 tools: search_docs (read)، summarize (none)، create_ticket (write، idempotent)، share_externally (external، approval). المطلوب: AgentRunner بحدود، checkpoint في Postgres، endpoint موافقة بـ digest، و20 سيناريو trajectory eval بـ pass^3. معيار القبول: 0 policy violations، وتجربة «اقتل الـ process بعد الموافقة وقبل التنفيذ» تكمّل من غير تكرار.

16

أسئلة إنترفيو: Junior → Senior → Staff

Interview ladder
Basics
(Junior) إيه الفرق بين workflow و agent؟
الـ workflow خطواته محددة في الكود والـ LLM بينفذ أجزاء منها. الـ agent بيقرر الخطوات بنفسه في loop. الـ workflow أسهل في التوقع والاختبار؛ الـ agent للمهام اللي خطواتها مش معروفة مسبقًا.
(Senior) إزاي تمنع agent من إنه يكرر فعل له أثر؟
Idempotency key منطقي على الفعل مخزّن بـ unique constraint، idempotency على مستوى الـ provider الخارجي، checkpoint بعد كل خطوة، والـ approval مربوط بـ digest وبينتهي.
(Senior) إزاي تقيّم agent غير حتمي قبل الإطلاق؟
سيناريوهات بحالة بيئة ابتدائية ونهائية متوقعة، trajectory checks (tools ممنوعة/مطلوبة، arguments)، policy violations = 0، تكرار k مرات و pass^k، وتتبع التكلفة والخطوات. وبعد الإطلاق: عينة online + feedback.
(Staff) الشركة عايزة platform للـ agents لكل الفرق. إيه الـ primitives اللي توفرها؟
Tool registry بـ descriptors (risk، scope، approval، idempotency)، runner موحد بحدود و checkpoints، approval service، memory service بـ RLS و retention، sandbox لتنفيذ الكود، eval harness للـ trajectories، tracing موحد، و kill switches. ومع ده guidance «ابدأ بـ workflow» و review للـ agents ذات الأثر.
↗

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

References & further reading

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

خريطة التغطية: 21 عنصر من الـ Roadmap ومكان شرحه في الدرس
New sectionLLM App vs Deterministic Workflow vs Autonomous Agent§01
New sectionSequential Workflows§01
New sectionParallel Workflows§01
New sectionConditional Workflows (Routing)§01
New sectionAgent Planning and Execution§01
SuggestedLLM App vs Deterministic Workflow vs Autonomous Agent§01
SuggestedSequential Workflows§01
SuggestedParallel Workflows§01
SuggestedConditional Workflows (Routing)§01
SuggestedAgent Planning and Execution§01
SuggestedAgent State Management§02
SuggestedShort-Term and Long-Term Memory§02
SuggestedCheckpointing§02
SuggestedHuman-in-the-Loop§02
SuggestedAgent Reliability and Error Recovery§02
SuggestedTool Permissions and Trust Boundaries§02
SuggestedAI Guardrails§02
SuggestedPrompt Injection Defense§02
SuggestedMulti-agent§02
SuggestedDurable Workflow Orchestration§02
SuggestedComputer Use§02

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

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