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

Generative AI وAgents وWorkflows

Generative AI, Agents and Workflows

Tool-calling loops, planning, workflows, memory, approvals, multi-agent and evaluation.

  • Professional Engineering
  • ~14 min read
  • 17 sections
  • 9 code examples
  • 1 diagrams
  • 7 questions
  • Priority L2 · Essential
  • Microsoft Agent Framework · MCP

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

  • تفرّق بين workflow ثابت وrouter وagent loop وتختار أبسط واحد يكفي.
  • تبني agent loop بـ allowlist وbudget وموافقة بشرية وidempotency.
  • تقيّم الـ agent على المسار والأمان والتكلفة مش الإجابة بس.

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

LLM Engineering (المجال 11) + قواعد بيانات + أساسيات الأنظمة الموزعة.

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

PRACTICALBuild one tool-calling assistant over your own API, with approvals for risky actions and a hard step limit.

01

LLM App vs Workflow vs Agent

Choose the least autonomous design
Deep dive

LLM app يستدعي model ضمن flow محدد. Workflow يحدد خطوات deterministic مع branching/parallelism. Agent يختار خطوات أو tools بناءً على state والنتائج. لا تستخدم agent إذا كانت قواعد العمل واضحة؛ workflow أبسط وأسهل للاختبار والتكلفة والحوكمة.

ReAct يجمع reasoning/action/observation في loop، و plan-and-execute يفصل التخطيط عن التنفيذ. هذه patterns ليست ضمانًا للصحة؛ تحتاج step limits، timeouts، tool allowlists، budgets، و state persistence.

02

الـ agent loop في رسمة

The agent loop
Deep dive

كل «agent» في الآخر حلقة: الموديل بيقرر الخطوة الجاية، الكود بينفذها بعد فحص، والنتيجة بترجع للموديل — لحد ما يوصل لإجابة أو يخلص الحد المسموح. القوة والخطر في نفس المكان: الحلقة دي ممكن تلف للأبد أو تنفذ حاجة مش مفروض.

Goaluser task + contextLLM: decideanswer or tool_call(args)Policy checkauthZ · schema · approvalExecute toolidempotent, timedObserveresult → context (as data)Stop?done · max steps · budgetloop
Agent loop: plan, call a tool through policy, observe, repeat; hard limits on steps, tokens and time
C#AgentLoop.cs: the loop with hard limits
public async Task<AgentResult> RunAsync(string goal, CancellationToken ct)
{
    var messages = new List<ChatMessage> { new(ChatRole.System, systemPrompt), new(ChatRole.User, goal) };
    for (var step = 1; step <= 8; step++)                                         // max steps: no infinite loops
    {
        var res = await chat.GetResponseAsync(messages, new ChatOptions { Tools = tools.Definitions }, ct);
        messages.AddRange(res.Messages);
        var calls = res.Messages.SelectMany(m => m.Contents.OfType<FunctionCallContent>()).ToList();
        if (calls.Count == 0) return AgentResult.Answer(res.Text, step);           // model chose to answer

        foreach (var call in calls)
        {
            var decision = await policy.EvaluateAsync(user, call, ct);              // authZ in code, not in the prompt
            object? output = decision switch
            {
                PolicyDecision.Allow => await tools.InvokeAsync(call, ct),
                PolicyDecision.NeedsApproval => await approvals.RequestAsync(user, call, ct),   // pauses the run
                _ => new { error = "not permitted" }
            };
            messages.Add(new ChatMessage(ChatRole.Tool, [new FunctionResultContent(call.CallId, output)]));
        }
        if (budget.Exceeded(messages)) return AgentResult.Stopped("budget", step);
    }
    return AgentResult.Stopped("max_steps", 8);
}

الربط: الـ approvals من AI Product Engineering، الـ tools عبر MCP، والتقييم (tool success rate، steps per task) في Agentic Workflow Engineering.

03

Tool-calling Loop و Planning

Bound the loop and validate every action
Practical

الـ loop: model proposes tool → backend validates → tool executes → result returns as untrusted observation → model continues or finishes. ضع max steps، max wall-clock duration، max tool calls، token budget، و repeated-call detection. لا تسمح للنموذج بتعديل هذه الحدود.

Planner قد ينتج خطة غير صحيحة أو متضاربة. حوّل الخطة إلى typed steps، تحقق من dependencies، واطلب clarification عند ambiguity. نفذ actions ذات side effects عبر explicit command handler وليس نص حر.

