0Pricing
AI Agents · درس

حلقات التأمل والنقد الذاتي

وكلاء يقيّمون مخرجاتهم بأنفسهم وينشئون اقتراحات للتحسين.

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

ما التأمل الذاتي للوكيل؟

التأمل الذاتي هو مطالبة الوكيل بتقييم مخرجه الذي أكمله للتو قبل إرجاعه إلى المستخدم، أو مباشرة بعد ذلك. وهنا يعمل الوكيل باعتباره ناقدًا لنفسه.

يحاكي هذا الطريقة التي يراجع بها الخبراء أعمالهم: مسودة ← نقد ← مراجعة. وغالبًا ما تؤدي إضافة هذه الحلقة إلى الوكلاء إلى تحسين جودة المخرجات من دون إجراء تغييرات على النموذج الأساسي.

نمط مطالبة التأمل

بعد أن ينتج الوكيل استجابة، مرّر الاستجابة مرة أخرى إلى النموذج باستخدام مطالبة تأمل منظّمة. ثم يحدد النموذج نقاط الضعف ويقترح تحسينات.

import anthropic

client = anthropic.Anthropic(api_key='YOUR_API_KEY')

def reflect_on_response(task: str, response: str) -> str:
    reflection_prompt = (
        'You just completed the following task:\n\n'
        f'TASK: {task}\n\n'
        f'YOUR RESPONSE:\n{response}\n\n'
        'Please reflect on your performance by answering:\n'
        '1. What did you do well?\n'
        '2. What could be improved?\n'
        '3. What would you do differently if you had to redo this?\n'
        'Be specific and honest.'
    )
    result = client.messages.create(
        model='claude-opus-4-5',
        max_tokens=512,
        messages=[{'role': 'user', 'content': reflection_prompt}]
    )
    return result.content[0].text

مخرج التأمل المنظّم

يصعب معالجة نص التأمل غير المنظّم برمجيًا. اطلب من النموذج إنتاج تأمل منظّم بصيغة JSON حتى تتمكن من استخراج الدرجات وعناصر الإجراءات بشكل موثوق.

STRUCTURED_REFLECTION_PROMPT = '''
Reflect on the task and response above. Return ONLY valid JSON:
{
  "strengths": ["..."],
  "weaknesses": ["..."],
  "alternative_approach": "...",
  "quality_score": 0.0,
  "retry_recommended": false
}
quality_score: 0.0 (terrible) to 1.0 (excellent).
retry_recommended: true if quality_score < 0.6.
'''

import json

def structured_reflect(task: str, response: str, client) -> dict:
    prompt = f'TASK: {task}\n\nRESPONSE: {response}\n\n{STRUCTURED_REFLECTION_PROMPT}'
    result = client.messages.create(
        model='claude-opus-4-5',
        max_tokens=512,
        messages=[{'role': 'user', 'content': prompt}]
    )
    text = result.content[0].text.strip()
    # strip markdown code fences if present
    if text.startswith('```'):
        text = text.split('```')[1].lstrip('json').strip()
    return json.loads(text)

if __name__ == '__main__':
    class FakeContent:
        def __init__(self, text):
            self.text = text

    class FakeResponse:
        def __init__(self, text):
            self.content = [FakeContent(text)]

    class FakeMessages:
        def create(self, **kwargs):
            return FakeResponse(
                '{"strengths": ["clear"], "weaknesses": ["too long"], '
                '"alternative_approach": "be more concise", '
                '"quality_score": 0.7, "retry_recommended": false}'
            )

    class FakeClient:
        def __init__(self):
            self.messages = FakeMessages()

    result = structured_reflect('Summarize the article', 'A very long response...', FakeClient())
    print('quality_score:', result['quality_score'])
    print('weaknesses:', result['weaknesses'])

حلقة النقد الذاتي: إعادة المحاولة عند انخفاض الدرجة

عندما تنخفض درجة التأمل عن حد معين، أعد محاولة تنفيذ المهمة تلقائيًا باستخدام نقاط الضعف والنهج البديل الواردين في التأمل كسياق إضافي. ينشئ ذلك حلقة تحسين قائمة على التغذية الراجعة ضمن تشغيل واحد للوكيل.

