0Pricing
AI Engineering Academy · درس

التصحيح الذاتي وكتابة Prompts تأملية

نفّذ خطوة تأمل يراجع فيها الوكيل مخرجاته مقابل الهدف الأصلي، ويحدد الثغرات أو الأخطاء، ويولّد خطة مصححة قبل إعادة المحاولة.

التصحيح الذاتي وكتابة Prompts تأملية درس مجاني في AI Engineering Academy على CoddyKit. هذا هو الدرس 2 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في AI Engineering Academy، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة AI Engineering Academy 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

What Is Reflective Prompting?

Reflective prompting is a technique where the agent is asked to evaluate its own output before finalizing it. Instead of producing an answer and stopping, the agent reviews its response against the original goal, identifies gaps or errors, and generates a corrected version. This mimics how humans proofread their own work and significantly improves output quality on complex tasks without requiring a separate critic model.

The Reflect-and-Revise Loop

The basic reflective loop has three steps: Generate an initial response, Critique that response against clear criteria, and Revise based on the critique. This loop can run one or more times. Each iteration improves the response until either the critique declares it satisfactory or a maximum revision count is reached. The critique step is itself an LLM call with a specialized reflection prompt.

async def reflect_and_revise(task: str, max_rounds: int = 2) -> str:
    response = await generate_initial(task)
    for round_num in range(max_rounds):
        critique = await critique_response(task, response)
        if critique.is_satisfactory:
            break
        response = await revise_response(task, response, critique.feedback)
    return response

Writing an Effective Critique Prompt

The critique prompt must specify concrete evaluation criteria rather than asking the model to simply 'improve' the response. List the specific things to check: Is every claim accurate? Did it answer all parts of the question? Is any step missing? Is there unnecessary padding? A critique prompt with explicit checklist items produces actionable feedback that the revision step can use directly.

CRITIQUE_PROMPT = '''
You are reviewing an AI-generated response to this task: {task}

Response to evaluate:
{response}

Check each criterion and provide specific feedback:
1. COMPLETENESS: Does it address all parts of the task?
2. ACCURACY: Are all factual claims correct?
3. CONCISENESS: Is there unnecessary padding or repetition?
4. FORMAT: Does it match the requested output format?
5. ACTIONABILITY: Can the user act on this response?

For each issue found, state exactly what to fix.
If the response is satisfactory on all criteria, say APPROVE.
'''

Parsing the Critique Response

Structure the critique output as a Pydantic model so you can programmatically decide whether to revise. The is_satisfactory field determines loop exit. The issues list tells the revision step exactly what to fix. The severity field lets you skip revision for minor stylistic issues while always revising for factual errors.

from pydantic import BaseModel
from typing import List, Literal

class Issue(BaseModel):
    criterion: str
    description: str
    severity: Literal['critical', 'moderate', 'minor']

class Critique(BaseModel):
    is_satisfactory: bool
    issues: List[Issue]
    overall_verdict: str

# is_satisfactory=True means no revision needed
# is_satisfactory=False means issues must be addressed

The Revision Prompt

The revision prompt receives the original task, the initial response, and the critique feedback. Ask the model to produce an improved version that specifically addresses each issue identified by the critique, while preserving the correct parts of the original response. Always include the word 'only' to prevent the model from making unnecessary changes to things the critique already approved.

def build_revision_prompt(task: str, response: str, critique: Critique) -> str:
    issues_text = '\n'.join(
        f'- [{i.severity.upper()}] {i.criterion}: {i.description}'
        for i in critique.issues
    )
    return f'''
Original task: {task}

Your previous response:
{response}

Issues to fix:
{issues_text}

Write an improved response that fixes ONLY the issues listed above.
Do not change parts that were not flagged as problems.
'''

Self-Correction for Code Generation

Self-correction is especially powerful for code generation. After generating code, run a linter or type checker on it, feed the error output back to the model, and ask it to fix the errors. This execution-grounded reflection is more reliable than language-only critique because the feedback comes from an objective tool rather than another LLM judgment.

import subprocess
import sys

async def self_correct_code(task: str, max_rounds: int = 3) -> str:
    code = await generate_code(task)
    for _ in range(max_rounds):
        # Write code to temp file and run mypy
        with open('/tmp/agent_code.py', 'w') as f:
            f.write(code)
        result = subprocess.run(
            [sys.executable, '-m', 'mypy', '/tmp/agent_code.py', '--ignore-missing-imports'],
            capture_output=True, text=True
        )
        if result.returncode == 0:
            break  # No type errors
        code = await fix_code(code, result.stdout + result.stderr)
    return code

Avoiding Overcorrection

A common failure in reflective systems is overcorrection: the model makes the original problem worse while trying to fix something else. Mitigate this by limiting the revision scope: the revision prompt should explicitly say 'do not change anything that was not flagged.' Also compare the revised response to the original using a diff-check — if the revised version is radically different, something went wrong and you should keep the original.

from difflib import SequenceMatcher

def safe_revision(original: str, revised: str, max_change_ratio: float = 0.7) -> str:
    similarity = SequenceMatcher(None, original, revised).ratio()
    if similarity < (1 - max_change_ratio):
        print(f'Revision changed too much (similarity: {similarity:.2f}). Keeping original.')
        return original
    return revised