PythonBound the loop and validate every action
MAX_STEPS = 6

async def run_agent(task, tools, policy):
    state = {"task": task, "steps": [], "status": "running"}
    for _ in range(MAX_STEPS):
        proposal = await model_next_action(state)
        if proposal.kind == "final":
            return validate_final(proposal.output)
        tool = tools.get(proposal.tool_name)
        if tool is None:
            raise PermissionError("Unknown tool")
        args = tool.validate(proposal.arguments)
        await policy.authorize(proposal.tool_name, args)
        observation = await tool.execute(args)
        state["steps"].append(sanitize_observation(observation))
    raise RuntimeError("Agent step budget exceeded")
04

Memory و State و Human-in-the-Loop

Persist only what is useful and permitted
Deep dive

Short-term memory قد تكون conversation history داخل session؛ long-term memory تحتاج storage، retention، deletion، provenance، و tenant isolation. لا تخزن كل شيء تلقائيًا؛ اختر facts ذات قيمة، واسمح للمستخدم بتصحيحها أو حذفها حسب policy. State يجب أن يكون typed ومؤرخًا وقابلًا للاسترجاع.

Human-in-the-loop يوقف workflow عند خطوة عالية المخاطر: preview action، evidence، cost، identity، expiry، approve/reject. Approval يجب أن يرتبط بالـ exact payload/hash حتى لا يتغير الأمر بعد موافقة المستخدم.

05

Multi-Agent و Agent-to-Agent و Computer Use

Advanced patterns and their costs
Basics

Multi-agent يفصل أدوارًا أو يوازي مهامًا، لكنه يضاعف coordination، token cost، latency، و failure surfaces. ابدأ agent واحدًا أو workflow nodes محددة. Agent-to-agent protocols و computer-use agents تخصصات متقدمة؛ تحتاج sandbox، permissions، audit، screenshots/data handling، و human supervision.

استخدم parallel agents فقط عندما المهام مستقلة فعلًا ويمكن دمج النتائج مع conflict resolution. لا تسمح لأكثر من agent بتنفيذ نفس side effect دون idempotency/locking.

06

Agent Evaluation و Failure Recovery

Test trajectories, not just final text
Practical

قيّم task success، tool selection accuracy، argument correctness، steps count، policy violations، recovery، cost، latency، و user satisfaction. خزّن traces مع privacy controls. اختبر tool unavailable، malformed output، loop، conflicting tools، stale memory، prompt injection، approval timeout، duplicate event، و cancellation.

Recovery يجب أن يستأنف من checkpoint آمن، لا يعيد side effect بلا idempotency. استخدم deterministic workflow engine للمهام طويلة الأمد والحساسة، و agent داخل step محدود بدل تركه يتحكم في العملية كلها.

Agent Evaluation: Task Success, Cost and Safety

Agent evaluation يجب أن يفحص final task success، correctness of tool choice، argument correctness، number of steps، recovery from failures، unauthorized actions، و cost/latency. Final answer قد يبدو صحيحًا رغم أن agent استخدم tool خاطئًا أو وصل للنتيجة بالصدفة؛ لذلك قيّم trajectory/events.

استخدم simulator أو mocked tools لتغطية failures، ثم staging integration tests، ثم shadow/limited rollout. ضع hard safety invariants: zero cross-tenant access، zero unapproved write actions، bounded steps. أي violation أمني يجب ألا يعوضه average success rate.

PythonEvaluate trajectories, not just final text
agent_run = {
  'task_success': True,
  'tool_calls': 4,
  'invalid_tool_arguments': 0,
  'unauthorized_actions': 0,
  'deadline_exceeded': False,
  'estimated_cost_usd': 0.013,
}
assert agent_run['unauthorized_actions'] == 0
07

Agent Design Patterns: ReAct vs Plan/Execute

Patterns and failure modes
Deep dive

ReAct يختار action بعد كل observation، جيد للمهام التفاعلية لكن قد يطيل loop. Plan-and-execute يضع خطة ثم ينفذها؛ الخطة قد تصبح stale إذا تغير state. Router agent يصنف task إلى workflow ثابت، و multi-agent يفصل أدوارًا لكنه يحتاج coordination. اختر pattern حسب uncertainty وعدد الخطوات والـ side effects.

