mirror of
https://github.com/crewAIInc/crewAI.git
synced 2026-07-01 13:18:10 +00:00
Switch docs.crewai.com from navigation-only versioning (every version selector entry rendered the same docs/<lang>/* source files) to Mintlify's directory-based versioning so each version selector entry renders its own snapshot. Add an "Edge" channel under docs/edge/<lang>/* that always reflects main HEAD for unreleased work, eliminating pre-release leakage onto frozen release labels. External links to canonical /<lang>/* URLs are preserved via wildcard redirects that always land on the current default version. Layout: - docs/edge/<lang>/* rolling source (you edit here) - docs/edge/enterprise-api.*.yaml - docs/v<X.Y.Z>/<lang>/* frozen, immutable snapshots - docs/v<X.Y.Z>/enterprise-api.*.yaml - docs/images/ shared, append-only - docs/docs.json nav + redirects URLs follow the Mintlify-idiomatic shape: /edge/<lang>/<page> for Edge, /v<X.Y.Z>/<lang>/<page> for every frozen snapshot. The wildcard redirects /<lang>/:slug* -> /<default>/<lang>/:slug* keep stale links working, and every freeze rewrites them (plus all per-section/per-page redirects) so destinations always resolve to the current default without depending on a second redirect hop. Release flow integration (devtools release): - New module crewai_devtools.docs_versioning.freeze() materialises docs/v<X.Y.Z>/ from docs/edge/, rewrites openapi: refs inside the snapshot, inserts the version into every language block in docs.json, and refreshes all redirect destinations. - _update_docs_and_create_pr() in cli.py now calls that freeze during Phase 2 of devtools release. Edge changelogs are updated first (so the snapshot freeze picks them up), then the snapshot is staged alongside docs.json, branched as docs/freeze-v<X.Y.Z>, and the PR is titled [docs-freeze] docs: snapshot and changelog for v<X.Y.Z> — the title prefix the new CI guard reads. - The PR still gates tag, GitHub release, PyPI publish, and the enterprise release as before; no new PRs are added. - Pre-releases (1.X.YaN, 1.X.YbN, ...) skip the snapshot — they ride Edge — and the docs PR title omits the [docs-freeze] prefix. - docs_check (AI-generated docs scaffolding) writes to docs/edge/<lang>/* so newly-generated unreleased docs land in Edge and never accidentally touch a frozen snapshot. Migration scripts (one-shot): - scripts/docs/freeze_historical_versions.py reconstructs all 16 historical snapshots (v1.10.0 .. v1.14.7) from git tags via git archive | tar, rewriting openapi: MDX refs so each snapshot reads its own enterprise-api YAML rather than the live one. - scripts/docs/prefix_version_paths.py one-shot-migrates docs.json: rewrites every page path in 16 versioned blocks to point under docs/v<X.Y.Z>/, inserts a new Edge entry per language, tags v1.14.7 as Latest (default), prunes pages whose target file doesn't exist in the snapshot (e.g. docs/ar/ didn't exist before v1.12.0), and writes the wildcard + per-section redirects. - scripts/docs/freeze_current_edge.py is now a thin CLI wrapper around docs_versioning.freeze for manual one-off freezes (e.g. retroactively snapshotting a forgotten release). CI guards (.github/workflows/docs-snapshots.yml): - Frozen snapshots under docs/v[0-9]*/ are immutable; only PRs whose title contains [docs-freeze] (i.e. release-cut PRs generated by devtools release or the manual wrapper) may modify them. - Images under docs/images/ are append-only since snapshots share a single image directory. Deleting or renaming an image breaks every historical snapshot that still references it. Restored docs/images/crewai-otel-export.png from PR #3673; it was deleted in PR #4908 but v1.10.0 / v1.10.1 snapshots still reference it. Restoring instead of editing the snapshots preserves historical rendering fidelity and validates the new append-only rule retroactively. Tests: - lib/devtools/tests/test_docs_versioning.py covers the freeze: file copy, openapi rewrite, version insertion, default demotion, redirect upserts, per-section redirect rewriting, idempotency, and invalid inputs. Verified locally with mintlify broken-links: 0 broken links across the full site (Edge + 16 frozen versions, 4 locales). AGENTS.md (repo root) is the contributor guide for the new model; RELEASING.md is the release-cut runbook; README's Contribution section links to both. Co-authored-by: Cursor <cursoragent@cursor.com>
481 lines
16 KiB
Plaintext
481 lines
16 KiB
Plaintext
---
|
|
title: خطافات استدعاء الأدوات
|
|
description: تعلم كيفية استخدام خطافات استدعاء الأدوات لاعتراض وتعديل والتحكم في تنفيذ الأدوات في CrewAI
|
|
mode: "wide"
|
|
---
|
|
|
|
توفر خطافات استدعاء الأدوات تحكماً دقيقاً في تنفيذ الأدوات أثناء عمليات الوكيل. تتيح لك هذه الخطافات اعتراض استدعاءات الأدوات وتعديل المدخلات وتحويل المخرجات وتنفيذ فحوصات السلامة وإضافة تسجيل أو مراقبة شاملة.
|
|
|
|
## نظرة عامة
|
|
|
|
تُنفذ خطافات الأدوات في نقطتين حرجتين:
|
|
- **قبل استدعاء الأداة**: تعديل المدخلات، التحقق من المعاملات، أو حظر التنفيذ
|
|
- **بعد استدعاء الأداة**: تحويل النتائج، تنقية المخرجات، أو تسجيل تفاصيل التنفيذ
|
|
|
|
## أنواع الخطافات
|
|
|
|
### خطافات ما قبل استدعاء الأداة
|
|
|
|
تُنفذ قبل كل تنفيذ أداة، ويمكن لهذه الخطافات:
|
|
- فحص وتعديل مدخلات الأداة
|
|
- حظر تنفيذ الأداة بناءً على شروط
|
|
- تنفيذ بوابات موافقة للعمليات الخطرة
|
|
- التحقق من المعاملات
|
|
- تسجيل استدعاءات الأدوات
|
|
|
|
**التوقيع:**
|
|
```python
|
|
def before_hook(context: ToolCallHookContext) -> bool | None:
|
|
# Return False to block execution
|
|
# Return True or None to allow execution
|
|
...
|
|
```
|
|
|
|
### خطافات ما بعد استدعاء الأداة
|
|
|
|
تُنفذ بعد كل تنفيذ أداة، ويمكن لهذه الخطافات:
|
|
- تعديل أو تنقية نتائج الأداة
|
|
- إضافة بيانات وصفية أو تنسيق
|
|
- تسجيل نتائج التنفيذ
|
|
- تنفيذ التحقق من النتائج
|
|
- تحويل تنسيقات المخرجات
|
|
|
|
**التوقيع:**
|
|
```python
|
|
def after_hook(context: ToolCallHookContext) -> str | None:
|
|
# Return modified result string
|
|
# Return None to keep original result
|
|
...
|
|
```
|
|
|
|
## سياق خطاف الأداة
|
|
|
|
يوفر كائن `ToolCallHookContext` وصولاً شاملاً لحالة تنفيذ الأداة:
|
|
|
|
```python
|
|
class ToolCallHookContext:
|
|
tool_name: str # Name of the tool being called
|
|
tool_input: dict[str, Any] # Mutable tool input parameters
|
|
tool: CrewStructuredTool # Tool instance reference
|
|
agent: Agent | BaseAgent | None # Agent executing the tool
|
|
task: Task | None # Current task
|
|
crew: Crew | None # Crew instance
|
|
tool_result: str | None # Tool result (after hooks only)
|
|
```
|
|
|
|
### تعديل مدخلات الأداة
|
|
|
|
**مهم:** قم دائماً بتعديل مدخلات الأداة في مكانها:
|
|
|
|
```python
|
|
# ✅ Correct - modify in-place
|
|
def sanitize_input(context: ToolCallHookContext) -> None:
|
|
context.tool_input['query'] = context.tool_input['query'].lower()
|
|
|
|
# ❌ Wrong - replaces dict reference
|
|
def wrong_approach(context: ToolCallHookContext) -> None:
|
|
context.tool_input = {'query': 'new query'}
|
|
```
|
|
|
|
## طرق التسجيل
|
|
|
|
### 1. تسجيل الخطافات العامة
|
|
|
|
تسجيل خطافات تنطبق على جميع استدعاءات الأدوات عبر جميع الأطقم:
|
|
|
|
```python
|
|
from crewai.hooks import register_before_tool_call_hook, register_after_tool_call_hook
|
|
|
|
def log_tool_call(context):
|
|
print(f"Tool: {context.tool_name}")
|
|
print(f"Input: {context.tool_input}")
|
|
return None # Allow execution
|
|
|
|
register_before_tool_call_hook(log_tool_call)
|
|
```
|
|
|
|
### 2. التسجيل باستخدام المزخرفات
|
|
|
|
استخدم المزخرفات لصياغة أنظف:
|
|
|
|
```python
|
|
from crewai.hooks import before_tool_call, after_tool_call
|
|
|
|
@before_tool_call
|
|
def block_dangerous_tools(context):
|
|
dangerous_tools = ['delete_database', 'drop_table', 'rm_rf']
|
|
if context.tool_name in dangerous_tools:
|
|
print(f"⛔ Blocked dangerous tool: {context.tool_name}")
|
|
return False # Block execution
|
|
return None
|
|
|
|
@after_tool_call
|
|
def sanitize_results(context):
|
|
if context.tool_result and "password" in context.tool_result.lower():
|
|
return context.tool_result.replace("password", "[REDACTED]")
|
|
return None
|
|
```
|
|
|
|
### 3. خطافات نطاق الطاقم
|
|
|
|
تسجيل خطافات لمثيل طاقم محدد:
|
|
|
|
```python
|
|
@CrewBase
|
|
class MyProjCrew:
|
|
@before_tool_call_crew
|
|
def validate_tool_inputs(self, context):
|
|
# Only applies to this crew
|
|
if context.tool_name == "web_search":
|
|
if not context.tool_input.get('query'):
|
|
print("❌ Invalid search query")
|
|
return False
|
|
return None
|
|
|
|
@after_tool_call_crew
|
|
def log_tool_results(self, context):
|
|
# Crew-specific tool logging
|
|
print(f"✅ {context.tool_name} completed")
|
|
return None
|
|
|
|
@crew
|
|
def crew(self) -> Crew:
|
|
return Crew(
|
|
agents=self.agents,
|
|
tasks=self.tasks,
|
|
process=Process.sequential,
|
|
verbose=True
|
|
)
|
|
```
|
|
|
|
## حالات الاستخدام الشائعة
|
|
|
|
### 1. حواجز السلامة
|
|
|
|
```python
|
|
@before_tool_call
|
|
def safety_check(context: ToolCallHookContext) -> bool | None:
|
|
destructive_tools = [
|
|
'delete_file',
|
|
'drop_table',
|
|
'remove_user',
|
|
'system_shutdown'
|
|
]
|
|
|
|
if context.tool_name in destructive_tools:
|
|
print(f"🛑 Blocked destructive tool: {context.tool_name}")
|
|
return False
|
|
|
|
sensitive_tools = ['send_email', 'post_to_social_media', 'charge_payment']
|
|
if context.tool_name in sensitive_tools:
|
|
print(f"⚠️ Executing sensitive tool: {context.tool_name}")
|
|
|
|
return None
|
|
```
|
|
|
|
### 2. بوابة الموافقة البشرية
|
|
|
|
```python
|
|
@before_tool_call
|
|
def require_approval_for_actions(context: ToolCallHookContext) -> bool | None:
|
|
approval_required = [
|
|
'send_email',
|
|
'make_purchase',
|
|
'delete_file',
|
|
'post_message'
|
|
]
|
|
|
|
if context.tool_name in approval_required:
|
|
response = context.request_human_input(
|
|
prompt=f"Approve {context.tool_name}?",
|
|
default_message=f"Input: {context.tool_input}\nType 'yes' to approve:"
|
|
)
|
|
|
|
if response.lower() != 'yes':
|
|
print(f"❌ Tool execution denied: {context.tool_name}")
|
|
return False
|
|
|
|
return None
|
|
```
|
|
|
|
### 3. التحقق من المدخلات وتنقيتها
|
|
|
|
```python
|
|
@before_tool_call
|
|
def validate_and_sanitize_inputs(context: ToolCallHookContext) -> bool | None:
|
|
if context.tool_name == 'web_search':
|
|
query = context.tool_input.get('query', '')
|
|
if len(query) < 3:
|
|
print("❌ Search query too short")
|
|
return False
|
|
context.tool_input['query'] = query.strip().lower()
|
|
|
|
if context.tool_name == 'read_file':
|
|
path = context.tool_input.get('path', '')
|
|
if '..' in path or path.startswith('/'):
|
|
print("❌ Invalid file path")
|
|
return False
|
|
|
|
return None
|
|
```
|
|
|
|
### 4. تنقية النتائج
|
|
|
|
```python
|
|
@after_tool_call
|
|
def sanitize_sensitive_data(context: ToolCallHookContext) -> str | None:
|
|
if not context.tool_result:
|
|
return None
|
|
|
|
import re
|
|
result = context.tool_result
|
|
|
|
result = re.sub(
|
|
r'(api[_-]?key|token)["\']?\s*[:=]\s*["\']?[\w-]+',
|
|
r'\1: [REDACTED]',
|
|
result,
|
|
flags=re.IGNORECASE
|
|
)
|
|
|
|
result = re.sub(
|
|
r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b',
|
|
'[EMAIL-REDACTED]',
|
|
result
|
|
)
|
|
|
|
result = re.sub(
|
|
r'\b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b',
|
|
'[CARD-REDACTED]',
|
|
result
|
|
)
|
|
|
|
return result
|
|
```
|
|
|
|
### 5. تحليلات استخدام الأدوات
|
|
|
|
```python
|
|
import time
|
|
from collections import defaultdict
|
|
|
|
tool_stats = defaultdict(lambda: {'count': 0, 'total_time': 0, 'failures': 0})
|
|
|
|
@before_tool_call
|
|
def start_timer(context: ToolCallHookContext) -> None:
|
|
context.tool_input['_start_time'] = time.time()
|
|
return None
|
|
|
|
@after_tool_call
|
|
def track_tool_usage(context: ToolCallHookContext) -> None:
|
|
start_time = context.tool_input.get('_start_time', time.time())
|
|
duration = time.time() - start_time
|
|
|
|
tool_stats[context.tool_name]['count'] += 1
|
|
tool_stats[context.tool_name]['total_time'] += duration
|
|
|
|
if not context.tool_result or 'error' in context.tool_result.lower():
|
|
tool_stats[context.tool_name]['failures'] += 1
|
|
|
|
print(f"""
|
|
📊 Tool Stats for {context.tool_name}:
|
|
- Executions: {tool_stats[context.tool_name]['count']}
|
|
- Avg Time: {tool_stats[context.tool_name]['total_time'] / tool_stats[context.tool_name]['count']:.2f}s
|
|
- Failures: {tool_stats[context.tool_name]['failures']}
|
|
""")
|
|
|
|
return None
|
|
```
|
|
|
|
### 6. تحديد المعدل
|
|
|
|
```python
|
|
from collections import defaultdict
|
|
from datetime import datetime, timedelta
|
|
|
|
tool_call_history = defaultdict(list)
|
|
|
|
@before_tool_call
|
|
def rate_limit_tools(context: ToolCallHookContext) -> bool | None:
|
|
tool_name = context.tool_name
|
|
now = datetime.now()
|
|
|
|
tool_call_history[tool_name] = [
|
|
call_time for call_time in tool_call_history[tool_name]
|
|
if now - call_time < timedelta(minutes=1)
|
|
]
|
|
|
|
if len(tool_call_history[tool_name]) >= 10:
|
|
print(f"🚫 Rate limit exceeded for {tool_name}")
|
|
return False
|
|
|
|
tool_call_history[tool_name].append(now)
|
|
return None
|
|
```
|
|
|
|
### 7. تخزين نتائج الأدوات مؤقتاً
|
|
|
|
```python
|
|
import hashlib
|
|
import json
|
|
|
|
tool_cache = {}
|
|
|
|
def cache_key(tool_name: str, tool_input: dict) -> str:
|
|
"""Generate cache key from tool name and input."""
|
|
input_str = json.dumps(tool_input, sort_keys=True)
|
|
return hashlib.md5(f"{tool_name}:{input_str}".encode()).hexdigest()
|
|
|
|
@before_tool_call
|
|
def check_cache(context: ToolCallHookContext) -> bool | None:
|
|
key = cache_key(context.tool_name, context.tool_input)
|
|
if key in tool_cache:
|
|
print(f"💾 Cache hit for {context.tool_name}")
|
|
return None
|
|
|
|
@after_tool_call
|
|
def cache_result(context: ToolCallHookContext) -> None:
|
|
if context.tool_result:
|
|
key = cache_key(context.tool_name, context.tool_input)
|
|
tool_cache[key] = context.tool_result
|
|
print(f"💾 Cached result for {context.tool_name}")
|
|
return None
|
|
```
|
|
|
|
### 8. تسجيل التصحيح
|
|
|
|
```python
|
|
@before_tool_call
|
|
def debug_tool_call(context: ToolCallHookContext) -> None:
|
|
print(f"""
|
|
🔍 Tool Call Debug:
|
|
- Tool: {context.tool_name}
|
|
- Agent: {context.agent.role if context.agent else 'Unknown'}
|
|
- Task: {context.task.description[:50] if context.task else 'Unknown'}...
|
|
- Input: {context.tool_input}
|
|
""")
|
|
return None
|
|
|
|
@after_tool_call
|
|
def debug_tool_result(context: ToolCallHookContext) -> None:
|
|
if context.tool_result:
|
|
result_preview = context.tool_result[:200]
|
|
print(f"✅ Result Preview: {result_preview}...")
|
|
else:
|
|
print("⚠️ No result returned")
|
|
return None
|
|
```
|
|
|
|
## إدارة الخطافات
|
|
|
|
### إلغاء تسجيل الخطافات
|
|
|
|
```python
|
|
from crewai.hooks import (
|
|
unregister_before_tool_call_hook,
|
|
unregister_after_tool_call_hook
|
|
)
|
|
|
|
def my_hook(context):
|
|
...
|
|
|
|
register_before_tool_call_hook(my_hook)
|
|
success = unregister_before_tool_call_hook(my_hook)
|
|
print(f"Unregistered: {success}")
|
|
```
|
|
|
|
### مسح الخطافات
|
|
|
|
```python
|
|
from crewai.hooks import (
|
|
clear_before_tool_call_hooks,
|
|
clear_after_tool_call_hooks,
|
|
clear_all_tool_call_hooks
|
|
)
|
|
|
|
count = clear_before_tool_call_hooks()
|
|
print(f"Cleared {count} before hooks")
|
|
|
|
before_count, after_count = clear_all_tool_call_hooks()
|
|
print(f"Cleared {before_count} before and {after_count} after hooks")
|
|
```
|
|
|
|
### عرض الخطافات المسجلة
|
|
|
|
```python
|
|
from crewai.hooks import (
|
|
get_before_tool_call_hooks,
|
|
get_after_tool_call_hooks
|
|
)
|
|
|
|
before_hooks = get_before_tool_call_hooks()
|
|
after_hooks = get_after_tool_call_hooks()
|
|
|
|
print(f"Registered: {len(before_hooks)} before, {len(after_hooks)} after")
|
|
```
|
|
|
|
## أفضل الممارسات
|
|
|
|
1. **اجعل الخطافات مركزة**: يجب أن يكون لكل خطاف مسؤولية واحدة
|
|
2. **تجنب الحسابات الثقيلة**: تُنفذ الخطافات في كل استدعاء أداة
|
|
3. **تعامل مع الأخطاء بأناقة**: استخدم try-except لمنع فشل الخطافات
|
|
4. **استخدم تلميحات الأنواع**: استفد من `ToolCallHookContext` لدعم أفضل في بيئة التطوير
|
|
5. **وثّق شروط الحظر**: وضّح متى ولماذا تُحظر الأدوات
|
|
6. **اختبر الخطافات بشكل مستقل**: اختبر الخطافات وحدوياً قبل الاستخدام في الإنتاج
|
|
7. **امسح الخطافات في الاختبارات**: استخدم `clear_all_tool_call_hooks()` بين تشغيلات الاختبار
|
|
8. **عدّل في المكان**: قم دائماً بتعديل `context.tool_input` في مكانه، ولا تستبدله
|
|
9. **سجّل القرارات المهمة**: خاصة عند حظر تنفيذ الأدوات
|
|
10. **راعِ الأداء**: خزّن عمليات التحقق المكلفة مؤقتاً عند الإمكان
|
|
|
|
## معالجة الأخطاء
|
|
|
|
```python
|
|
@before_tool_call
|
|
def safe_validation(context: ToolCallHookContext) -> bool | None:
|
|
try:
|
|
if not validate_input(context.tool_input):
|
|
return False
|
|
except Exception as e:
|
|
print(f"⚠️ Hook error: {e}")
|
|
return None # Allow execution despite error
|
|
```
|
|
|
|
## أمان الأنواع
|
|
|
|
```python
|
|
from crewai.hooks import ToolCallHookContext, BeforeToolCallHookType, AfterToolCallHookType
|
|
|
|
def my_before_hook(context: ToolCallHookContext) -> bool | None:
|
|
return None
|
|
|
|
def my_after_hook(context: ToolCallHookContext) -> str | None:
|
|
return None
|
|
|
|
register_before_tool_call_hook(my_before_hook)
|
|
register_after_tool_call_hook(my_after_hook)
|
|
```
|
|
|
|
## استكشاف الأخطاء وإصلاحها
|
|
|
|
### الخطاف لا يُنفذ
|
|
- تحقق من أن الخطاف مسجل قبل تنفيذ الطاقم
|
|
- تحقق مما إذا كان خطاف سابق أرجع `False` (يحظر التنفيذ والخطافات اللاحقة)
|
|
- تأكد من أن توقيع الخطاف يطابق النوع المتوقع
|
|
|
|
### تعديلات المدخلات لا تعمل
|
|
- استخدم التعديلات في المكان: `context.tool_input['key'] = value`
|
|
- لا تستبدل القاموس: `context.tool_input = {}`
|
|
|
|
### تعديلات النتائج لا تعمل
|
|
- أرجع السلسلة النصية المعدلة من خطافات ما بعد
|
|
- إرجاع `None` يحتفظ بالنتيجة الأصلية
|
|
- تأكد من أن الأداة أرجعت نتيجة فعلاً
|
|
|
|
### أداة محظورة بشكل غير متوقع
|
|
- تحقق من جميع خطافات ما قبل بحثاً عن شروط حظر
|
|
- تحقق من ترتيب تنفيذ الخطافات
|
|
- أضف تسجيل تصحيح لتحديد الخطاف الذي يحظر
|
|
|
|
## الخاتمة
|
|
|
|
توفر خطافات استدعاء الأدوات إمكانيات قوية للتحكم في تنفيذ الأدوات ومراقبتها في CrewAI. استخدمها لتنفيذ حواجز السلامة وبوابات الموافقة والتحقق من المدخلات وتنقية النتائج والتسجيل والتحليلات. مع معالجة الأخطاء المناسبة وأمان الأنواع، تُمكّن الخطافات أنظمة وكلاء آمنة وجاهزة للإنتاج مع مراقبة شاملة.
|