Reflection in Multi-Step Agent Tasks

In a multi-step agent, add a reflection checkpoint after completing a set of steps — for example, after gathering all research but before writing the final report. The agent reviews what it has collected, identifies gaps, and decides whether to gather more information or proceed. This mid-task reflection prevents agents from proceeding to the synthesis step with incomplete or contradictory evidence.

async def research_with_reflection(question: str) -> str:
    # Phase 1: gather evidence
    evidence = await gather_evidence(question)

    # Reflection checkpoint
    assessment = await assess_evidence_completeness(question, evidence)
    if not assessment.is_complete:
        for gap in assessment.gaps:
            more_evidence = await targeted_search(gap.search_query)
            evidence.extend(more_evidence)

    # Phase 2: synthesize
    return await synthesize_answer(question, evidence)

Logging Reflection Outcomes

Log every reflection round: the critique scores, which issues were identified, and whether the revision actually resolved them. This data reveals whether your reflection prompts are effective. If the revised response consistently re-introduces the same issues the critique flagged, your revision prompt is not specific enough. If most critiques say 'APPROVE' on the first round, the initial generation quality is already high and reflection overhead may not be worth the cost.

import structlog

log = structlog.get_logger()

def log_reflection_round(task_id: str, round_num: int, critique: Critique, action: str):
    log.info(
        'reflection_round',
        task_id=task_id,
        round=round_num,
        is_satisfactory=critique.is_satisfactory,
        issue_count=len(critique.issues),
        critical_issues=sum(1 for i in critique.issues if i.severity == 'critical'),
        action=action  # 'approved', 'revised', 'max_rounds_reached'
    )

When to Use Reflection

Reflection adds latency and cost — a two-round reflect-and-revise at least triples the number of LLM calls for that task. Use reflection selectively: always for high-stakes outputs (code that will run, answers to consequential business questions), optionally for user-facing responses, and never for internal intermediate steps that will be immediately verified by a tool. The cost is worth it when quality matters more than speed.

# Reflection decision matrix:
# Task type:              Use reflection?
# SQL query generation    YES (run+verify)
# Final report writing    YES (review before delivery)
# Tool argument prep      NO  (tool result verifies it)
# Short factual answer    MAYBE (if accuracy is critical)
# Internal agent thought  NO   (intermediate, not final)
# Code generation         YES  (run linter/tests)

USE_REFLECTION = {'report', 'code', 'email', 'analysis'}

Measuring Reflection Effectiveness

Track whether reflection actually improves your outputs by running A/B tests: process a random 50% of tasks with reflection and 50% without, then judge both sets with your LLM judge. If the reflective group scores significantly higher (and the improvement exceeds the additional latency and cost), reflection is paying off. If scores are similar, your initial generation quality is already high enough and reflection is adding overhead without benefit.

async def reflection_ab_test(tasks: list) -> dict:
    import random
    results = {'with_reflection': [], 'without_reflection': []}
    for task in tasks:
        if random.random() < 0.5:
            response = await reflect_and_revise(task, max_rounds=2)
            group = 'with_reflection'
        else:
            response = await generate_initial(task)
            group = 'without_reflection'
        score = await judge(task, response)
        results[group].append(score.overall)
    return {
        'mean_with': sum(results['with_reflection']) / len(results['with_reflection']),
        'mean_without': sum(results['without_reflection']) / len(results['without_reflection'])
    }

Quick Check

Test your understanding of self-correction and reflective prompting in agents.

Lesson Recap

In this lesson you learned: reflect-and-revise loops improve output quality by having the agent critique and fix its own responses, concrete critique rubrics produce actionable feedback rather than vague improvement suggestions, and execution-grounded reflection with objective tools like linters is especially powerful for code generation. Next up we implement agent checkpointing and task resumption.

الأسئلة الشائعة

هل درس «التصحيح الذاتي وكتابة Prompts تأملية» مجاني؟

نعم — نص درس «التصحيح الذاتي وكتابة Prompts تأملية» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة AI Engineering Academy، انتقل إلى CoddyKit PRO. تتضمن دورة AI Engineering Academy 4 دروس في المجموع.

ماذا ستتعلم في «التصحيح الذاتي وكتابة Prompts تأملية»؟

نفّذ خطوة تأمل يراجع فيها الوكيل مخرجاته مقابل الهدف الأصلي، ويحدد الثغرات أو الأخطاء، ويولّد خطة مصححة قبل إعادة المحاولة. تتمرن على AI Engineering Academy مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ AI Engineering Academy؟

لا تُشترط خبرة سابقة. AI Engineering Academy على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 2 من أصل 4.

كم من الوقت يستغرق درس «التصحيح الذاتي وكتابة Prompts تأملية»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس AI Engineering Academy هذا؟

نعم. كل درس في AI Engineering Academy يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. تصنيف أنماط فشل الوكلاء
  2. التصحيح الذاتي وكتابة Prompts تأملية
  3. حفظ نقاط التحقق واستئناف المهام
  4. التصعيد إلى الإنسان ضمن الحلقة
← العودة إلى AI Engineering Academy