اجعل planning منفصلًا عن execution، و validate كل transition. لا تسمح للـ agent بتوسيع tool permissions أو تغيير policy أو تخطي approval. سجّل trajectory لا final answer فقط.

08

Agent Observability و Replay

Understand why an agent took an action
Practical

Trace لكل step: model request ID، plan version، tool name، sanitized arguments، policy decision، tool duration/result status، retry count، token usage، و checkpoint ID. Replay يجب أن يستخدم recorded observations أو sandbox؛ لا تعِد side effects الحقيقية عند replay. افصل debug traces عن audit records.

راقب average/max steps، repeated tool calls، invalid args، approval rejection، task success، abandonment، cost/task، و latency. إن زادت الخطوات دون تحسن success فراجع planner أو workflow design.

PythonUnderstand why an agent took an action
trace_step = {
  "workflow_id": "wf-42",
  "step": 3,
  "tool": "orders.get_status",
  "policy": "allow_read_own_tenant",
  "duration_ms": 84,
  "status": "succeeded",
  "checkpoint": "cp-3",
}
09

Agent Memory Governance

Memory needs provenance and deletion
Pitfalls

Memory ليست transcript دائمًا. صنفها: session context، user-approved preferences، retrieved facts، task state. لكل نوع retention و source of truth و delete/update semantics. لا تستنتج sensitive profile من محادثات عابرة ثم تحفظه دون أساس. memory stale قد تسبب قرارات خاطئة؛ أضف timestamps و confidence/provenance، واسمح بإبطالها.

افصل memory per user/tenant، وطبق ACL عند retrieval. لا تجعل memory تمنح permissions أو تتجاوز current database state.

10

Tool Failure Matrix

Recover from partial and ambiguous outcomes
Practical

صنّف tool outcomes: success، validation failure، permission denied، transient unavailable، timeout with unknown completion، و permanent failure. Timeout بعد إرسال command لا يعني أنه لم ينفذ؛ افحص idempotency key/status قبل retry. tool result يجب أن يحمل operation ID عند side effects.

عند unknown completion، أوقف loop واطلب reconciliation بدل تكرار command. ضع max tool calls لكل tool، وليس global steps فقط.

11

الـ Agent من جوه: حلقة، مش سحر

The agent loop with tool permissions, budgets, human approval and idempotency — executed
Deep dive

الـ agent في أبسط صوره حلقة: الموديل يقرر الخطوة الجاية، الكود ينفذها، النتيجة ترجع للموديل، ونكرر. كل «ذكاء» الـ agent في الموديل، وكل أمانه في الكود اللي حوالين الحلقة. الكود ده بيبني الحلقة كاملة بضوابطها، وبيستخدم موديل «مزيّف» بسكريبت ثابت عشان يتنفذ أوفلاين وتشوف الضوابط وهي بتشتغل.

النمطمين بيحدد الخطواتاستخدمه لما
Workflow ثابت (deterministic)الكود. الموديل بيملى خانات بسالخطوات معروفة مسبقًا — ده الـ default
Routerالموديل بيختار مسار من مسارات محددةأنواع طلبات مختلفة، كل نوع له workflow
Agent loopالموديل، خطوة بخطوةالمسار فعلًا مش معروف مسبقًا والمهمة تستاهل التكلفة
Multi-agentأكتر من موديل بأدوارنادرًا — لما التخصص أو العزل مبرَّر بقياس
Pythonagent_loop.py — policy-enforced tool execution around a scripted modelExecuted ✓
import json

# ---------- tools: each declares its risk level; writes need an idempotency key ----------
DB = {"orders": {"o-7": {"owner": "alice", "status": "delivered", "total": 120}}, "refunds": {}}

def get_order(user, order_id):
    o = DB["orders"].get(order_id)
    return {"error": "order not found"} if not o or o["owner"] != user else {"status": o["status"], "total": o["total"]}

def refund_order(user, order_id, amount, idempotency_key):
    if idempotency_key in DB["refunds"]:                       # retry-safe: same key => same result, no double refund
        return DB["refunds"][idempotency_key]
    o = DB["orders"].get(order_id)
    if not o or o["owner"] != user:
        return {"error": "order not found"}
    if amount > o["total"]:
        return {"error": "amount exceeds order total"}
    DB["refunds"][idempotency_key] = {"refunded": amount, "order": order_id}
    return DB["refunds"][idempotency_key]