def agent_with_self_critique(task: str, client, max_retries: int = 2) -> str:
    response = run_agent(task, client)

    for attempt in range(max_retries):
        reflection = structured_reflect(task, response, client)
        print(f'Attempt {attempt+1} quality: {reflection["quality_score"]:.2f}')

        if not reflection['retry_recommended']:
            break

        # Enrich the task with reflection insights
        improved_task = (
            f'{task}\n\n'
            'Previous attempt weaknesses:\n'
            + '\n'.join(f'- {w}' for w in reflection['weaknesses'])
            + f'\n\nSuggested approach: {reflection["alternative_approach"]}'
        )
        response = run_agent(improved_task, client)

    return response

def run_agent(task: str, client) -> str:
    result = client.messages.create(
        model='claude-opus-4-5',
        max_tokens=1024,
        messages=[{'role': 'user', 'content': task}]
    )
    return result.content[0].text

الذاكرة العرضية للتأملات

يكون التأمل الواحد مفيدًا لمرة واحدة؛ أما التأملات المخزّنة فتصبح ذاكرة عرضية تساعد الوكيل على التعلم عبر الجلسات. كل تأمل هو حلقة تتضمن: سياق المهمة + ما حدث + ما تعلمه الوكيل.

from datetime import datetime
from dataclasses import dataclass, asdict
from typing import Optional

@dataclass
class ReflectionEpisode:
    episode_id: str
    task_type: str          # e.g. 'summarize', 'code_review', 'translate'
    task_summary: str       # short description (not full text)
    quality_score: float
    strengths: list
    weaknesses: list
    alternative_approach: str
    timestamp: str = ''

    def __post_init__(self):
        if not self.timestamp:
            self.timestamp = datetime.utcnow().isoformat()

    def to_dict(self) -> dict:
        return asdict(self)

# Example
episode = ReflectionEpisode(
    episode_id='ep_001',
    task_type='summarize',
    task_summary='Summarize a 5-page financial report',
    quality_score=0.55,
    strengths=['Identified key figures'],
    weaknesses=['Too verbose', 'Missed conclusion'],
    alternative_approach='Lead with the executive summary first'
)
print(episode.to_dict())

تخزين التأملات بشكل دائم

خزّن حلقات التأمل في ملف JSON أو قاعدة بيانات. وعند بدء التشغيل، حمّل الحلقات الحديثة لنوع المهمة نفسه وأدرجها في السياق — فيتعلم الوكيل من أدائه السابق.

import json
import os

MEMORY_FILE = 'agent_episodic_memory.json'

def save_episode(episode: ReflectionEpisode):
    episodes = load_all_episodes()
    episodes.append(episode.to_dict())
    with open(MEMORY_FILE, 'w') as f:
        json.dump(episodes, f, indent=2)

def load_all_episodes() -> list:
    if not os.path.exists(MEMORY_FILE):
        return []
    with open(MEMORY_FILE) as f:
        return json.load(f)

def load_recent_episodes(task_type: str, n: int = 3) -> list:
    all_ep = load_all_episodes()
    matching = [e for e in all_ep if e['task_type'] == task_type]
    # Sort by timestamp descending, take most recent n
    matching.sort(key=lambda e: e['timestamp'], reverse=True)
    return matching[:n]

إدراج التأملات السابقة في السياق

قبل بدء مهمة، استرجع أحدث التأملات العرضية لنوع المهمة نفسه وأدرجها في مطالبة النظام. يعرف الوكيل الآن الأخطاء التي ارتكبها في المرة السابقة ويمكنه تجنبها استباقيًا.

def build_system_prompt_with_memory(task_type: str) -> str:
    base = 'You are a helpful AI assistant. Complete the task carefully.'
    episodes = load_recent_episodes(task_type, n=3)

    if not episodes:
        return base

    memory_block = '\n\nYour recent performance on similar tasks:\n'
    for ep in episodes:
        memory_block += (
            f'- Score {ep["quality_score"]:.2f}: '
            f'Weaknesses: {ep["weaknesses"]}. '
            f'Better approach: {ep["alternative_approach"]}\n'
        )
    memory_block += '\nApply these lessons to your current response.'
    return base + memory_block

