خطافات استدعاء LLM
توفر خطافات استدعاء LLM تحكماً دقيقاً في تفاعلات نماذج اللغة أثناء تنفيذ الوكيل. تتيح لك هذه الخطافات اعتراض استدعاءات LLM وتعديل المطالبات وتحويل الاستجابات وتنفيذ بوابات الموافقة وإضافة تسجيل أو مراقبة مخصصة.
نظرة عامة
Section titled “نظرة عامة”تُنفذ خطافات LLM في نقطتين حرجتين:
- قبل استدعاء LLM: تعديل الرسائل، التحقق من المدخلات، أو حظر التنفيذ
- بعد استدعاء LLM: تحويل الاستجابات، تنقية المخرجات، أو تعديل سجل المحادثة
أنواع الخطافات
Section titled “أنواع الخطافات”خطافات ما قبل استدعاء LLM
Section titled “خطافات ما قبل استدعاء LLM”تُنفذ قبل كل استدعاء LLM، ويمكن لهذه الخطافات:
- فحص وتعديل الرسائل المرسلة إلى LLM
- حظر تنفيذ LLM بناءً على شروط
- تنفيذ تحديد معدل أو بوابات موافقة
- إضافة سياق أو رسائل نظام
- تسجيل تفاصيل الطلب
التوقيع:
def before_hook(context: LLMCallHookContext) -> bool | None: # Return False to block execution # Return True or None to allow execution ...خطافات ما بعد استدعاء LLM
Section titled “خطافات ما بعد استدعاء LLM”تُنفذ بعد كل استدعاء LLM، ويمكن لهذه الخطافات:
- تعديل أو تنقية استجابات LLM
- إضافة بيانات وصفية أو تنسيق
- تسجيل تفاصيل الاستجابة
- تحديث سجل المحادثة
- تنفيذ تصفية المحتوى
التوقيع:
def after_hook(context: LLMCallHookContext) -> str | None: # Return modified response string # Return None to keep original response ...سياق خطاف LLM
Section titled “سياق خطاف LLM”يوفر كائن LLMCallHookContext وصولاً شاملاً لحالة التنفيذ:
class LLMCallHookContext: executor: CrewAgentExecutor # Full executor reference messages: list # Mutable message list agent: Agent # Current agent task: Task # Current task crew: Crew # Crew instance llm: BaseLLM # LLM instance iterations: int # Current iteration count response: str | None # LLM response (after hooks only)تعديل الرسائل
Section titled “تعديل الرسائل”مهم: قم دائماً بتعديل الرسائل في مكانها:
# ✅ Correct - modify in-placedef add_context(context: LLMCallHookContext) -> None: context.messages.append({"role": "system", "content": "Be concise"})
# ❌ Wrong - replaces list referencedef wrong_approach(context: LLMCallHookContext) -> None: context.messages = [{"role": "system", "content": "Be concise"}]طرق التسجيل
Section titled “طرق التسجيل”1. تسجيل الخطافات العامة
Section titled “1. تسجيل الخطافات العامة”تسجيل خطافات تنطبق على جميع استدعاءات LLM عبر جميع الأطقم:
from crewai.hooks import register_before_llm_call_hook, register_after_llm_call_hook
def log_llm_call(context): print(f"LLM call by {context.agent.role} at iteration {context.iterations}") return None # Allow execution
register_before_llm_call_hook(log_llm_call)2. التسجيل باستخدام المزخرفات
Section titled “2. التسجيل باستخدام المزخرفات”استخدم المزخرفات لصياغة أنظف:
from crewai.hooks import before_llm_call, after_llm_call
@before_llm_calldef validate_iteration_count(context): if context.iterations > 10: print("⚠️ Exceeded maximum iterations") return False # Block execution return None
@after_llm_calldef sanitize_response(context): if context.response and "API_KEY" in context.response: return context.response.replace("API_KEY", "[REDACTED]") return None3. خطافات نطاق الطاقم
Section titled “3. خطافات نطاق الطاقم”تسجيل خطافات لمثيل طاقم محدد:
@CrewBaseclass MyProjCrew: @before_llm_call_crew def validate_inputs(self, context): # Only applies to this crew if context.iterations == 0: print(f"Starting task: {context.task.description}") return None
@after_llm_call_crew def log_responses(self, context): # Crew-specific response logging print(f"Response length: {len(context.response)}") return None
@crew def crew(self) -> Crew: return Crew( agents=self.agents, tasks=self.tasks, process=Process.sequential, verbose=True )حالات الاستخدام الشائعة
Section titled “حالات الاستخدام الشائعة”1. تحديد التكرارات
Section titled “1. تحديد التكرارات”@before_llm_calldef limit_iterations(context: LLMCallHookContext) -> bool | None: max_iterations = 15 if context.iterations > max_iterations: print(f"⛔ Blocked: Exceeded {max_iterations} iterations") return False # Block execution return None2. بوابة الموافقة البشرية
Section titled “2. بوابة الموافقة البشرية”@before_llm_calldef require_approval(context: LLMCallHookContext) -> bool | None: if context.iterations > 5: response = context.request_human_input( prompt=f"Iteration {context.iterations}: Approve LLM call?", default_message="Press Enter to approve, or type 'no' to block:" ) if response.lower() == "no": print("🚫 LLM call blocked by user") return False return None3. إضافة سياق النظام
Section titled “3. إضافة سياق النظام”@before_llm_calldef add_guardrails(context: LLMCallHookContext) -> None: # Add safety guidelines to every LLM call context.messages.append({ "role": "system", "content": "Ensure responses are factual and cite sources when possible." }) return None4. تنقية الاستجابات
Section titled “4. تنقية الاستجابات”@after_llm_calldef sanitize_sensitive_data(context: LLMCallHookContext) -> str | None: if not context.response: return None
# Remove sensitive patterns import re sanitized = context.response sanitized = re.sub(r'\b\d{3}-\d{2}-\d{4}\b', '[SSN-REDACTED]', sanitized) sanitized = re.sub(r'\b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b', '[CARD-REDACTED]', sanitized)
return sanitized5. تتبع التكاليف
Section titled “5. تتبع التكاليف”import tiktoken
@before_llm_calldef track_token_usage(context: LLMCallHookContext) -> None: encoding = tiktoken.get_encoding("cl100k_base") total_tokens = sum( len(encoding.encode(msg.get("content", ""))) for msg in context.messages ) print(f"📊 Input tokens: ~{total_tokens}") return None
@after_llm_calldef track_response_tokens(context: LLMCallHookContext) -> None: if context.response: encoding = tiktoken.get_encoding("cl100k_base") tokens = len(encoding.encode(context.response)) print(f"📊 Response tokens: ~{tokens}") return None6. تسجيل التصحيح
Section titled “6. تسجيل التصحيح”@before_llm_calldef debug_request(context: LLMCallHookContext) -> None: print(f""" 🔍 LLM Call Debug: - Agent: {context.agent.role} - Task: {context.task.description[:50]}... - Iteration: {context.iterations} - Message Count: {len(context.messages)} - Last Message: {context.messages[-1] if context.messages else 'None'} """) return None
@after_llm_calldef debug_response(context: LLMCallHookContext) -> None: if context.response: print(f"✅ Response Preview: {context.response[:100]}...") return Noneإدارة الخطافات
Section titled “إدارة الخطافات”إلغاء تسجيل الخطافات
Section titled “إلغاء تسجيل الخطافات”from crewai.hooks import ( unregister_before_llm_call_hook, unregister_after_llm_call_hook)
# Unregister specific hookdef my_hook(context): ...
register_before_llm_call_hook(my_hook)# Later...unregister_before_llm_call_hook(my_hook) # Returns True if foundمسح الخطافات
Section titled “مسح الخطافات”from crewai.hooks import ( clear_before_llm_call_hooks, clear_after_llm_call_hooks, clear_all_llm_call_hooks)
# Clear specific hook typecount = clear_before_llm_call_hooks()print(f"Cleared {count} before hooks")
# Clear all LLM hooksbefore_count, after_count = clear_all_llm_call_hooks()print(f"Cleared {before_count} before and {after_count} after hooks")عرض الخطافات المسجلة
Section titled “عرض الخطافات المسجلة”from crewai.hooks import ( get_before_llm_call_hooks, get_after_llm_call_hooks)
# Get current hooksbefore_hooks = get_before_llm_call_hooks()after_hooks = get_after_llm_call_hooks()
print(f"Registered: {len(before_hooks)} before, {len(after_hooks)} after")أنماط متقدمة
Section titled “أنماط متقدمة”تنفيذ خطاف مشروط
Section titled “تنفيذ خطاف مشروط”@before_llm_calldef conditional_blocking(context: LLMCallHookContext) -> bool | None: # Only block for specific agents if context.agent.role == "researcher" and context.iterations > 10: return False
# Only block for specific tasks if "sensitive" in context.task.description.lower() and context.iterations > 5: return False
return Noneتعديلات واعية بالسياق
Section titled “تعديلات واعية بالسياق”@before_llm_calldef adaptive_prompting(context: LLMCallHookContext) -> None: # Add different context based on iteration if context.iterations == 0: context.messages.append({ "role": "system", "content": "Start with a high-level overview." }) elif context.iterations > 3: context.messages.append({ "role": "system", "content": "Focus on specific details and provide examples." }) return Noneربط الخطافات
Section titled “ربط الخطافات”# Multiple hooks execute in registration order
@before_llm_calldef first_hook(context): print("1. First hook executed") return None
@before_llm_calldef second_hook(context): print("2. Second hook executed") return None
@before_llm_calldef blocking_hook(context): if context.iterations > 10: print("3. Blocking hook - execution stopped") return False # Subsequent hooks won't execute print("3. Blocking hook - execution allowed") return Noneأفضل الممارسات
Section titled “أفضل الممارسات”- اجعل الخطافات مركزة: يجب أن يكون لكل خطاف مسؤولية واحدة
- تجنب الحسابات الثقيلة: تُنفذ الخطافات في كل استدعاء LLM
- تعامل مع الأخطاء بأناقة: استخدم try-except لمنع فشل الخطافات من كسر التنفيذ
- استخدم تلميحات الأنواع: استفد من
LLMCallHookContextلدعم أفضل في بيئة التطوير - وثّق سلوك الخطاف: خاصة لشروط الحظر
- اختبر الخطافات بشكل مستقل: اختبر الخطافات وحدوياً قبل الاستخدام في الإنتاج
- امسح الخطافات في الاختبارات: استخدم
clear_all_llm_call_hooks()بين تشغيلات الاختبار - عدّل في المكان: قم دائماً بتعديل
context.messagesفي مكانها، ولا تستبدلها
معالجة الأخطاء
Section titled “معالجة الأخطاء”@before_llm_calldef safe_hook(context: LLMCallHookContext) -> bool | None: try: # Your hook logic if some_condition: return False except Exception as e: print(f"⚠️ Hook error: {e}") # Decide: allow or block on error return None # Allow execution despite errorأمان الأنواع
Section titled “أمان الأنواع”from crewai.hooks import LLMCallHookContext, BeforeLLMCallHookType, AfterLLMCallHookType
# Explicit type annotationsdef my_before_hook(context: LLMCallHookContext) -> bool | None: return None
def my_after_hook(context: LLMCallHookContext) -> str | None: return None
# Type-safe registrationregister_before_llm_call_hook(my_before_hook)register_after_llm_call_hook(my_after_hook)استكشاف الأخطاء وإصلاحها
Section titled “استكشاف الأخطاء وإصلاحها”الخطاف لا يُنفذ
Section titled “الخطاف لا يُنفذ”- تحقق من أن الخطاف مسجل قبل تنفيذ الطاقم
- تحقق مما إذا كان خطاف سابق أرجع
False(يحظر الخطافات اللاحقة) - تأكد من أن توقيع الخطاف يطابق النوع المتوقع
تعديلات الرسائل لا تستمر
Section titled “تعديلات الرسائل لا تستمر”- استخدم التعديلات في المكان:
context.messages.append() - لا تستبدل القائمة:
context.messages = []
تعديلات الاستجابة لا تعمل
Section titled “تعديلات الاستجابة لا تعمل”- أرجع السلسلة النصية المعدلة من خطافات ما بعد
- إرجاع
Noneيحتفظ بالاستجابة الأصلية
الخاتمة
Section titled “الخاتمة”توفر خطافات استدعاء LLM إمكانيات قوية للتحكم في تفاعلات نماذج اللغة ومراقبتها في CrewAI. استخدمها لتنفيذ حواجز الأمان وبوابات الموافقة والتسجيل وتتبع التكاليف وتنقية الاستجابات. مع معالجة الأخطاء المناسبة وأمان الأنواع، تُمكّن الخطافات أنظمة وكلاء قوية وجاهزة للإنتاج.