TOOLS = {"get_order":    {"fn": get_order,    "risk": "read"},
         "refund_order": {"fn": refund_order, "risk": "write"}}

# ---------- the "model": a fixed script, so the run is reproducible offline ----------
def scripted_model(script):
    steps = iter(script)
    return lambda messages: next(steps)

# ---------- the loop: every safety property lives here, not in the prompt ----------
def run_agent(model, user, task, *, allowed, approve, max_steps=6, max_tool_calls=4):
    messages, calls, log = [{"role": "user", "content": task}], 0, []
    for step in range(1, max_steps + 1):
        action = model(messages)
        if action["type"] == "final":
            return action["text"], log
        name, args = action["tool"], action["args"]
        if name not in TOOLS or name not in allowed:           # allowlist decided by the host
            result = {"error": f"tool '{name}' is not available"}
        elif calls >= max_tool_calls:
            return "Stopped: tool-call budget exhausted.", log
        elif TOOLS[name]["risk"] == "write" and not approve(name, args):
            result = {"error": "rejected by human reviewer"}
        else:
            calls += 1
            try:
                result = TOOLS[name]["fn"](user, **args)       # `user` comes from the session, never from the model
            except TypeError as e:
                result = {"error": f"invalid arguments: {e}"}
        log.append(f"step {step}: {name}({json.dumps(args)}) -> {json.dumps(result)}")
        messages.append({"role": "tool", "name": name, "content": json.dumps(result)})   # result is DATA
    return "Stopped: step limit reached.", log

def show(title, **kw):
    answer, log = run_agent(**kw)
    print(f"--- {title}")
    for line in log:
        print("   ", line)
    print("    answer:", answer)

refund = {"type": "tool", "tool": "refund_order", "args": {"order_id": "o-7", "amount": 120, "idempotency_key": "req-1"}}
happy = [{"type": "tool", "tool": "get_order", "args": {"order_id": "o-7"}}, refund,
         {"type": "final", "text": "Your refund of 120 has been issued."}]

show("1) approved refund", model=scripted_model(happy), user="alice", task="refund o-7",
     allowed={"get_order", "refund_order"}, approve=lambda n, a: True)
show("2) the same request retried (network blip): no double refund", model=scripted_model([refund, {"type": "final", "text": "Already refunded."}]),
     user="alice", task="refund o-7", allowed={"get_order", "refund_order"}, approve=lambda n, a: True)
show("3) reviewer rejects", model=scripted_model([refund, {"type": "final", "text": "A reviewer declined the refund."}]),
     user="alice", task="refund o-7", allowed={"get_order", "refund_order"}, approve=lambda n, a: False)
show("4) read-only feature: write tool is not on the allowlist", model=scripted_model([refund, {"type": "final", "text": "I can't issue refunds here."}]),
     user="alice", task="refund o-7", allowed={"get_order"}, approve=lambda n, a: True)
show("5) another user's order", model=scripted_model([{"type": "tool", "tool": "get_order", "args": {"order_id": "o-7"}}, {"type": "final", "text": "I couldn't find that order."}]),
     user="mallory", task="status of o-7", allowed={"get_order"}, approve=lambda n, a: True)
loop = [{"type": "tool", "tool": "get_order", "args": {"order_id": "o-7"}}] * 10
show("6) a model stuck in a loop", model=scripted_model(loop), user="alice", task="status", allowed={"get_order"}, approve=lambda n, a: True)
print("refunds recorded:", len(DB["refunds"]))
ConsoleOutput — captured from a real run
--- 1) approved refund
    step 1: get_order({"order_id": "o-7"}) -> {"status": "delivered", "total": 120}
    step 2: refund_order({"order_id": "o-7", "amount": 120, "idempotency_key": "req-1"}) -> {"refunded": 120, "order": "o-7"}
    answer: Your refund of 120 has been issued.
--- 2) the same request retried (network blip): no double refund
    step 1: refund_order({"order_id": "o-7", "amount": 120, "idempotency_key": "req-1"}) -> {"refunded": 120, "order": "o-7"}
    answer: Already refunded.
--- 3) reviewer rejects
    step 1: refund_order({"order_id": "o-7", "amount": 120, "idempotency_key": "req-1"}) -> {"error": "rejected by human reviewer"}
    answer: A reviewer declined the refund.