# Before each task:
system_prompt = build_system_prompt_with_memory('summarize')
print(system_prompt[:300])

التأمل في استخدام الأدوات

تكون التأملات أكثر قيمة للوكلاء الذين يستخدمون الأدوات، إذ يمكن للوكيل أن يتأمل استراتيجية استدعاء الأدوات لديه: هل استخدم الأدوات الصحيحة، بالترتيب الصحيح، وبالمعلمات الصحيحة؟

TOOL_REFLECTION_PROMPT = '''
You completed a multi-step task using tools. Reflect on your tool usage:

Tool call log:
{tool_log}

Final result: {result}

Answer:
1. Were all tool calls necessary?
2. Were there redundant or incorrect calls?
3. What is the optimal tool sequence for this task type?

Return JSON:
{{
  "redundant_calls": [],
  "incorrect_calls": [],
  "optimal_sequence": [],
  "efficiency_score": 0.0
}}
'''

def reflect_on_tool_use(tool_log: list, result: str, client) -> dict:
    import json
    log_str = json.dumps(tool_log, indent=2)
    prompt = TOOL_REFLECTION_PROMPT.format(
        tool_log=log_str, result=result
    )
    response = client.messages.create(
        model='claude-opus-4-5',
        max_tokens=512,
        messages=[{'role': 'user', 'content': prompt}]
    )
    return json.loads(response.content[0].text)

if __name__ == '__main__':
    class FakeContent:
        def __init__(self, text):
            self.text = text

    class FakeResponse:
        def __init__(self, text):
            self.content = [FakeContent(text)]

    class FakeMessages:
        def create(self, **kwargs):
            return FakeResponse(
                '{"redundant_calls": ["search(x)"], "incorrect_calls": [], '
                '"optimal_sequence": ["search", "summarize"], "efficiency_score": 0.8}'
            )

    class FakeClient:
        def __init__(self):
            self.messages = FakeMessages()

    tool_log = [{'tool': 'search', 'args': {'q': 'x'}}, {'tool': 'search', 'args': {'q': 'x'}}]
    reflection = reflect_on_tool_use(tool_log, 'Found the answer', FakeClient())
    print('Efficiency score:', reflection['efficiency_score'])
    print('Redundant calls:', reflection['redundant_calls'])

اضمحلال الذاكرة العرضية وتشذيبها

تصبح التأملات القديمة غير ملائمة إذا تغير العالم أو حُدّث النموذج. طبّق الاضمحلال: امنح الحلقات الحديثة أوزانًا أكبر، وشذّب الحلقات الأقدم من حد معين أو ذات درجات الجودة المنخفضة جدًا (فقد تكون حالات شاذة).

from datetime import datetime, timedelta

def prune_old_episodes(
    episodes: list,
    max_age_days: int = 30,
    min_quality: float = 0.0
) -> list:
    cutoff = datetime.utcnow() - timedelta(days=max_age_days)
    kept = []
    for ep in episodes:
        ep_time = datetime.fromisoformat(ep['timestamp'])
        if ep_time >= cutoff and ep['quality_score'] >= min_quality:
            kept.append(ep)
    return kept

def weighted_episodes(episodes: list) -> list:
    now = datetime.utcnow()
    for ep in episodes:
        age_days = (now - datetime.fromisoformat(ep['timestamp'])).days
        # Recency weight: 1.0 today, halves every 7 days
        ep['weight'] = 0.5 ** (age_days / 7)
    return sorted(episodes, key=lambda e: e['weight'], reverse=True)

if __name__ == '__main__':
    now = datetime.utcnow()
    episodes = [
        {'timestamp': (now - timedelta(days=2)).isoformat(), 'quality_score': 0.9, 'content': 'recent good episode'},
        {'timestamp': (now - timedelta(days=45)).isoformat(), 'quality_score': 0.8, 'content': 'old episode'},
        {'timestamp': (now - timedelta(days=10)).isoformat(), 'quality_score': 0.3, 'content': 'low quality episode'},
    ]
    kept = prune_old_episodes(episodes, max_age_days=30, min_quality=0.5)
    print(f'Kept {len(kept)} of {len(episodes)} episodes after pruning')
    for ep in weighted_episodes(kept):
        print(f"  weight={ep['weight']:.3f} content={ep['content']}")