--- 4) read-only feature: write tool is not on the allowlist
    step 1: refund_order({"order_id": "o-7", "amount": 120, "idempotency_key": "req-1"}) -> {"error": "tool 'refund_order' is not available"}
    answer: I can't issue refunds here.
--- 5) another user's order
    step 1: get_order({"order_id": "o-7"}) -> {"error": "order not found"}
    answer: I couldn't find that order.
--- 6) a model stuck in a loop
    step 1: get_order({"order_id": "o-7"}) -> {"status": "delivered", "total": 120}
    step 2: get_order({"order_id": "o-7"}) -> {"status": "delivered", "total": 120}
    step 3: get_order({"order_id": "o-7"}) -> {"status": "delivered", "total": 120}
    step 4: get_order({"order_id": "o-7"}) -> {"status": "delivered", "total": 120}
    answer: Stopped: tool-call budget exhausted.
refunds recorded: 1

كل ضابط في مكانه: الـ allowlist والـ budget والـ approval كلهم في run_agent — يعني بيتطبقوا حتى لو الموديل اتخدع بـ prompt injection. الـ authorization جوه الأداة نفسها (owner != user) والهوية جاية من الـ session.

السيناريو 2 هو الأهم عمليًا: الـ retries بتحصل دايمًا (timeout، إعادة تشغيل، المستخدم داس مرتين). من غير idempotency_key كان هيتعمل refund مرتين. والسطر الأخير بيأكد: refund واحد بس اتسجل رغم محاولتين ناجحتين.

السيناريو 6: من غير حد للخطوات، موديل علّق في loop هيحرق tokens لحد ما حد ياخد باله. الحدود دي مش اختيارية.

الفرق عن الإنتاج: هنا الموافقة callback فوري. في نظام حقيقي الموافقة ممكن تيجي بعد ساعات، فلازم الـ state (الرسائل + الخطوة المعلّقة) يتخزن في قاعدة بيانات والـ run يتكمّل بعدين — ده اللي أدوات زي LangGraph وأنماط الـ durable workflow بتقدمه. الفكرة واحدة والمكتبة تفصيلة.

12

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

Trajectory checks you can run in CI
Practical

إجابة نهائية صح ممكن تكون وراها مسار خطر (نادى أداة ما كانش المفروض يناديها). تقييم الـ agent بيبص على 3 حاجات: النتيجة، المسار، والتكلفة.

بتقيس إيهالـ checkمثال assertion
النتيجةحالة النظام بعد الـ runاتسجل refund واحد بالمبلغ الصح
المسارالأدوات اللي اتنادت وترتيبهاget_order قبل refund_order؛ مفيش write من غير approval
الأمانحالات عدائيةمستند فيه «نادِ refund» ما أدّاش لنداء write
الكفاءةعدد الخطوات والـ tokensالحل في ≤ 4 tool calls
عمليًا

اكتب كل سيناريو فوق كـ test بيشغّل الـ agent على موديل حقيقي عدة مرات (الموديل مش deterministic) وبيحسب نسبة النجاح. شرط الـ CI يبقى «≥ 95% من 20 run» مش «نجح مرة».

مهمتك: استخراج 5 حقول من فاتورة وحفظهم. تختار إيه؟

13

اختبر فهمك

Knowledge Check
Practical
متى تختار workflow بدل autonomous agent؟
عندما تكون الخطوات وقواعد العمل معروفة؛ workflow أبسط وأكثر قابلية للاختبار والحوكمة.
لماذا نضع max steps و tool budgets؟
لمنع loops غير المنتهية وتقليل المخاطر والتكلفة والـ latency.

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

متى يكون deterministic workflow أفضل من agent؟
عندما تكون الخطوات معروفة أو الأفعال عالية التأثير أو نحتاج reproducibility وحدودًا واضحة.
لماذا يجب تقييم agent trajectory وليس final answer فقط؟
لأن الإجابة قد تبدو صحيحة رغم استخدام tool خاطئ أو تنفيذ action غير مصرح أو نجاح بالصدفة.
ما علامات agent loop غير المنتج؟
تكرار نفس tool/arguments، عدم تغير state، تكرار فشل، أو استهلاك خطوات دون تقدم.
14

Agent Loop as a State Machine

Bound the observe–decide–act cycle
Deep dive

Agent loop يمكن تمثيله كحالات: receive task → select action → validate/authorize → execute tool → observe result → continue/finish/escalate. لا تجعل النموذج يتحكم وحده في termination؛ ضع max steps، max tool calls، deadline، token budget، و allowed tool set. كل transition يجب أن يسجل state and reason.

فرق بين planner و executor و policy enforcement. LLM قد يقترح action، لكن deterministic layer يقرر هل action allowed. إذا tool result ambiguous أو state changed، أعد قراءة source of truth بدل متابعة خطة قديمة.

PythonBound the observe–decide–act cycle
from enum import Enum
class State(str, Enum):
    PLAN='plan'; ACT='act'; OBSERVE='observe'; DONE='done'; ESCALATE='escalate'

MAX_STEPS = 8

def can_continue(step: int, deadline_remaining_s: float) -> bool:
    return step < MAX_STEPS and deadline_remaining_s > 0
15

Planning Strategies and When Not to Use an Agent

Deterministic workflows are often better
Deep dive

Agent مناسب عندما الخطوات تعتمد على observations غير متوقعة، والهدف يمكن تفكيكه تدريجيًا، والأدوات آمنة ومحدودة. Workflow deterministic أفضل عندما sequence معروف أو action عالي الأثر أو reproducibility ضرورية. Agent يزيد latency/cost/non-determinism و attack surface؛ لا تستخدمه لمجرد أن المهمة تتضمن LLM.

قارن single-call structured output، fixed chain، state machine، agent loop، multi-agent. ابدأ بأبسط architecture تحقق quality. أضف autonomy فقط إذا أثبت evaluation أن فائدتها تتجاوز تكلفتها ومخاطرها.

PythonDeterministic workflows are often better
architecture_choice = {
  'known_steps': 'deterministic_workflow',
  'variable_tool_sequence': 'bounded_agent',
  'high_impact_write': 'human_approval_plus_workflow',
  'simple_extraction': 'single_structured_call',
}
print(architecture_choice)
16

Tool Selection, Observation Quality and Loop Detection

Bad observations create bad plans
Deep dive

Tool result يجب أن يكون concise، typed، include status/provenance, و distinguish empty result from failure. إذا رجعت آلاف rows، لخص server-side أو paginate؛ لا ترسل raw database dump إلى context. Error messages يجب أن تساعد recovery دون كشف secrets أو internal stack traces.

Loop detection يمكن أن يراقب repeated identical tool calls/arguments، unchanged state، same failed action، و no-progress cycles. أوقف agent بعد repeated no-progress، واطلب clarification أو escalate. لا تعتبر تغيير صياغة argument تقدمًا حقيقيًا إذا business state لم يتغير.

PythonBad observations create bad plans
def is_repeated_call(history, tool_name, arguments):
    signature = (tool_name, tuple(sorted(arguments.items())))
    return signature in history

history = {('get_order', (('id', '42'),))}
print(is_repeated_call(history, 'get_order', {'id': '42'}))
17

Multi-agent و GraphRAG و A2A: أمثلة وحدود الاستخدام

Use multiple agents or graph retrieval only for a measured need
Deep dive

ابدأ بـ workflow عادي. لو المسار معروف، search → draft → validate أوضح في الاختبار من agent حر. Multi-agent يستاهل لما في تخصصات/صلاحيات منفصلة أو أعمال مستقلة تتنفذ بالتوازي، ولكل خطوة contract و budget و timeout. عدد agents مش مقياس جودة.

Pythonbounded_agent_workflow.py — deterministic contracts, no model calls
from dataclasses import dataclass

@dataclass
class Evidence:
    source_id: str
    text: str

@dataclass
class Draft:
    answer: str
    citations: list[str]

def researcher(question: str, evidence: list[Evidence]) -> Draft:
    # A production step may call a model; it receives authorized evidence only.
    return Draft("Review the cited policy before deciding.", [item.source_id for item in evidence[:2]])

def reviewer(draft: Draft, evidence: list[Evidence]) -> bool:
    allowed = {item.source_id for item in evidence}
    return bool(draft.answer.strip()) and set(draft.citations).issubset(allowed)

context = [Evidence("policy-12", "Refund reviews take five working days.")]
draft = researcher("What is the review time?", context)
if not reviewer(draft, context):
    raise ValueError("Draft failed citation validation")
print(draft)