قياس فعالية التأمل

تتبّع ما إذا كان النقد الذاتي يحسّن النتائج فعلًا، وذلك بمقارنة درجات جودة المحاولات الأولى بدرجات المحاولات النهائية (بعد التأمل). إذا كان التحسن ضئيلًا أو سلبيًا، فقد تحتاج مطالبة التأمل إلى الضبط.

def measure_reflection_gain(run_log: list) -> dict:
    """
    run_log: list of dicts with keys 'attempt', 'quality_score'
    e.g. [{'attempt': 1, 'quality_score': 0.55}, {'attempt': 2, 'quality_score': 0.78}]
    """
    if not run_log:
        return {}

    first_score = run_log[0]['quality_score']
    best_score = max(r['quality_score'] for r in run_log)
    final_score = run_log[-1]['quality_score']

    return {
        'first_attempt_score': first_score,
        'final_score': final_score,
        'best_score': best_score,
        'absolute_gain': final_score - first_score,
        'relative_gain_pct': ((final_score - first_score) / max(first_score, 0.001)) * 100,
        'retries': len(run_log) - 1
    }

log = [
    {'attempt': 1, 'quality_score': 0.55},
    {'attempt': 2, 'quality_score': 0.78}
]
print(measure_reflection_gain(log))

ضمانات حلقة التأمل

من دون حدود، قد تعمل حلقة التأمل إلى ما لا نهاية. احرص دائمًا على فرض: حد أقصى لعدد مرات إعادة المحاولة، وحد أدنى للدرجة للخروج المبكر، وميزانية زمنية. سجّل جميع التأملات حتى تتمكن من تدقيق سلوك الحلقة.

import time

def safe_reflection_loop(
    task: str,
    client,
    max_retries: int = 3,
    quality_target: float = 0.75,
    time_budget_seconds: float = 30.0
) -> dict:
    start = time.time()
    response = run_agent(task, client)
    run_log = []

    for attempt in range(max_retries + 1):
        if time.time() - start > time_budget_seconds:
            print('Time budget exceeded, returning best result')
            break
        reflection = structured_reflect(task, response, client)
        run_log.append({'attempt': attempt + 1,
                        'quality_score': reflection['quality_score']})

        if reflection['quality_score'] >= quality_target:
            print(f'Quality target reached at attempt {attempt + 1}')
            break
        if attempt < max_retries:
            response = run_agent(task + '\n' + reflection['alternative_approach'], client)

    return {'response': response, 'run_log': run_log,
            'gain': measure_reflection_gain(run_log)}

اختبار المعرفة

ما الفائدة الرئيسية من تخزين حلقات التأمل باعتبارها ذاكرة عرضية؟

مراجعة: حلقات التأمل والنقد الذاتي

ممتاز! إليكم ما تناولتموه في هذا الدرس:

  • مطالبة التأمل: JSON منظّم يتضمن نقاط القوة، ونقاط الضعف، ودرجة الجودة، وعلامة إعادة المحاولة
  • حلقة النقد الذاتي: إعادة المحاولة عند انخفاض الدرجة، مع إثراء المهمة برؤى التأمل
  • الذاكرة العرضية: تخزين التأملات باعتبارها حلقات مؤرخة زمنيًا حسب نوع المهمة
  • إدراج الذاكرة: تحميل الحلقات الحديثة في مطالبة النظام قبل كل تشغيل
  • الضمانات: حد أقصى لإعادة المحاولات، وميزانية زمنية، وخروج مبكر عند بلوغ هدف الجودة

التالي: كيفية استخدام مسارات التنفيذ الناجحة والفاشلة لتحقيق تحسين ذاتي أعمق.

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

هل درس «حلقات التأمل والنقد الذاتي» مجاني؟

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

ماذا ستتعلم في «حلقات التأمل والنقد الذاتي»؟

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

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

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

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

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

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

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

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

  1. جمع الملاحظات وتخزينها
  2. حلقات التأمل والنقد الذاتي
  3. التحسين الذاتي القائم على مسار الإجراءات
  4. عندما يسوء التحسين الذاتي
← العودة إلى AI Agents