ده mock deterministic يشرح contracts، مش multi-agent AI حقيقي ولا يثبت جودة model. في التنفيذ، سجّل input/output لكل خطوة، اقطع loop عند budget، ومرّر evidence IDs بدل نسخ مستندات كاملة. ما تعتبرش حكم نموذج ثانٍ ضمان أمان.

GraphRAG لسؤال يعتمد على العلاقات

Vector search مناسب لسؤال عن فقرة قريبة بالمعنى. Graph retrieval يضيف روابط زي Team → owns → Service → governed_by → Policy؛ يفيد لما السؤال يحتاج traversal متعدد الخطوات. احتفظ بمصدر كل edge و ACL، ولا تعامل extracted graph كحقيقة من غير تحقق. قارن الفكرة مع baseline على golden questions قبل إضافة خدمة graph.

Pythontoy_graph_retrieval.py — provenance on each edge
from collections import defaultdict, deque

edges = [
    ("Team-A", "owns", "Service-X", "org-chart-4"),
    ("Service-X", "governed_by", "Policy-7", "service-catalog-2"),
]
graph = defaultdict(list)
for source, relation, target, evidence_id in edges:
    graph[source].append((relation, target, evidence_id))

def paths(start, max_hops=2):
    queue = deque([(start, [])])
    while queue:
        node, path = queue.popleft()
        if len(path) == max_hops:
            continue
        for relation, target, evidence_id in graph[node]:
            next_path = path + [(relation, target, evidence_id)]
            yield next_path
            queue.append((target, next_path))

for path in paths("Team-A"):
    print(path)

ده traversal توضيحي، مش GraphRAG production. التطبيق يحتاج entity resolution و edge provenance و tenant filtering و evaluation للعلاقات المفقودة أو الغلط. لو join عادي على system of record يحل السؤال أسرع، استخدمه.

Agent-to-Agent Protocol

MCP يوحّد اتصال agent بأداة/مصدر بيانات. A2A يوحّد تواصل تطبيقات agents مستقلة عبر الشبكة مع discovery و messages/tasks؛ لا يقرر صلاحيات business ولا يشارك memory سرية تلقائيًا. قيّمه لما agent مستقل له مالك أو runtime أو trust boundary مختلف؛ داخل تطبيق واحد ابدأ بخدمة application أو workflow محلي.

قبل remote agent: تحقق من identity و authorization و Agent Card version؛ حدد schema و timeout و max payload؛ اعتبر الرد untrusted؛ سجّل correlation/task IDs؛ وحدد retry/idempotency للآثار الجانبية. ما تنقلش أسرار أو tenant data أكتر من الحاجة. المواصفة والـ SDKs تتغير، فراجع الإصدار الحالي.

تمارين وحلول ومشروع مصغر

أساسي: أداة send_refund فيها أثر مالي. الحل: backend authorization، عرض المبلغ للمستخدم، موافقة بشرية، idempotency و audit log؛ الرفض هو الافتراضي عند الغموض.

متوسط: «مين مالك الخدمة وما سياسة الاحتفاظ؟» هل يحتاج GraphRAG؟ الحل: قارن traversal موثوق مع joins عادية على service catalog؛ اختر الأقل تعقيدًا الذي يحقق الجودة.

متقدم: remote agent أعاد citation غير معروف. الحل: ارفضه أو علّمه unsupported، وتحقق من source id في trusted store بدل الوثوق بالرابط.

مشروع: قارن workflow بمرحلتين مع single-agent على حالات محلية. القبول: task success و cost و latency وصحة citations وصفر actions غير مصرح بها.

↗

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

References & further reading

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

خريطة التغطية: 14 عنصر من الـ Roadmap ومكان شرحه في الدرس
New sectionGenerative AI modalities: text, image, audio, code, video§01
New sectionEmbeddings and semantic search§01
New sectionThe tool-calling loop§01
New sectionAgents: ReAct, plan-and-execute§01
New sectionWorkflows vs agents (prefer the simplest)§01
New sectionMulti-step orchestration§01
New sectionMemory: short-term and long-term§04
New sectionHuman-in-the-loop approvals§04
New sectionMulti-agent patterns (awareness)§05
New sectionLoop limits and cost limits§03
New sectionMCP tools for agents§03
New sectionAgent-to-agent protocols (awareness)§04
New sectionComputer-use agents (awareness)§05
New sectionUsing agentic coding tools wisely§05

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

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