mirror of
https://github.com/crewAIInc/crewAI.git
synced 2026-04-30 23:02:50 +00:00
docs: add modern standard arabic translation of all documentation
This commit is contained in:
87
docs/ar/learn/a2a-agent-delegation.mdx
Normal file
87
docs/ar/learn/a2a-agent-delegation.mdx
Normal file
@@ -0,0 +1,87 @@
|
||||
---
|
||||
title: بروتوكول Agent-to-Agent (A2A)
|
||||
description: الـ Agents تفوّض المهام إلى Agents A2A بعيدة و/أو تعمل كـ Agents خادم متوافقة مع A2A.
|
||||
icon: network-wired
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## تفويض Agent A2A
|
||||
|
||||
يعامل CrewAI [بروتوكول A2A](https://a2a-protocol.org/latest/) كبنية تفويض أساسية، مما يمكّن الـ Agents من تفويض المهام وطلب المعلومات والتعاون مع Agents بعيدة، وكذلك العمل كـ Agents خادم متوافقة مع A2A. في وضع العميل، تختار الـ Agents تلقائيًا بين التنفيذ المحلي والتفويض البعيد بناءً على متطلبات المهمة.
|
||||
|
||||
## كيف يعمل
|
||||
|
||||
عندما يُهيَّأ Agent بقدرات A2A:
|
||||
|
||||
1. يحلل الـ Agent كل مهمة
|
||||
2. يقرر إما:
|
||||
- معالجة المهمة مباشرة باستخدام قدراته الخاصة
|
||||
- التفويض إلى Agent A2A بعيد للمعالجة المتخصصة
|
||||
3. إذا فوّض، يتواصل الـ Agent مع Agent A2A البعيد عبر البروتوكول
|
||||
4. تُعاد النتائج إلى سير عمل CrewAI
|
||||
|
||||
<Note>
|
||||
تفويض A2A يتطلب حزمة `a2a-sdk`. ثبّتها بـ: `uv add 'crewai[a2a]'` أو `pip install 'crewai[a2a]'`
|
||||
</Note>
|
||||
|
||||
## التهيئة الأساسية
|
||||
|
||||
<Warning>
|
||||
`crewai.a2a.config.A2AConfig` مهمل وسيُزال في v2.0.0. استخدم `A2AClientConfig` للاتصال بـ Agents بعيدة و/أو `A2AServerConfig` لعرض الـ Agents كخوادم.
|
||||
</Warning>
|
||||
|
||||
```python Code
|
||||
from crewai import Agent, Crew, Task
|
||||
from crewai.a2a import A2AClientConfig
|
||||
|
||||
agent = Agent(
|
||||
role="Research Coordinator",
|
||||
goal="Coordinate research tasks efficiently",
|
||||
backstory="Expert at delegating to specialized research agents",
|
||||
llm="gpt-4o",
|
||||
a2a=A2AClientConfig(
|
||||
endpoint="https://example.com/.well-known/agent-card.json",
|
||||
timeout=120,
|
||||
max_turns=10
|
||||
)
|
||||
)
|
||||
|
||||
task = Task(
|
||||
description="Research the latest developments in quantum computing",
|
||||
expected_output="A comprehensive research report",
|
||||
agent=agent
|
||||
)
|
||||
|
||||
crew = Crew(agents=[agent], tasks=[task], verbose=True)
|
||||
result = crew.kickoff()
|
||||
```
|
||||
|
||||
## خيارات تهيئة العميل
|
||||
|
||||
راجع الملف الإنجليزي الأصلي للحصول على القائمة الكاملة لمعاملات `A2AClientConfig` وخيارات المصادقة وآليات التحديث وتهيئة الخادم.
|
||||
|
||||
## أفضل الممارسات
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="عيّن مهلات مناسبة" icon="clock">
|
||||
هيّئ المهلات بناءً على أوقات استجابة Agent A2A المتوقعة.
|
||||
</Card>
|
||||
|
||||
<Card title="حدّ جولات المحادثة" icon="comments">
|
||||
استخدم `max_turns` لمنع التبادل المفرط.
|
||||
</Card>
|
||||
|
||||
<Card title="استخدم معالجة أخطاء مرنة" icon="shield-check">
|
||||
عيّن `fail_fast=False` لبيئات الإنتاج مع عدة Agents.
|
||||
</Card>
|
||||
|
||||
<Card title="أمّن بيانات الاعتماد" icon="lock">
|
||||
خزّن رموز المصادقة وبيانات الاعتماد كمتغيرات بيئة، ليس في الكود.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## تعلم المزيد
|
||||
|
||||
- [توثيق بروتوكول A2A](https://a2a-protocol.org)
|
||||
- [تطبيقات A2A النموذجية](https://github.com/a2aproject/a2a-samples)
|
||||
- [A2A Python SDK](https://github.com/a2aproject/a2a-python)
|
||||
47
docs/ar/learn/before-and-after-kickoff-hooks.mdx
Normal file
47
docs/ar/learn/before-and-after-kickoff-hooks.mdx
Normal file
@@ -0,0 +1,47 @@
|
||||
---
|
||||
title: خطافات قبل وبعد الانطلاق
|
||||
description: تعلم كيفية استخدام خطافات قبل وبعد الانطلاق في CrewAI
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
يوفر CrewAI خطافات تتيح لك تنفيذ كود قبل وبعد انطلاق Crew. هذه الخطافات مفيدة لمعالجة المدخلات مسبقًا أو معالجة النتائج لاحقًا.
|
||||
|
||||
## خطاف قبل الانطلاق
|
||||
|
||||
يُنفَّذ خطاف قبل الانطلاق قبل أن يبدأ Crew مهامه. يتلقى قاموس المدخلات ويمكنه تعديله قبل تمريره إلى Crew. يمكنك استخدام هذا الخطاف لإعداد بيئتك أو تحميل البيانات اللازمة أو معالجة المدخلات مسبقًا.
|
||||
|
||||
```python
|
||||
from crewai import CrewBase
|
||||
from crewai.project import before_kickoff
|
||||
|
||||
@CrewBase
|
||||
class MyCrew:
|
||||
@before_kickoff
|
||||
def prepare_data(self, inputs):
|
||||
inputs['processed'] = True
|
||||
return inputs
|
||||
```
|
||||
|
||||
## خطاف بعد الانطلاق
|
||||
|
||||
يُنفَّذ خطاف بعد الانطلاق بعد إتمام Crew مهامه. يتلقى كائن النتيجة الذي يحتوي على مخرجات تنفيذ Crew. هذا الخطاف مثالي لمعالجة النتائج لاحقًا مثل التسجيل أو تحويل البيانات أو التحليل الإضافي.
|
||||
|
||||
```python
|
||||
from crewai import CrewBase
|
||||
from crewai.project import after_kickoff
|
||||
|
||||
@CrewBase
|
||||
class MyCrew:
|
||||
@after_kickoff
|
||||
def log_results(self, result):
|
||||
print("Crew execution completed with result:", result)
|
||||
return result
|
||||
```
|
||||
|
||||
## استخدام كلا الخطافين
|
||||
|
||||
يمكن استخدام كلا الخطافين معًا لتوفير عملية إعداد وتفكيك شاملة لتنفيذ Crew. وهما مفيدان بشكل خاص في الحفاظ على بنية كود نظيفة من خلال فصل المسؤوليات وتعزيز نمطية تنفيذات CrewAI.
|
||||
|
||||
## الخلاصة
|
||||
|
||||
توفر خطافات قبل وبعد الانطلاق في CrewAI طرقًا قوية للتفاعل مع دورة حياة تنفيذ Crew. من خلال فهم واستخدام هذه الخطافات، يمكنك تعزيز متانة ومرونة Agents الذكاء الاصطناعي بشكل كبير.
|
||||
41
docs/ar/learn/bring-your-own-agent.mdx
Normal file
41
docs/ar/learn/bring-your-own-agent.mdx
Normal file
@@ -0,0 +1,41 @@
|
||||
---
|
||||
title: أحضر Agent الخاص بك
|
||||
description: تعلم كيفية إحضار Agents خاصة بك تعمل ضمن Crew.
|
||||
icon: robots
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
قابلية التشغيل البيني مفهوم أساسي في CrewAI. يوضح هذا الدليل كيفية إحضار Agents خاصة بك تعمل ضمن Crew.
|
||||
|
||||
## دليل المحوّلات لإحضار Agents الخاصة (Agents من LangGraph وOpenAI وغيرها...)
|
||||
|
||||
نتطلب 3 محوّلات لتحويل أي Agent من أطر عمل مختلفة للعمل ضمن Crew.
|
||||
|
||||
1. BaseAgentAdapter
|
||||
2. BaseToolAdapter
|
||||
3. BaseConverter
|
||||
|
||||
## BaseAgentAdapter
|
||||
|
||||
تعرّف هذه الفئة المجردة الواجهة المشتركة والوظائف التي يجب أن تنفذها جميع محوّلات الـ Agent. تمتد BaseAgent للحفاظ على التوافق مع إطار عمل CrewAI مع إضافة متطلبات خاصة بالمحوّل.
|
||||
|
||||
الطرق المطلوبة:
|
||||
|
||||
1. `def configure_tools`
|
||||
2. `def configure_structured_output`
|
||||
|
||||
## إنشاء محوّل خاص بك
|
||||
|
||||
لدمج Agent من إطار عمل مختلف في CrewAI، تحتاج لإنشاء محوّل مخصص بوراثة `BaseAgentAdapter`. يعمل هذا المحوّل كطبقة توافق تترجم بين واجهات CrewAI والمتطلبات المحددة للـ Agent الخارجي.
|
||||
|
||||
راجع الملف الإنجليزي الأصلي لأمثلة الكود التفصيلية لتنفيذ BaseAgentAdapter وBaseToolAdapter وBaseConverter.
|
||||
|
||||
## محوّلات جاهزة للاستخدام
|
||||
|
||||
نوفر محوّلات جاهزة للأطر التالية:
|
||||
1. LangGraph
|
||||
2. OpenAI Agents
|
||||
|
||||
## تشغيل Crew مع Agents محوّلة:
|
||||
|
||||
راجع الملف الإنجليزي الأصلي للحصول على مثال الكود الكامل الذي يوضح استخدام CrewAI Agent وOpenAI Agent Adapter وLangGraph Agent Adapter معًا في Crew واحد.
|
||||
80
docs/ar/learn/coding-agents.mdx
Normal file
80
docs/ar/learn/coding-agents.mdx
Normal file
@@ -0,0 +1,80 @@
|
||||
---
|
||||
title: Agents البرمجة
|
||||
description: تعلم كيفية تمكين Agents CrewAI من كتابة وتنفيذ الكود، واستكشف الميزات المتقدمة لوظائف محسّنة.
|
||||
icon: rectangle-code
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## مقدمة
|
||||
|
||||
أصبح لدى CrewAI Agents القدرة القوية على كتابة وتنفيذ الكود، مما يعزز قدراتها في حل المشكلات بشكل كبير. هذه الميزة مفيدة بشكل خاص للمهام التي تتطلب حلولاً حسابية أو برمجية.
|
||||
|
||||
## تمكين تنفيذ الكود
|
||||
|
||||
لتمكين تنفيذ الكود لـ Agent، عيّن معامل `allow_code_execution` إلى `True` عند إنشاء الـ Agent.
|
||||
|
||||
```python Code
|
||||
from crewai import Agent
|
||||
|
||||
coding_agent = Agent(
|
||||
role="Senior Python Developer",
|
||||
goal="Craft well-designed and thought-out code",
|
||||
backstory="You are a senior Python developer with extensive experience in software architecture and best practices.",
|
||||
allow_code_execution=True
|
||||
)
|
||||
```
|
||||
|
||||
<Note>
|
||||
لاحظ أن معامل `allow_code_execution` يكون `False` افتراضيًا.
|
||||
</Note>
|
||||
|
||||
## اعتبارات مهمة
|
||||
|
||||
1. **اختيار النموذج**: يُوصى بشدة باستخدام نماذج أكثر قدرة مثل Claude 3.5 Sonnet وGPT-4 عند تمكين تنفيذ الكود.
|
||||
|
||||
2. **معالجة الأخطاء**: تتضمن ميزة تنفيذ الكود معالجة أخطاء. إذا أثار الكود المُنفَّذ استثناءً، سيتلقى الـ Agent رسالة الخطأ ويمكنه محاولة تصحيح الكود. يتحكم معامل `max_retry_limit` (الافتراضي 2) في الحد الأقصى لعدد المحاولات.
|
||||
|
||||
3. **التبعيات**: لاستخدام ميزة تنفيذ الكود، تحتاج لتثبيت حزمة `crewai_tools`.
|
||||
|
||||
## عملية تنفيذ الكود
|
||||
|
||||
<Steps>
|
||||
<Step title="تحليل المهمة">
|
||||
يحلل الـ Agent المهمة ويحدد أن تنفيذ الكود ضروري.
|
||||
</Step>
|
||||
<Step title="صياغة الكود">
|
||||
يصيغ كود Python اللازم لحل المشكلة.
|
||||
</Step>
|
||||
<Step title="تنفيذ الكود">
|
||||
يُرسَل الكود إلى أداة تنفيذ الكود الداخلية (`CodeInterpreterTool`).
|
||||
</Step>
|
||||
<Step title="تفسير النتيجة">
|
||||
يفسر الـ Agent النتيجة ويدمجها في استجابته أو يستخدمها لمزيد من حل المشكلات.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## مثال استخدام
|
||||
|
||||
```python Code
|
||||
from crewai import Agent, Task, Crew
|
||||
|
||||
coding_agent = Agent(
|
||||
role="Python Data Analyst",
|
||||
goal="Analyze data and provide insights using Python",
|
||||
backstory="You are an experienced data analyst with strong Python skills.",
|
||||
allow_code_execution=True
|
||||
)
|
||||
|
||||
data_analysis_task = Task(
|
||||
description="Analyze the given dataset and calculate the average age of participants.",
|
||||
agent=coding_agent
|
||||
)
|
||||
|
||||
analysis_crew = Crew(
|
||||
agents=[coding_agent],
|
||||
tasks=[data_analysis_task]
|
||||
)
|
||||
|
||||
result = analysis_crew.kickoff()
|
||||
print(result)
|
||||
```
|
||||
14
docs/ar/learn/conditional-tasks.mdx
Normal file
14
docs/ar/learn/conditional-tasks.mdx
Normal file
@@ -0,0 +1,14 @@
|
||||
---
|
||||
title: المهام الشرطية
|
||||
description: تعلم كيفية استخدام المهام الشرطية في انطلاق crewAI
|
||||
icon: diagram-subtask
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## مقدمة
|
||||
|
||||
تتيح المهام الشرطية في crewAI التكيف الديناميكي لسير العمل بناءً على نتائج المهام السابقة. تمكّن هذه الميزة القوية الـ Crews من اتخاذ قرارات وتنفيذ المهام بشكل انتقائي، مما يعزز مرونة وكفاءة عملياتك المدفوعة بالذكاء الاصطناعي.
|
||||
|
||||
## مثال استخدام
|
||||
|
||||
راجع الملف الإنجليزي الأصلي للحصول على مثال الكود الكامل الذي يوضح استخدام `ConditionalTask` مع دالة شرط `is_data_missing` للتحكم في تنفيذ المهام بناءً على مخرجات المهام السابقة.
|
||||
77
docs/ar/learn/create-custom-tools.mdx
Normal file
77
docs/ar/learn/create-custom-tools.mdx
Normal file
@@ -0,0 +1,77 @@
|
||||
---
|
||||
title: إنشاء أدوات مخصصة
|
||||
description: دليل شامل لصياغة واستخدام وإدارة الأدوات المخصصة ضمن إطار عمل CrewAI، بما في ذلك الوظائف الجديدة ومعالجة الأخطاء.
|
||||
icon: hammer
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## إنشاء واستخدام الأدوات في CrewAI
|
||||
|
||||
يقدم هذا الدليل تعليمات مفصلة لإنشاء أدوات مخصصة لإطار عمل CrewAI وكيفية إدارة واستخدام هذه الأدوات بكفاءة، مع دمج أحدث الوظائف مثل تفويض الأدوات ومعالجة الأخطاء واستدعاء الأدوات الديناميكي.
|
||||
|
||||
<Tip>
|
||||
**هل تريد نشر أداتك للمجتمع؟** إذا كنت تبني أداة يمكن أن تفيد الآخرين، اطلع على دليل [نشر أدوات مخصصة](/ar/guides/tools/publish-custom-tools) لتعلم كيفية تعبئة وتوزيع أداتك على PyPI.
|
||||
</Tip>
|
||||
|
||||
### وراثة `BaseTool`
|
||||
|
||||
لإنشاء أداة مخصصة، ورث من `BaseTool` وعرّف السمات الضرورية بما في ذلك `args_schema` للتحقق من المدخلات وطريقة `_run`.
|
||||
|
||||
```python Code
|
||||
from typing import Type
|
||||
from crewai.tools import BaseTool
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
class MyToolInput(BaseModel):
|
||||
"""Input schema for MyCustomTool."""
|
||||
argument: str = Field(..., description="Description of the argument.")
|
||||
|
||||
class MyCustomTool(BaseTool):
|
||||
name: str = "Name of my tool"
|
||||
description: str = "What this tool does. It's vital for effective utilization."
|
||||
args_schema: Type[BaseModel] = MyToolInput
|
||||
|
||||
def _run(self, argument: str) -> str:
|
||||
return "Tool's result"
|
||||
```
|
||||
|
||||
### استخدام مزخرف `tool`
|
||||
|
||||
```python Code
|
||||
from crewai.tools import tool
|
||||
|
||||
@tool("Tool Name")
|
||||
def my_simple_tool(question: str) -> str:
|
||||
"""Tool description for clarity."""
|
||||
return "Tool output"
|
||||
```
|
||||
|
||||
### تعريف دالة تخزين مؤقت للأداة
|
||||
|
||||
```python Code
|
||||
@tool("Tool with Caching")
|
||||
def cached_tool(argument: str) -> str:
|
||||
"""Tool functionality description."""
|
||||
return "Cacheable result"
|
||||
|
||||
def my_cache_strategy(arguments: dict, result: str) -> bool:
|
||||
return True if some_condition else False
|
||||
|
||||
cached_tool.cache_function = my_cache_strategy
|
||||
```
|
||||
|
||||
### إنشاء أدوات غير متزامنة
|
||||
|
||||
يدعم CrewAI الأدوات غير المتزامنة لعمليات I/O غير المحجوبة.
|
||||
|
||||
```python Code
|
||||
import aiohttp
|
||||
from crewai.tools import tool
|
||||
|
||||
@tool("Async Web Fetcher")
|
||||
async def fetch_webpage(url: str) -> str:
|
||||
"""Fetch content from a webpage asynchronously."""
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(url) as response:
|
||||
return await response.text()
|
||||
```
|
||||
55
docs/ar/learn/custom-llm.mdx
Normal file
55
docs/ar/learn/custom-llm.mdx
Normal file
@@ -0,0 +1,55 @@
|
||||
---
|
||||
title: تنفيذ LLM مخصص
|
||||
description: تعلم كيفية إنشاء تنفيذات LLM مخصصة في CrewAI.
|
||||
icon: code
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## نظرة عامة
|
||||
|
||||
يدعم CrewAI تنفيذات LLM المخصصة من خلال فئة `BaseLLM` المجردة. يتيح لك ذلك دمج أي مزود LLM لا يحظى بدعم مدمج في LiteLLM، أو تنفيذ آليات مصادقة مخصصة.
|
||||
|
||||
## بداية سريعة
|
||||
|
||||
راجع الملف الإنجليزي الأصلي للحصول على تنفيذ LLM مخصص كامل يوضح طريقة `call()` المطلوبة والطرق الاختيارية مثل `supports_function_calling()` و`get_context_window_size()`.
|
||||
|
||||
## استخدام LLM المخصص
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
|
||||
custom_llm = CustomLLM(
|
||||
model="my-custom-model",
|
||||
api_key="your-api-key",
|
||||
endpoint="https://api.example.com/v1/chat/completions",
|
||||
temperature=0.7
|
||||
)
|
||||
|
||||
agent = Agent(
|
||||
role="Research Assistant",
|
||||
goal="Find and analyze information",
|
||||
backstory="You are a research assistant.",
|
||||
llm=custom_llm
|
||||
)
|
||||
|
||||
task = Task(
|
||||
description="Research the latest developments in AI",
|
||||
expected_output="A comprehensive summary",
|
||||
agent=agent
|
||||
)
|
||||
|
||||
crew = Crew(agents=[agent], tasks=[task])
|
||||
result = crew.kickoff()
|
||||
```
|
||||
|
||||
## الطرق المطلوبة
|
||||
|
||||
### البنّاء: `__init__()`
|
||||
|
||||
**مهم**: يجب استدعاء `super().__init__(model, temperature)` مع المعاملات المطلوبة.
|
||||
|
||||
### الطريقة المجردة: `call()`
|
||||
|
||||
طريقة `call()` هي قلب تنفيذ LLM. يجب أن تقبل الرسائل وتعيد استجابة نصية وتعالج الأدوات واستدعاء الدوال إذا كانت مدعومة.
|
||||
|
||||
يغطي هذا الدليل أساسيات تنفيذ LLM مخصصة في CrewAI.
|
||||
81
docs/ar/learn/custom-manager-agent.mdx
Normal file
81
docs/ar/learn/custom-manager-agent.mdx
Normal file
@@ -0,0 +1,81 @@
|
||||
---
|
||||
title: Agent مدير مخصص
|
||||
description: تعلم كيفية تعيين Agent مخصص كمدير في CrewAI، مما يوفر مزيدًا من التحكم في إدارة المهام والتنسيق.
|
||||
icon: user-shield
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
# تعيين Agent محدد كمدير في CrewAI
|
||||
|
||||
يتيح CrewAI للمستخدمين تعيين Agent محدد كمدير للـ Crew، مما يوفر مزيدًا من التحكم في إدارة المهام وتنسيقها.
|
||||
|
||||
## استخدام سمة `manager_agent`
|
||||
|
||||
تتيح لك سمة `manager_agent` تعريف Agent مخصص لإدارة الـ Crew. سيشرف هذا الـ Agent على العملية بأكملها لضمان إتمام المهام بكفاءة وبأعلى المعايير.
|
||||
|
||||
```python Code
|
||||
import os
|
||||
from crewai import Agent, Task, Crew, Process
|
||||
|
||||
researcher = Agent(
|
||||
role="Researcher",
|
||||
goal="Conduct thorough research and analysis on AI and AI agents",
|
||||
backstory="You're an expert researcher...",
|
||||
allow_delegation=False,
|
||||
)
|
||||
|
||||
writer = Agent(
|
||||
role="Senior Writer",
|
||||
goal="Create compelling content about AI and AI agents",
|
||||
backstory="You're a senior writer...",
|
||||
allow_delegation=False,
|
||||
)
|
||||
|
||||
task = Task(
|
||||
description="Generate a list of 5 interesting ideas for an article...",
|
||||
expected_output="5 bullet points, each with a paragraph and accompanying notes.",
|
||||
)
|
||||
|
||||
manager = Agent(
|
||||
role="Project Manager",
|
||||
goal="Efficiently manage the crew and ensure high-quality task completion",
|
||||
backstory="You're an experienced project manager...",
|
||||
allow_delegation=True,
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[researcher, writer],
|
||||
tasks=[task],
|
||||
manager_agent=manager,
|
||||
process=Process.hierarchical,
|
||||
)
|
||||
|
||||
result = crew.kickoff()
|
||||
```
|
||||
|
||||
## فوائد Agent المدير المخصص
|
||||
|
||||
- **تحكم محسّن**: تخصيص نهج الإدارة ليناسب الاحتياجات المحددة لمشروعك.
|
||||
- **تنسيق محسّن**: ضمان تنسيق المهام وإدارتها بكفاءة من قبل Agent ذي خبرة.
|
||||
- **إدارة قابلة للتخصيص**: تعريف أدوار ومسؤوليات إدارية تتماشى مع أهداف مشروعك.
|
||||
|
||||
## تعيين LLM للمدير
|
||||
|
||||
إذا كنت تستخدم العملية الهرمية ولا تريد تعيين Agent مدير مخصص، يمكنك تحديد نموذج اللغة للمدير:
|
||||
|
||||
```python Code
|
||||
from crewai import LLM
|
||||
|
||||
manager_llm = LLM(model="gpt-4o")
|
||||
|
||||
crew = Crew(
|
||||
agents=[researcher, writer],
|
||||
tasks=[task],
|
||||
process=Process.hierarchical,
|
||||
manager_llm=manager_llm
|
||||
)
|
||||
```
|
||||
|
||||
<Note>
|
||||
يجب تعيين إما `manager_agent` أو `manager_llm` عند استخدام العملية الهرمية.
|
||||
</Note>
|
||||
67
docs/ar/learn/customizing-agents.mdx
Normal file
67
docs/ar/learn/customizing-agents.mdx
Normal file
@@ -0,0 +1,67 @@
|
||||
---
|
||||
title: تخصيص الـ Agents
|
||||
description: دليل شامل لتخصيص الـ Agents لأدوار ومهام محددة وتخصيصات متقدمة ضمن إطار عمل CrewAI.
|
||||
icon: user-pen
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## السمات القابلة للتخصيص
|
||||
|
||||
يعتمد بناء فريق CrewAI فعّال على القدرة على تخصيص Agents الذكاء الاصطناعي ديناميكيًا لتلبية المتطلبات الفريدة لأي مشروع. يغطي هذا القسم السمات الأساسية التي يمكنك تخصيصها.
|
||||
|
||||
### السمات الرئيسية للتخصيص
|
||||
|
||||
| السمة | الوصف |
|
||||
|:-----------------------|:----------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| **Role** | يحدد وظيفة الـ Agent ضمن Crew، مثل 'محلل' أو 'ممثل خدمة عملاء'. |
|
||||
| **Goal** | يعرّف أهداف الـ Agent، متوافقة مع دوره ومهمة Crew الشاملة. |
|
||||
| **Backstory** | يوفر عمقًا لشخصية الـ Agent، معززًا الدوافع والتفاعلات ضمن Crew. |
|
||||
| **Tools** *(اختياري)* | يمثل القدرات أو الطرق التي يستخدمها الـ Agent للمهام. |
|
||||
| **Cache** *(اختياري)* | يحدد ما إذا كان الـ Agent يجب أن يستخدم ذاكرة مؤقتة لاستخدام الأدوات. |
|
||||
| **Max RPM** | يعيّن الحد الأقصى للطلبات في الدقيقة (`max_rpm`). |
|
||||
| **Verbose** *(اختياري)* | يمكّن التسجيل التفصيلي للتصحيح والتحسين. |
|
||||
| **Allow Delegation** *(اختياري)* | يتحكم في تفويض المهام لـ Agents أخرى، الافتراضي `False`. |
|
||||
| **Max Iter** *(اختياري)* | يحد الحد الأقصى لعدد التكرارات (`max_iter`) لمهمة، الافتراضي 25. |
|
||||
|
||||
## خيارات تخصيص متقدمة
|
||||
|
||||
### تخصيص نموذج اللغة
|
||||
|
||||
يمكن تخصيص الـ Agents بنماذج لغة محددة (`llm`) ونماذج لغة لاستدعاء الدوال (`function_calling_llm`)، مما يوفر تحكمًا متقدمًا في قدرات المعالجة وصنع القرار.
|
||||
|
||||
## إعدادات الأداء والتصحيح
|
||||
|
||||
- **وضع التفصيل**: يمكّن التسجيل التفصيلي لإجراءات الـ Agent.
|
||||
- **حد RPM**: يعيّن الحد الأقصى للطلبات في الدقيقة.
|
||||
|
||||
### مثال: تعيين أدوات لـ Agent
|
||||
|
||||
```python Code
|
||||
import os
|
||||
from crewai import Agent
|
||||
from crewai_tools import SerperDevTool
|
||||
|
||||
os.environ["OPENAI_API_KEY"] = "Your Key"
|
||||
os.environ["SERPER_API_KEY"] = "Your Key"
|
||||
|
||||
search_tool = SerperDevTool()
|
||||
|
||||
agent = Agent(
|
||||
role='Research Analyst',
|
||||
goal='Provide up-to-date market analysis',
|
||||
backstory='An expert analyst with a keen eye for market trends.',
|
||||
tools=[search_tool],
|
||||
memory=True,
|
||||
verbose=True,
|
||||
max_rpm=None,
|
||||
max_iter=25,
|
||||
)
|
||||
```
|
||||
|
||||
## التفويض والاستقلالية
|
||||
|
||||
التحكم في قدرة الـ Agent على تفويض المهام أو طرح الأسئلة أمر حيوي لتخصيص استقلاليته وديناميكيات التعاون. افتراضيًا، سمة `allow_delegation` معيّنة على `False`.
|
||||
|
||||
## الخلاصة
|
||||
|
||||
تخصيص الـ Agents في CrewAI من خلال تعيين أدوارهم وأهدافهم وخلفياتهم وأدواتهم، إلى جانب خيارات متقدمة مثل تخصيص نموذج اللغة والذاكرة وإعدادات الأداء وتفضيلات التفويض، يجهّز فريق AI دقيق وقادر جاهز للتحديات المعقدة.
|
||||
52
docs/ar/learn/dalle-image-generation.mdx
Normal file
52
docs/ar/learn/dalle-image-generation.mdx
Normal file
@@ -0,0 +1,52 @@
|
||||
---
|
||||
title: "إنشاء الصور باستخدام DALL-E"
|
||||
description: "تعلم كيفية استخدام DALL-E لإنشاء صور مدعومة بالذكاء الاصطناعي في مشاريع CrewAI"
|
||||
icon: "image"
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
يدعم CrewAI التكامل مع DALL-E من OpenAI، مما يتيح لـ Agents الذكاء الاصطناعي إنشاء صور كجزء من مهامهم. سيرشدك هذا الدليل عبر كيفية إعداد واستخدام أداة DALL-E في مشاريع CrewAI.
|
||||
|
||||
## المتطلبات المسبقة
|
||||
|
||||
- crewAI مثبّت (أحدث إصدار)
|
||||
- مفتاح OpenAI API مع وصول إلى DALL-E
|
||||
|
||||
## إعداد أداة DALL-E
|
||||
|
||||
<Steps>
|
||||
<Step title="استيراد أداة DALL-E">
|
||||
```python
|
||||
from crewai_tools import DallETool
|
||||
```
|
||||
</Step>
|
||||
|
||||
<Step title="إضافة أداة DALL-E إلى تهيئة Agent">
|
||||
```python
|
||||
@agent
|
||||
def researcher(self) -> Agent:
|
||||
return Agent(
|
||||
config=self.agents_config['researcher'],
|
||||
tools=[SerperDevTool(), DallETool()],
|
||||
allow_delegation=False,
|
||||
verbose=True
|
||||
)
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## استخدام أداة DALL-E
|
||||
|
||||
بمجرد إضافة أداة DALL-E إلى Agent، يمكنه إنشاء صور بناءً على مطالبات نصية. ستعيد الأداة رابط URL للصورة المُنشأة.
|
||||
|
||||
## أفضل الممارسات
|
||||
|
||||
1. **كن محددًا في مطالبات إنشاء الصور** للحصول على أفضل النتائج.
|
||||
2. **ضع في اعتبارك وقت الإنشاء** - قد يستغرق إنشاء الصور بعض الوقت.
|
||||
3. **اتبع سياسات الاستخدام** - التزم دائمًا بسياسات استخدام OpenAI عند إنشاء الصور.
|
||||
|
||||
## استكشاف الأخطاء
|
||||
|
||||
1. **تحقق من وصول API** - تأكد من أن مفتاح OpenAI API لديه وصول إلى DALL-E.
|
||||
2. **توافق الإصدارات** - تأكد من استخدام أحدث إصدار من crewAI وcrewai-tools.
|
||||
3. **تهيئة الأداة** - تحقق من إضافة أداة DALL-E بشكل صحيح لقائمة أدوات الـ Agent.
|
||||
86
docs/ar/learn/execution-hooks.mdx
Normal file
86
docs/ar/learn/execution-hooks.mdx
Normal file
@@ -0,0 +1,86 @@
|
||||
---
|
||||
title: نظرة عامة على خطافات التنفيذ
|
||||
description: فهم واستخدام خطافات التنفيذ في CrewAI للتحكم الدقيق في عمليات الـ Agent
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
توفر خطافات التنفيذ تحكمًا دقيقًا في سلوك وقت تشغيل Agents CrewAI. على عكس خطافات الانطلاق التي تعمل قبل وبعد تنفيذ Crew، تعترض خطافات التنفيذ عمليات محددة أثناء تنفيذ الـ Agent، مما يتيح لك تعديل السلوك وتنفيذ فحوصات أمان وإضافة مراقبة شاملة.
|
||||
|
||||
## أنواع خطافات التنفيذ
|
||||
|
||||
### 1. [خطافات استدعاء LLM](/learn/llm-hooks)
|
||||
|
||||
التحكم ومراقبة تفاعلات نموذج اللغة:
|
||||
- **قبل استدعاء LLM**: تعديل المطالبات، التحقق من المدخلات، بوابات الموافقة
|
||||
- **بعد استدعاء LLM**: تحويل الاستجابات، تنقية المخرجات، تحديث سجل المحادثة
|
||||
|
||||
### 2. [خطافات استدعاء الأدوات](/learn/tool-hooks)
|
||||
|
||||
التحكم ومراقبة تنفيذ الأدوات:
|
||||
- **قبل استدعاء الأداة**: تعديل المدخلات، التحقق من المعاملات، حظر العمليات الخطرة
|
||||
- **بعد استدعاء الأداة**: تحويل النتائج، تنقية المخرجات، تسجيل تفاصيل التنفيذ
|
||||
|
||||
## طرق تسجيل الخطافات
|
||||
|
||||
### 1. خطافات بالمزخرفات (مُوصى بها)
|
||||
|
||||
```python
|
||||
from crewai.hooks import before_llm_call, after_llm_call, before_tool_call, after_tool_call
|
||||
|
||||
@before_llm_call
|
||||
def limit_iterations(context):
|
||||
if context.iterations > 10:
|
||||
return False
|
||||
return None
|
||||
|
||||
@after_llm_call
|
||||
def sanitize_response(context):
|
||||
if "API_KEY" in context.response:
|
||||
return context.response.replace("API_KEY", "[REDACTED]")
|
||||
return None
|
||||
|
||||
@before_tool_call
|
||||
def block_dangerous_tools(context):
|
||||
if context.tool_name == "delete_database":
|
||||
return False
|
||||
return None
|
||||
```
|
||||
|
||||
### 2. خطافات نطاق Crew
|
||||
|
||||
```python
|
||||
from crewai import CrewBase
|
||||
from crewai.project import crew
|
||||
from crewai.hooks import before_llm_call_crew, after_tool_call_crew
|
||||
|
||||
@CrewBase
|
||||
class MyProjCrew:
|
||||
@before_llm_call_crew
|
||||
def validate_inputs(self, context):
|
||||
print(f"LLM call in {self.__class__.__name__}")
|
||||
return None
|
||||
|
||||
@after_tool_call_crew
|
||||
def log_results(self, context):
|
||||
print(f"Tool result: {context.tool_result[:50]}...")
|
||||
return None
|
||||
```
|
||||
|
||||
## أفضل الممارسات
|
||||
|
||||
1. **اجعل الخطافات مركّزة** - كل خطاف يجب أن يكون له مسؤولية واحدة واضحة
|
||||
2. **عالج الأخطاء بلطف**
|
||||
3. **عدّل السياق في مكانه**
|
||||
4. **استخدم تلميحات الأنواع**
|
||||
5. **نظّف في الاختبارات**
|
||||
|
||||
## التوثيق ذو الصلة
|
||||
|
||||
- [خطافات استدعاء LLM](/learn/llm-hooks)
|
||||
- [خطافات استدعاء الأدوات](/learn/tool-hooks)
|
||||
- [خطافات قبل وبعد الانطلاق](/learn/before-and-after-kickoff-hooks)
|
||||
- [التدخل البشري](/learn/human-in-the-loop)
|
||||
|
||||
## الخلاصة
|
||||
|
||||
توفر خطافات التنفيذ تحكمًا قويًا في سلوك وقت تشغيل الـ Agent. استخدمها لتنفيذ حواجز أمان وسير عمل موافقة ومراقبة شاملة ومنطق أعمال مخصص.
|
||||
45
docs/ar/learn/force-tool-output-as-result.mdx
Normal file
45
docs/ar/learn/force-tool-output-as-result.mdx
Normal file
@@ -0,0 +1,45 @@
|
||||
---
|
||||
title: فرض مخرجات الأداة كنتيجة
|
||||
description: تعلم كيفية فرض مخرجات الأداة كنتيجة لمهمة Agent في CrewAI.
|
||||
icon: wrench-simple
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## مقدمة
|
||||
|
||||
في CrewAI، يمكنك فرض مخرجات أداة كنتيجة لمهمة Agent. هذه الميزة مفيدة عندما تريد التأكد من التقاط مخرجات الأداة وإعادتها كنتيجة للمهمة، متجنبًا أي تعديل من قبل الـ Agent أثناء تنفيذ المهمة.
|
||||
|
||||
## فرض مخرجات الأداة كنتيجة
|
||||
|
||||
لفرض مخرجات الأداة كنتيجة لمهمة Agent، تحتاج لتعيين معامل `result_as_answer` إلى `True` عند إضافة أداة إلى الـ Agent.
|
||||
|
||||
```python Code
|
||||
from crewai.agent import Agent
|
||||
from my_tool import MyCustomTool
|
||||
|
||||
coding_agent = Agent(
|
||||
role="Data Scientist",
|
||||
goal="Produce amazing reports on AI",
|
||||
backstory="You work with data and AI",
|
||||
tools=[MyCustomTool(result_as_answer=True)],
|
||||
)
|
||||
|
||||
task_result = coding_agent.execute_task(task)
|
||||
```
|
||||
|
||||
## سير العمل أثناء التنفيذ
|
||||
|
||||
<Steps>
|
||||
<Step title="تنفيذ المهمة">
|
||||
ينفذ الـ Agent المهمة باستخدام الأداة المقدمة.
|
||||
</Step>
|
||||
<Step title="مخرجات الأداة">
|
||||
تولّد الأداة المخرجات التي تُلتقط كنتيجة للمهمة.
|
||||
</Step>
|
||||
<Step title="تفاعل الـ Agent">
|
||||
قد يتأمل الـ Agent ويستخلص دروسًا من الأداة لكن لا يعدّل المخرجات.
|
||||
</Step>
|
||||
<Step title="إعادة النتيجة">
|
||||
تُعاد مخرجات الأداة كنتيجة للمهمة دون أي تعديلات.
|
||||
</Step>
|
||||
</Steps>
|
||||
76
docs/ar/learn/hierarchical-process.mdx
Normal file
76
docs/ar/learn/hierarchical-process.mdx
Normal file
@@ -0,0 +1,76 @@
|
||||
---
|
||||
title: العملية الهرمية
|
||||
description: دليل شامل لفهم وتطبيق العملية الهرمية ضمن مشاريع CrewAI.
|
||||
icon: sitemap
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## مقدمة
|
||||
|
||||
تقدم العملية الهرمية في CrewAI نهجًا منظمًا لإدارة المهام، محاكاةً للتسلسلات الهرمية التنظيمية التقليدية للتفويض والتنفيذ الفعّال للمهام.
|
||||
|
||||
<Tip>
|
||||
صُممت العملية الهرمية للاستفادة من نماذج متقدمة مثل GPT-4، مما يحسّن استخدام الرموز المميزة مع التعامل مع المهام المعقدة بكفاءة أكبر.
|
||||
</Tip>
|
||||
|
||||
## نظرة عامة على العملية الهرمية
|
||||
|
||||
افتراضيًا، تُدار المهام في CrewAI من خلال عملية متسلسلة. لكن اعتماد نهج هرمي يتيح تسلسلاً واضحًا في إدارة المهام، حيث يقوم Agent 'مدير' بتنسيق سير العمل وتفويض المهام والتحقق من النتائج.
|
||||
|
||||
### الميزات الرئيسية
|
||||
|
||||
- **تفويض المهام**: Agent مدير يوزّع المهام بين أعضاء Crew بناءً على أدوارهم وقدراتهم.
|
||||
- **التحقق من النتائج**: يقيّم المدير النتائج لضمان استيفائها للمعايير المطلوبة.
|
||||
- **سير عمل فعّال**: يحاكي الهياكل المؤسسية مقدمًا نهجًا منظمًا لإدارة المهام.
|
||||
|
||||
## تنفيذ العملية الهرمية
|
||||
|
||||
```python Code
|
||||
from crewai import Crew, Process, Agent
|
||||
|
||||
researcher = Agent(
|
||||
role='Researcher',
|
||||
goal='Conduct in-depth analysis',
|
||||
backstory='Experienced data analyst with a knack for uncovering hidden trends.',
|
||||
)
|
||||
writer = Agent(
|
||||
role='Writer',
|
||||
goal='Create engaging content',
|
||||
backstory='Creative writer passionate about storytelling in technical domains.',
|
||||
)
|
||||
|
||||
project_crew = Crew(
|
||||
tasks=[...],
|
||||
agents=[researcher, writer],
|
||||
manager_llm="gpt-4o",
|
||||
process=Process.hierarchical,
|
||||
planning=True,
|
||||
)
|
||||
```
|
||||
|
||||
### استخدام Agent مدير مخصص
|
||||
|
||||
```python
|
||||
manager = Agent(
|
||||
role="Project Manager",
|
||||
goal="Efficiently manage the crew and ensure high-quality task completion",
|
||||
backstory="You're an experienced project manager...",
|
||||
allow_delegation=True,
|
||||
)
|
||||
|
||||
project_crew = Crew(
|
||||
tasks=[...],
|
||||
agents=[researcher, writer],
|
||||
manager_agent=manager,
|
||||
process=Process.hierarchical,
|
||||
planning=True,
|
||||
)
|
||||
```
|
||||
|
||||
<Tip>
|
||||
لمزيد من التفاصيل حول إنشاء وتخصيص Agent مدير، اطلع على [توثيق Agent المدير المخصص](/ar/learn/custom-manager-agent).
|
||||
</Tip>
|
||||
|
||||
## الخلاصة
|
||||
|
||||
اعتماد العملية الهرمية في CrewAI مع التهيئات الصحيحة وفهم قدرات النظام يسهّل نهجًا منظمًا وفعّالاً لإدارة المشاريع. استفد من الميزات المتقدمة والتخصيصات لتكييف سير العمل لاحتياجاتك المحددة.
|
||||
98
docs/ar/learn/human-feedback-in-flows.mdx
Normal file
98
docs/ar/learn/human-feedback-in-flows.mdx
Normal file
@@ -0,0 +1,98 @@
|
||||
---
|
||||
title: التغذية الراجعة البشرية في Flows
|
||||
description: تعلم كيفية دمج التغذية الراجعة البشرية مباشرة في CrewAI Flows باستخدام مزخرف @human_feedback
|
||||
icon: user-check
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## نظرة عامة
|
||||
|
||||
<Note>
|
||||
يتطلب مزخرف `@human_feedback` إصدار **CrewAI 1.8.0 أو أحدث**. تأكد من تحديث تثبيتك قبل استخدام هذه الميزة.
|
||||
</Note>
|
||||
|
||||
يمكّن مزخرف `@human_feedback` سير العمل البشري في الحلقة (HITL) مباشرة ضمن CrewAI Flows. يتيح لك إيقاف تنفيذ Flow مؤقتًا وعرض المخرجات لإنسان للمراجعة وجمع تعليقاته واختياريًا التوجيه إلى مستمعين مختلفين بناءً على نتيجة التعليقات.
|
||||
|
||||
هذا مفيد بشكل خاص لـ:
|
||||
|
||||
- **ضمان الجودة**: مراجعة المحتوى المُنشأ بالذكاء الاصطناعي قبل استخدامه
|
||||
- **بوابات القرار**: السماح للبشر باتخاذ قرارات حرجة في سير العمل الآلي
|
||||
- **سير عمل الموافقة**: تنفيذ أنماط الموافقة/الرفض/المراجعة
|
||||
- **التحسين التفاعلي**: جمع التعليقات لتحسين المخرجات تكراريًا
|
||||
|
||||
## بداية سريعة
|
||||
|
||||
```python Code
|
||||
from crewai.flow.flow import Flow, start, listen
|
||||
from crewai.flow.human_feedback import human_feedback
|
||||
|
||||
class SimpleReviewFlow(Flow):
|
||||
@start()
|
||||
@human_feedback(message="Please review this content:")
|
||||
def generate_content(self):
|
||||
return "This is AI-generated content that needs review."
|
||||
|
||||
@listen(generate_content)
|
||||
def process_feedback(self, result):
|
||||
print(f"Content: {result.output}")
|
||||
print(f"Human said: {result.feedback}")
|
||||
|
||||
flow = SimpleReviewFlow()
|
||||
flow.kickoff()
|
||||
```
|
||||
|
||||
## التوجيه مع emit
|
||||
|
||||
عند تحديد `emit`، يصبح المزخرف موجّهًا. يُفسَّر التعليق البشري الحر بواسطة LLM ويُختزل إلى إحدى النتائج المحددة:
|
||||
|
||||
```python Code
|
||||
from crewai.flow.flow import Flow, start, listen, or_
|
||||
from crewai.flow.human_feedback import human_feedback
|
||||
|
||||
class ReviewFlow(Flow):
|
||||
@start()
|
||||
def generate_content(self):
|
||||
return "Draft blog post content here..."
|
||||
|
||||
@human_feedback(
|
||||
message="Do you approve this content for publication?",
|
||||
emit=["approved", "rejected", "needs_revision"],
|
||||
llm="gpt-4o-mini",
|
||||
default_outcome="needs_revision",
|
||||
)
|
||||
@listen(or_("generate_content", "needs_revision"))
|
||||
def review_content(self):
|
||||
return "Draft blog post content here..."
|
||||
|
||||
@listen("approved")
|
||||
def publish(self, result):
|
||||
print(f"Publishing! User said: {result.feedback}")
|
||||
|
||||
@listen("rejected")
|
||||
def discard(self, result):
|
||||
print(f"Discarding. Reason: {result.feedback}")
|
||||
```
|
||||
|
||||
## التعلم من التغذية الراجعة
|
||||
|
||||
معامل `learn=True` يمكّن حلقة تغذية راجعة بين المراجعين البشريين ونظام الذاكرة. عند تمكينه، يحسّن النظام مخرجاته تدريجيًا بالتعلم من التصحيحات البشرية السابقة.
|
||||
|
||||
## أفضل الممارسات
|
||||
|
||||
1. **اكتب رسائل طلب واضحة**
|
||||
2. **اختر نتائج ذات معنى**
|
||||
3. **وفّر دائمًا نتيجة افتراضية**
|
||||
4. **استخدم سجل التعليقات لمسارات التدقيق**
|
||||
|
||||
## التغذية الراجعة البشرية غير المتزامنة (غير محجوبة)
|
||||
|
||||
استخدم معامل `provider` لتحديد استراتيجية جمع تعليقات مخصصة تتكامل مع أنظمة خارجية مثل Slack والبريد الإلكتروني وWebhooks وواجهات API.
|
||||
|
||||
## التوثيق ذو الصلة
|
||||
|
||||
- [نظرة عامة على Flows](/ar/concepts/flows)
|
||||
- [إدارة حالة Flow](/ar/guides/flows/mastering-flow-state)
|
||||
- [حفظ Flow](/ar/concepts/flows#persistence)
|
||||
- [التوجيه مع @router](/ar/concepts/flows#router)
|
||||
- [إدخال بشري عند التنفيذ](/ar/learn/human-input-on-execution)
|
||||
- [الذاكرة](/ar/concepts/memory)
|
||||
80
docs/ar/learn/human-in-the-loop.mdx
Normal file
80
docs/ar/learn/human-in-the-loop.mdx
Normal file
@@ -0,0 +1,80 @@
|
||||
---
|
||||
title: "سير عمل التدخل البشري (HITL)"
|
||||
description: "تعلم كيفية تنفيذ سير عمل التدخل البشري في CrewAI لتعزيز صنع القرار"
|
||||
icon: "user-check"
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
التدخل البشري (HITL) هو نهج قوي يجمع بين الذكاء الاصطناعي والخبرة البشرية لتعزيز صنع القرار وتحسين نتائج المهام. يوفر CrewAI طرقًا متعددة لتنفيذ HITL حسب احتياجاتك.
|
||||
|
||||
## اختيار نهج HITL
|
||||
|
||||
يوفر CrewAI نهجين رئيسيين لتنفيذ سير عمل التدخل البشري:
|
||||
|
||||
| النهج | الأنسب لـ | التكامل | الإصدار |
|
||||
|----------|----------|-------------|---------|
|
||||
| **قائم على Flow** (مزخرف `@human_feedback`) | التطوير المحلي، المراجعة عبر وحدة التحكم، سير العمل المتزامن | [التغذية الراجعة البشرية في Flows](/ar/learn/human-feedback-in-flows) | **1.8.0+** |
|
||||
| **قائم على Webhook** (المؤسسات) | نشر الإنتاج، سير العمل غير المتزامن، التكاملات الخارجية (Slack، Teams، إلخ) | هذا الدليل | - |
|
||||
|
||||
<Tip>
|
||||
إذا كنت تبني Flows وتريد إضافة خطوات مراجعة بشرية مع توجيه بناءً على التعليقات، اطلع على دليل [التغذية الراجعة البشرية في Flows](/ar/learn/human-feedback-in-flows) لمزخرف `@human_feedback`.
|
||||
</Tip>
|
||||
|
||||
## إعداد سير عمل HITL القائم على Webhook
|
||||
|
||||
<Steps>
|
||||
<Step title="تهيئة المهمة">
|
||||
أعدّ مهمتك مع تمكين إدخال بشري.
|
||||
</Step>
|
||||
|
||||
<Step title="توفير عنوان Webhook URL">
|
||||
عند تشغيل Crew، أدرج عنوان Webhook URL لإدخال بشري.
|
||||
</Step>
|
||||
|
||||
<Step title="تلقي إشعار Webhook">
|
||||
بمجرد إتمام Crew المهمة التي تتطلب إدخالاً بشريًا، ستتلقى إشعار Webhook.
|
||||
</Step>
|
||||
|
||||
<Step title="مراجعة مخرجات المهمة">
|
||||
سيتوقف النظام في حالة `Pending Human Input`. راجع مخرجات المهمة بعناية.
|
||||
</Step>
|
||||
|
||||
<Step title="إرسال التغذية الراجعة البشرية">
|
||||
استدعِ نقطة نهاية الاستئناف لـ Crew.
|
||||
|
||||
<Warning>
|
||||
**مهم: يجب توفير عناوين Webhook URL مرة أخرى**:
|
||||
يجب توفير نفس عناوين Webhook URL في استدعاء الاستئناف التي استخدمتها في استدعاء الانطلاق.
|
||||
</Warning>
|
||||
</Step>
|
||||
|
||||
<Step title="معالجة التعليقات السلبية">
|
||||
إذا قدمت تعليقات سلبية، سيعيد Crew محاولة المهمة مع سياق إضافي من تعليقاتك.
|
||||
</Step>
|
||||
|
||||
<Step title="استمرار التنفيذ">
|
||||
عند إرسال تعليقات إيجابية، سيستمر التنفيذ إلى الخطوات التالية.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## أفضل الممارسات
|
||||
|
||||
- **كن محددًا**: قدم تعليقات واضحة وقابلة للتنفيذ
|
||||
- **ابقَ ذا صلة**: أدرج فقط معلومات تساعد في تحسين تنفيذ المهمة
|
||||
- **كن في الوقت المناسب**: استجب لمطالبات HITL بسرعة لتجنب تأخير سير العمل
|
||||
- **راجع بعناية**: تحقق من تعليقاتك قبل الإرسال لضمان الدقة
|
||||
|
||||
## حالات الاستخدام الشائعة
|
||||
|
||||
سير عمل HITL مفيدة بشكل خاص لـ:
|
||||
- ضمان الجودة والتحقق
|
||||
- سيناريوهات صنع القرار المعقدة
|
||||
- العمليات الحساسة أو عالية المخاطر
|
||||
- المهام الإبداعية التي تتطلب حكمًا بشريًا
|
||||
- مراجعات الامتثال والتنظيم
|
||||
|
||||
## ميزات المؤسسات
|
||||
|
||||
<Card title="منصة إدارة HITL للـ Flow" icon="users-gear" href="/ar/enterprise/features/flow-hitl-management">
|
||||
يوفر CrewAI Enterprise نظام إدارة HITL شامل لـ Flows مع مراجعة داخل المنصة وتعيين المستجيبين والأذونات وسياسات التصعيد وإدارة SLA والتوجيه الديناميكي والتحليلات الكاملة. [تعلم المزيد](/ar/enterprise/features/flow-hitl-management)
|
||||
</Card>
|
||||
99
docs/ar/learn/human-input-on-execution.mdx
Normal file
99
docs/ar/learn/human-input-on-execution.mdx
Normal file
@@ -0,0 +1,99 @@
|
||||
---
|
||||
title: الإدخال البشري أثناء التنفيذ
|
||||
description: دمج CrewAI مع الإدخال البشري أثناء التنفيذ في عمليات اتخاذ القرارات المعقدة والاستفادة الكاملة من إمكانيات خصائص وأدوات الوكيل.
|
||||
icon: user-plus
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## الإدخال البشري في تنفيذ الوكيل
|
||||
|
||||
يُعد الإدخال البشري أمراً بالغ الأهمية في العديد من سيناريوهات تنفيذ الوكلاء، حيث يسمح للوكلاء بطلب معلومات إضافية أو توضيحات عند الضرورة.
|
||||
هذه الميزة مفيدة بشكل خاص في عمليات اتخاذ القرارات المعقدة أو عندما يحتاج الوكلاء إلى مزيد من التفاصيل لإكمال مهمة بفعالية.
|
||||
|
||||
## استخدام الإدخال البشري مع CrewAI
|
||||
|
||||
لدمج الإدخال البشري في تنفيذ الوكيل، قم بتعيين علامة `human_input` في تعريف المهمة. عند تفعيلها، يطلب الوكيل من المستخدم إدخالاً قبل تقديم إجابته النهائية.
|
||||
يمكن أن يوفر هذا الإدخال سياقاً إضافياً، أو يوضح الغموض، أو يتحقق من مخرجات الوكيل.
|
||||
|
||||
### مثال:
|
||||
|
||||
```shell
|
||||
pip install crewai
|
||||
```
|
||||
|
||||
```python Code
|
||||
import os
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import SerperDevTool
|
||||
|
||||
os.environ["SERPER_API_KEY"] = "Your Key" # serper.dev API key
|
||||
os.environ["OPENAI_API_KEY"] = "Your Key"
|
||||
|
||||
# Loading Tools
|
||||
search_tool = SerperDevTool()
|
||||
|
||||
# Define your agents with roles, goals, tools, and additional attributes
|
||||
researcher = Agent(
|
||||
role='Senior Research Analyst',
|
||||
goal='Uncover cutting-edge developments in AI and data science',
|
||||
backstory=(
|
||||
"You are a Senior Research Analyst at a leading tech think tank. "
|
||||
"Your expertise lies in identifying emerging trends and technologies in AI and data science. "
|
||||
"You have a knack for dissecting complex data and presenting actionable insights."
|
||||
),
|
||||
verbose=True,
|
||||
allow_delegation=False,
|
||||
tools=[search_tool]
|
||||
)
|
||||
writer = Agent(
|
||||
role='Tech Content Strategist',
|
||||
goal='Craft compelling content on tech advancements',
|
||||
backstory=(
|
||||
"You are a renowned Tech Content Strategist, known for your insightful and engaging articles on technology and innovation. "
|
||||
"With a deep understanding of the tech industry, you transform complex concepts into compelling narratives."
|
||||
),
|
||||
verbose=True,
|
||||
allow_delegation=True,
|
||||
tools=[search_tool],
|
||||
cache=False, # Disable cache for this agent
|
||||
)
|
||||
|
||||
# Create tasks for your agents
|
||||
task1 = Task(
|
||||
description=(
|
||||
"Conduct a comprehensive analysis of the latest advancements in AI in 2025. "
|
||||
"Identify key trends, breakthrough technologies, and potential industry impacts. "
|
||||
"Compile your findings in a detailed report. "
|
||||
"Make sure to check with a human if the draft is good before finalizing your answer."
|
||||
),
|
||||
expected_output='A comprehensive full report on the latest AI advancements in 2025, leave nothing out',
|
||||
agent=researcher,
|
||||
human_input=True
|
||||
)
|
||||
|
||||
task2 = Task(
|
||||
description=(
|
||||
"Using the insights from the researcher\'s report, develop an engaging blog post that highlights the most significant AI advancements. "
|
||||
"Your post should be informative yet accessible, catering to a tech-savvy audience. "
|
||||
"Aim for a narrative that captures the essence of these breakthroughs and their implications for the future."
|
||||
),
|
||||
expected_output='A compelling 3 paragraphs blog post formatted as markdown about the latest AI advancements in 2025',
|
||||
agent=writer,
|
||||
human_input=True
|
||||
)
|
||||
|
||||
# Instantiate your crew with a sequential process
|
||||
crew = Crew(
|
||||
agents=[researcher, writer],
|
||||
tasks=[task1, task2],
|
||||
verbose=True,
|
||||
memory=True,
|
||||
planning=True # Enable planning feature for the crew
|
||||
)
|
||||
|
||||
# Get your crew to work!
|
||||
result = crew.kickoff()
|
||||
|
||||
print("######################")
|
||||
print(result)
|
||||
```
|
||||
306
docs/ar/learn/kickoff-async.mdx
Normal file
306
docs/ar/learn/kickoff-async.mdx
Normal file
@@ -0,0 +1,306 @@
|
||||
---
|
||||
title: تشغيل الطاقم بشكل غير متزامن
|
||||
description: تشغيل الطاقم بشكل غير متزامن
|
||||
icon: rocket-launch
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## مقدمة
|
||||
|
||||
يوفر CrewAI القدرة على تشغيل طاقم بشكل غير متزامن، مما يتيح لك بدء تنفيذ الطاقم بطريقة غير حاجبة.
|
||||
هذه الميزة مفيدة بشكل خاص عندما تريد تشغيل عدة أطقم بشكل متزامن أو عندما تحتاج إلى أداء مهام أخرى أثناء تنفيذ الطاقم.
|
||||
|
||||
يقدم CrewAI نهجين للتنفيذ غير المتزامن:
|
||||
|
||||
| الطريقة | النوع | الوصف |
|
||||
|--------|------|-------------|
|
||||
| `akickoff()` | غير متزامن أصلي | async/await أصلي عبر سلسلة التنفيذ بالكامل |
|
||||
| `kickoff_async()` | قائم على الخيوط | يغلف التنفيذ المتزامن في `asyncio.to_thread` |
|
||||
|
||||
<Note>
|
||||
لأحمال العمل عالية التزامن، يُوصى باستخدام `akickoff()` لأنه يستخدم async أصلي لتنفيذ المهام وعمليات الذاكرة واسترجاع المعرفة.
|
||||
</Note>
|
||||
|
||||
## التنفيذ غير المتزامن الأصلي مع `akickoff()`
|
||||
|
||||
توفر طريقة `akickoff()` تنفيذاً غير متزامن أصلياً حقيقياً، باستخدام async/await عبر سلسلة التنفيذ بالكامل بما في ذلك تنفيذ المهام وعمليات الذاكرة واستعلامات المعرفة.
|
||||
|
||||
### توقيع الطريقة
|
||||
|
||||
```python Code
|
||||
async def akickoff(self, inputs: dict) -> CrewOutput:
|
||||
```
|
||||
|
||||
### المعاملات
|
||||
|
||||
- `inputs` (dict): قاموس يحتوي على بيانات الإدخال المطلوبة للمهام.
|
||||
|
||||
### القيمة المُرجعة
|
||||
|
||||
- `CrewOutput`: كائن يمثل نتيجة تنفيذ الطاقم.
|
||||
|
||||
### مثال: تنفيذ طاقم غير متزامن أصلي
|
||||
|
||||
```python Code
|
||||
import asyncio
|
||||
from crewai import Crew, Agent, Task
|
||||
|
||||
# Create an agent
|
||||
coding_agent = Agent(
|
||||
role="Python Data Analyst",
|
||||
goal="Analyze data and provide insights using Python",
|
||||
backstory="You are an experienced data analyst with strong Python skills.",
|
||||
allow_code_execution=True
|
||||
)
|
||||
|
||||
# Create a task
|
||||
data_analysis_task = Task(
|
||||
description="Analyze the given dataset and calculate the average age of participants. Ages: {ages}",
|
||||
agent=coding_agent,
|
||||
expected_output="The average age of the participants."
|
||||
)
|
||||
|
||||
# Create a crew
|
||||
analysis_crew = Crew(
|
||||
agents=[coding_agent],
|
||||
tasks=[data_analysis_task]
|
||||
)
|
||||
|
||||
# Native async execution
|
||||
async def main():
|
||||
result = await analysis_crew.akickoff(inputs={"ages": [25, 30, 35, 40, 45]})
|
||||
print("Crew Result:", result)
|
||||
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
### مثال: عدة أطقم غير متزامنة أصلية
|
||||
|
||||
تشغيل عدة أطقم بشكل متزامن باستخدام `asyncio.gather()` مع async أصلي:
|
||||
|
||||
```python Code
|
||||
import asyncio
|
||||
from crewai import Crew, Agent, Task
|
||||
|
||||
coding_agent = Agent(
|
||||
role="Python Data Analyst",
|
||||
goal="Analyze data and provide insights using Python",
|
||||
backstory="You are an experienced data analyst with strong Python skills.",
|
||||
allow_code_execution=True
|
||||
)
|
||||
|
||||
task_1 = Task(
|
||||
description="Analyze the first dataset and calculate the average age. Ages: {ages}",
|
||||
agent=coding_agent,
|
||||
expected_output="The average age of the participants."
|
||||
)
|
||||
|
||||
task_2 = Task(
|
||||
description="Analyze the second dataset and calculate the average age. Ages: {ages}",
|
||||
agent=coding_agent,
|
||||
expected_output="The average age of the participants."
|
||||
)
|
||||
|
||||
crew_1 = Crew(agents=[coding_agent], tasks=[task_1])
|
||||
crew_2 = Crew(agents=[coding_agent], tasks=[task_2])
|
||||
|
||||
async def main():
|
||||
results = await asyncio.gather(
|
||||
crew_1.akickoff(inputs={"ages": [25, 30, 35, 40, 45]}),
|
||||
crew_2.akickoff(inputs={"ages": [20, 22, 24, 28, 30]})
|
||||
)
|
||||
|
||||
for i, result in enumerate(results, 1):
|
||||
print(f"Crew {i} Result:", result)
|
||||
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
### مثال: async أصلي لمدخلات متعددة
|
||||
|
||||
استخدم `akickoff_for_each()` لتنفيذ طاقمك على مدخلات متعددة بشكل متزامن مع async أصلي:
|
||||
|
||||
```python Code
|
||||
import asyncio
|
||||
from crewai import Crew, Agent, Task
|
||||
|
||||
coding_agent = Agent(
|
||||
role="Python Data Analyst",
|
||||
goal="Analyze data and provide insights using Python",
|
||||
backstory="You are an experienced data analyst with strong Python skills.",
|
||||
allow_code_execution=True
|
||||
)
|
||||
|
||||
data_analysis_task = Task(
|
||||
description="Analyze the dataset and calculate the average age. Ages: {ages}",
|
||||
agent=coding_agent,
|
||||
expected_output="The average age of the participants."
|
||||
)
|
||||
|
||||
analysis_crew = Crew(
|
||||
agents=[coding_agent],
|
||||
tasks=[data_analysis_task]
|
||||
)
|
||||
|
||||
async def main():
|
||||
datasets = [
|
||||
{"ages": [25, 30, 35, 40, 45]},
|
||||
{"ages": [20, 22, 24, 28, 30]},
|
||||
{"ages": [30, 35, 40, 45, 50]}
|
||||
]
|
||||
|
||||
results = await analysis_crew.akickoff_for_each(datasets)
|
||||
|
||||
for i, result in enumerate(results, 1):
|
||||
print(f"Dataset {i} Result:", result)
|
||||
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
## التنفيذ غير المتزامن القائم على الخيوط مع `kickoff_async()`
|
||||
|
||||
توفر طريقة `kickoff_async()` تنفيذاً غير متزامن عن طريق تغليف `kickoff()` المتزامن في خيط. هذا مفيد للتكامل البسيط مع async أو للتوافق مع الإصدارات السابقة.
|
||||
|
||||
### توقيع الطريقة
|
||||
|
||||
```python Code
|
||||
async def kickoff_async(self, inputs: dict) -> CrewOutput:
|
||||
```
|
||||
|
||||
### المعاملات
|
||||
|
||||
- `inputs` (dict): قاموس يحتوي على بيانات الإدخال المطلوبة للمهام.
|
||||
|
||||
### القيمة المُرجعة
|
||||
|
||||
- `CrewOutput`: كائن يمثل نتيجة تنفيذ الطاقم.
|
||||
|
||||
### مثال: تنفيذ غير متزامن قائم على الخيوط
|
||||
|
||||
```python Code
|
||||
import asyncio
|
||||
from crewai import Crew, Agent, Task
|
||||
|
||||
coding_agent = Agent(
|
||||
role="Python Data Analyst",
|
||||
goal="Analyze data and provide insights using Python",
|
||||
backstory="You are an experienced data analyst with strong Python skills.",
|
||||
allow_code_execution=True
|
||||
)
|
||||
|
||||
data_analysis_task = Task(
|
||||
description="Analyze the given dataset and calculate the average age of participants. Ages: {ages}",
|
||||
agent=coding_agent,
|
||||
expected_output="The average age of the participants."
|
||||
)
|
||||
|
||||
analysis_crew = Crew(
|
||||
agents=[coding_agent],
|
||||
tasks=[data_analysis_task]
|
||||
)
|
||||
|
||||
async def async_crew_execution():
|
||||
result = await analysis_crew.kickoff_async(inputs={"ages": [25, 30, 35, 40, 45]})
|
||||
print("Crew Result:", result)
|
||||
|
||||
asyncio.run(async_crew_execution())
|
||||
```
|
||||
|
||||
### مثال: عدة أطقم غير متزامنة قائمة على الخيوط
|
||||
|
||||
```python Code
|
||||
import asyncio
|
||||
from crewai import Crew, Agent, Task
|
||||
|
||||
coding_agent = Agent(
|
||||
role="Python Data Analyst",
|
||||
goal="Analyze data and provide insights using Python",
|
||||
backstory="You are an experienced data analyst with strong Python skills.",
|
||||
allow_code_execution=True
|
||||
)
|
||||
|
||||
task_1 = Task(
|
||||
description="Analyze the first dataset and calculate the average age of participants. Ages: {ages}",
|
||||
agent=coding_agent,
|
||||
expected_output="The average age of the participants."
|
||||
)
|
||||
|
||||
task_2 = Task(
|
||||
description="Analyze the second dataset and calculate the average age of participants. Ages: {ages}",
|
||||
agent=coding_agent,
|
||||
expected_output="The average age of the participants."
|
||||
)
|
||||
|
||||
crew_1 = Crew(agents=[coding_agent], tasks=[task_1])
|
||||
crew_2 = Crew(agents=[coding_agent], tasks=[task_2])
|
||||
|
||||
async def async_multiple_crews():
|
||||
result_1 = crew_1.kickoff_async(inputs={"ages": [25, 30, 35, 40, 45]})
|
||||
result_2 = crew_2.kickoff_async(inputs={"ages": [20, 22, 24, 28, 30]})
|
||||
|
||||
results = await asyncio.gather(result_1, result_2)
|
||||
|
||||
for i, result in enumerate(results, 1):
|
||||
print(f"Crew {i} Result:", result)
|
||||
|
||||
asyncio.run(async_multiple_crews())
|
||||
```
|
||||
|
||||
## البث غير المتزامن
|
||||
|
||||
تدعم كلتا الطريقتين غير المتزامنتين البث عند تعيين `stream=True` على الطاقم:
|
||||
|
||||
```python Code
|
||||
import asyncio
|
||||
from crewai import Crew, Agent, Task
|
||||
|
||||
agent = Agent(
|
||||
role="Researcher",
|
||||
goal="Research and summarize topics",
|
||||
backstory="You are an expert researcher."
|
||||
)
|
||||
|
||||
task = Task(
|
||||
description="Research the topic: {topic}",
|
||||
agent=agent,
|
||||
expected_output="A comprehensive summary of the topic."
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[agent],
|
||||
tasks=[task],
|
||||
stream=True # Enable streaming
|
||||
)
|
||||
|
||||
async def main():
|
||||
streaming_output = await crew.akickoff(inputs={"topic": "AI trends in 2024"})
|
||||
|
||||
# Async iteration over streaming chunks
|
||||
async for chunk in streaming_output:
|
||||
print(f"Chunk: {chunk.content}")
|
||||
|
||||
# Access final result after streaming completes
|
||||
result = streaming_output.result
|
||||
print(f"Final result: {result.raw}")
|
||||
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
## حالات الاستخدام المحتملة
|
||||
|
||||
- **توليد المحتوى بالتوازي**: تشغيل عدة أطقم مستقلة بشكل غير متزامن، كل منها مسؤول عن توليد محتوى حول مواضيع مختلفة. على سبيل المثال، قد يبحث طاقم ويصوغ مقالاً عن اتجاهات الذكاء الاصطناعي، بينما يولد طاقم آخر منشورات وسائل التواصل الاجتماعي حول إطلاق منتج جديد.
|
||||
|
||||
- **مهام أبحاث السوق المتزامنة**: إطلاق عدة أطقم بشكل غير متزامن لإجراء أبحاث السوق بالتوازي. قد يحلل طاقم اتجاهات الصناعة، بينما يفحص آخر استراتيجيات المنافسين، ويقيّم ثالث مشاعر المستهلكين.
|
||||
|
||||
- **وحدات تخطيط السفر المستقلة**: تنفيذ أطقم منفصلة للتخطيط المستقل لجوانب مختلفة من رحلة. قد يتعامل طاقم مع خيارات الرحلات الجوية، وآخر مع الإقامة، وثالث يخطط للأنشطة.
|
||||
|
||||
## الاختيار بين `akickoff()` و `kickoff_async()`
|
||||
|
||||
| الميزة | `akickoff()` | `kickoff_async()` |
|
||||
|---------|--------------|-------------------|
|
||||
| نموذج التنفيذ | async/await أصلي | غلاف قائم على الخيوط |
|
||||
| تنفيذ المهام | غير متزامن مع `aexecute_sync()` | متزامن في مجمع الخيوط |
|
||||
| عمليات الذاكرة | غير متزامنة | متزامنة في مجمع الخيوط |
|
||||
| استرجاع المعرفة | غير متزامن | متزامن في مجمع الخيوط |
|
||||
| الأفضل لـ | أحمال العمل عالية التزامن والمرتبطة بالإدخال/الإخراج | التكامل البسيط مع async |
|
||||
| دعم البث | نعم | نعم |
|
||||
54
docs/ar/learn/kickoff-for-each.mdx
Normal file
54
docs/ar/learn/kickoff-for-each.mdx
Normal file
@@ -0,0 +1,54 @@
|
||||
---
|
||||
title: تشغيل الطاقم لكل عنصر
|
||||
description: تشغيل الطاقم لكل عنصر في قائمة
|
||||
icon: at
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## مقدمة
|
||||
|
||||
يوفر CrewAI القدرة على تشغيل طاقم لكل عنصر في قائمة، مما يتيح لك تنفيذ الطاقم لكل عنصر في القائمة.
|
||||
هذه الميزة مفيدة بشكل خاص عندما تحتاج إلى تنفيذ نفس مجموعة المهام لعناصر متعددة.
|
||||
|
||||
## تشغيل طاقم لكل عنصر
|
||||
|
||||
لتشغيل طاقم لكل عنصر في قائمة، استخدم طريقة `kickoff_for_each()`.
|
||||
تنفذ هذه الطريقة الطاقم لكل عنصر في القائمة، مما يتيح لك معالجة عناصر متعددة بكفاءة.
|
||||
|
||||
إليك مثالاً على كيفية تشغيل طاقم لكل عنصر في قائمة:
|
||||
|
||||
```python Code
|
||||
from crewai import Crew, Agent, Task
|
||||
|
||||
# Create an agent with code execution enabled
|
||||
coding_agent = Agent(
|
||||
role="Python Data Analyst",
|
||||
goal="Analyze data and provide insights using Python",
|
||||
backstory="You are an experienced data analyst with strong Python skills.",
|
||||
allow_code_execution=True
|
||||
)
|
||||
|
||||
# Create a task that requires code execution
|
||||
data_analysis_task = Task(
|
||||
description="Analyze the given dataset and calculate the average age of participants. Ages: {ages}",
|
||||
agent=coding_agent,
|
||||
expected_output="The average age calculated from the dataset"
|
||||
)
|
||||
|
||||
# Create a crew and add the task
|
||||
analysis_crew = Crew(
|
||||
agents=[coding_agent],
|
||||
tasks=[data_analysis_task],
|
||||
verbose=True,
|
||||
memory=False
|
||||
)
|
||||
|
||||
datasets = [
|
||||
{ "ages": [25, 30, 35, 40, 45] },
|
||||
{ "ages": [20, 25, 30, 35, 40] },
|
||||
{ "ages": [30, 35, 40, 45, 50] }
|
||||
]
|
||||
|
||||
# Execute the crew
|
||||
result = analysis_crew.kickoff_for_each(inputs=datasets)
|
||||
```
|
||||
358
docs/ar/learn/litellm-removal-guide.mdx
Normal file
358
docs/ar/learn/litellm-removal-guide.mdx
Normal file
@@ -0,0 +1,358 @@
|
||||
---
|
||||
title: استخدام CrewAI بدون LiteLLM
|
||||
description: كيفية استخدام CrewAI مع التكاملات الأصلية للمزودين وإزالة اعتمادية LiteLLM من مشروعك.
|
||||
icon: shield-check
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## نظرة عامة
|
||||
|
||||
يدعم CrewAI مسارين للاتصال بمزودي LLM:
|
||||
|
||||
1. **التكاملات الأصلية** — اتصالات SDK مباشرة مع OpenAI وAnthropic وGoogle Gemini وAzure OpenAI وAWS Bedrock
|
||||
2. **LiteLLM كاحتياط** — طبقة ترجمة تدعم أكثر من 100 مزود إضافي
|
||||
|
||||
يشرح هذا الدليل كيفية استخدام CrewAI حصرياً مع التكاملات الأصلية للمزودين، مع إزالة أي اعتمادية على LiteLLM.
|
||||
|
||||
<Warning>
|
||||
تم عزل حزمة `litellm` على PyPI بسبب حادث أمني/موثوقية. إذا كنت تعتمد على مزودين يحتاجون LiteLLM، يجب عليك الانتقال إلى التكاملات الأصلية. توفر لك تكاملات CrewAI الأصلية الوظائف الكاملة بدون LiteLLM.
|
||||
</Warning>
|
||||
|
||||
## لماذا إزالة LiteLLM؟
|
||||
|
||||
- **تقليل سطح الاعتماديات** — حزم أقل تعني مخاطر أقل محتملة في سلسلة التوريد
|
||||
- **أداء أفضل** — تتواصل حزم SDK الأصلية مباشرة مع واجهات برمجة تطبيقات المزودين، مما يلغي طبقة الترجمة
|
||||
- **تصحيح أخطاء أبسط** — طبقة تجريد واحدة أقل بين كودك والمزود
|
||||
- **حجم تثبيت أصغر** — يجلب LiteLLM العديد من الاعتماديات العابرة
|
||||
|
||||
## المزودون الأصليون (لا يحتاجون LiteLLM)
|
||||
|
||||
هؤلاء المزودون يستخدمون حزم SDK الخاصة بهم ويعملون بدون تثبيت LiteLLM:
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="OpenAI" icon="bolt">
|
||||
GPT-4o، GPT-4o-mini، o1، o3-mini، والمزيد.
|
||||
```bash
|
||||
uv add "crewai[openai]"
|
||||
```
|
||||
</Card>
|
||||
<Card title="Anthropic" icon="a">
|
||||
Claude Sonnet، Claude Haiku، والمزيد.
|
||||
```bash
|
||||
uv add "crewai[anthropic]"
|
||||
```
|
||||
</Card>
|
||||
<Card title="Google Gemini" icon="google">
|
||||
Gemini 2.0 Flash، Gemini 2.0 Pro، والمزيد.
|
||||
```bash
|
||||
uv add "crewai[gemini]"
|
||||
```
|
||||
</Card>
|
||||
<Card title="Azure OpenAI" icon="microsoft">
|
||||
نماذج OpenAI المستضافة على Azure.
|
||||
```bash
|
||||
uv add "crewai[azure]"
|
||||
```
|
||||
</Card>
|
||||
<Card title="AWS Bedrock" icon="aws">
|
||||
Claude، Llama، Titan، والمزيد عبر AWS.
|
||||
```bash
|
||||
uv add "crewai[bedrock]"
|
||||
```
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Info>
|
||||
إذا كنت تستخدم المزودين الأصليين فقط، فلن تحتاج **أبداً** لتثبيت `crewai[litellm]`. حزمة `crewai` الأساسية بالإضافة إلى الإضافة الخاصة بالمزود الذي اخترته هي كل ما تحتاجه.
|
||||
</Info>
|
||||
|
||||
## كيفية التحقق مما إذا كنت تستخدم LiteLLM
|
||||
|
||||
### تحقق من سلاسل النماذج الخاصة بك
|
||||
|
||||
إذا كان كودك يستخدم بادئات النماذج هذه، فأنت تمرر عبر LiteLLM:
|
||||
|
||||
| البادئة | المزود | يستخدم LiteLLM؟ |
|
||||
|--------|----------|---------------|
|
||||
| `ollama/` | Ollama | ✅ نعم |
|
||||
| `groq/` | Groq | ✅ نعم |
|
||||
| `together_ai/` | Together AI | ✅ نعم |
|
||||
| `mistral/` | Mistral | ✅ نعم |
|
||||
| `cohere/` | Cohere | ✅ نعم |
|
||||
| `huggingface/` | Hugging Face | ✅ نعم |
|
||||
| `openai/` | OpenAI | ❌ أصلي |
|
||||
| `anthropic/` | Anthropic | ❌ أصلي |
|
||||
| `gemini/` | Google Gemini | ❌ أصلي |
|
||||
| `azure/` | Azure OpenAI | ❌ أصلي |
|
||||
| `bedrock/` | AWS Bedrock | ❌ أصلي |
|
||||
|
||||
### تحقق مما إذا كان LiteLLM مثبتاً
|
||||
|
||||
```bash
|
||||
# Using pip
|
||||
pip show litellm
|
||||
|
||||
# Using uv
|
||||
uv pip show litellm
|
||||
```
|
||||
|
||||
إذا أرجع الأمر معلومات الحزمة، فإن LiteLLM مثبت في بيئتك.
|
||||
|
||||
### تحقق من اعتمادياتك
|
||||
|
||||
انظر إلى ملف `pyproject.toml` الخاص بك بحثاً عن `crewai[litellm]`:
|
||||
|
||||
```toml
|
||||
# If you see this, you have LiteLLM as a dependency
|
||||
dependencies = [
|
||||
"crewai[litellm]>=0.100.0", # ← Uses LiteLLM
|
||||
]
|
||||
|
||||
# Change to a native provider extra instead
|
||||
dependencies = [
|
||||
"crewai[openai]>=0.100.0", # ← Native, no LiteLLM
|
||||
]
|
||||
```
|
||||
|
||||
## دليل الانتقال
|
||||
|
||||
### الخطوة 1: حدد مزودك الحالي
|
||||
|
||||
ابحث عن جميع استدعاءات `LLM()` وسلاسل النماذج في كودك:
|
||||
|
||||
```bash
|
||||
# Search your codebase for LLM model strings
|
||||
grep -r "LLM(" --include="*.py" .
|
||||
grep -r "llm=" --include="*.yaml" .
|
||||
grep -r "llm:" --include="*.yaml" .
|
||||
```
|
||||
|
||||
### الخطوة 2: انتقل إلى مزود أصلي
|
||||
|
||||
<Tabs>
|
||||
<Tab title="الانتقال إلى OpenAI">
|
||||
```python
|
||||
from crewai import LLM
|
||||
|
||||
# Before (LiteLLM):
|
||||
# llm = LLM(model="groq/llama-3.1-70b")
|
||||
|
||||
# After (Native):
|
||||
llm = LLM(model="openai/gpt-4o")
|
||||
```
|
||||
|
||||
```bash
|
||||
# Install
|
||||
uv add "crewai[openai]"
|
||||
|
||||
# Set your API key
|
||||
export OPENAI_API_KEY="sk-..."
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="الانتقال إلى Anthropic">
|
||||
```python
|
||||
from crewai import LLM
|
||||
|
||||
# Before (LiteLLM):
|
||||
# llm = LLM(model="together_ai/meta-llama/Meta-Llama-3.1-70B")
|
||||
|
||||
# After (Native):
|
||||
llm = LLM(model="anthropic/claude-sonnet-4-20250514")
|
||||
```
|
||||
|
||||
```bash
|
||||
# Install
|
||||
uv add "crewai[anthropic]"
|
||||
|
||||
# Set your API key
|
||||
export ANTHROPIC_API_KEY="sk-ant-..."
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="الانتقال إلى Gemini">
|
||||
```python
|
||||
from crewai import LLM
|
||||
|
||||
# Before (LiteLLM):
|
||||
# llm = LLM(model="mistral/mistral-large-latest")
|
||||
|
||||
# After (Native):
|
||||
llm = LLM(model="gemini/gemini-2.0-flash")
|
||||
```
|
||||
|
||||
```bash
|
||||
# Install
|
||||
uv add "crewai[gemini]"
|
||||
|
||||
# Set your API key
|
||||
export GEMINI_API_KEY="..."
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="الانتقال إلى Azure OpenAI">
|
||||
```python
|
||||
from crewai import LLM
|
||||
|
||||
# After (Native):
|
||||
llm = LLM(
|
||||
model="azure/your-deployment-name",
|
||||
api_key="your-azure-api-key",
|
||||
base_url="https://your-resource.openai.azure.com",
|
||||
api_version="2024-06-01"
|
||||
)
|
||||
```
|
||||
|
||||
```bash
|
||||
# Install
|
||||
uv add "crewai[azure]"
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="الانتقال إلى AWS Bedrock">
|
||||
```python
|
||||
from crewai import LLM
|
||||
|
||||
# After (Native):
|
||||
llm = LLM(
|
||||
model="bedrock/anthropic.claude-3-5-sonnet-20241022-v2:0",
|
||||
aws_region_name="us-east-1"
|
||||
)
|
||||
```
|
||||
|
||||
```bash
|
||||
# Install
|
||||
uv add "crewai[bedrock]"
|
||||
|
||||
# Configure AWS credentials
|
||||
export AWS_ACCESS_KEY_ID="..."
|
||||
export AWS_SECRET_ACCESS_KEY="..."
|
||||
export AWS_DEFAULT_REGION="us-east-1"
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### الخطوة 3: الاحتفاظ بـ Ollama بدون LiteLLM
|
||||
|
||||
إذا كنت تستخدم Ollama وتريد الاستمرار في استخدامه، يمكنك الاتصال عبر واجهة برمجة تطبيقات Ollama المتوافقة مع OpenAI:
|
||||
|
||||
```python
|
||||
from crewai import LLM
|
||||
|
||||
# Before (LiteLLM):
|
||||
# llm = LLM(model="ollama/llama3")
|
||||
|
||||
# After (OpenAI-compatible mode, no LiteLLM needed):
|
||||
llm = LLM(
|
||||
model="openai/llama3",
|
||||
base_url="http://localhost:11434/v1",
|
||||
api_key="ollama" # Ollama doesn't require a real API key
|
||||
)
|
||||
```
|
||||
|
||||
<Tip>
|
||||
العديد من خوادم الاستدلال المحلية (Ollama، vLLM، LM Studio، llama.cpp) توفر واجهة برمجة تطبيقات متوافقة مع OpenAI. يمكنك استخدام بادئة `openai/` مع `base_url` مخصص للاتصال بأي منها بشكل أصلي.
|
||||
</Tip>
|
||||
|
||||
### الخطوة 4: تحديث إعدادات YAML
|
||||
|
||||
```yaml
|
||||
# Before (LiteLLM providers):
|
||||
researcher:
|
||||
role: Research Specialist
|
||||
goal: Conduct research
|
||||
backstory: A dedicated researcher
|
||||
llm: groq/llama-3.1-70b # ← LiteLLM
|
||||
|
||||
# After (Native provider):
|
||||
researcher:
|
||||
role: Research Specialist
|
||||
goal: Conduct research
|
||||
backstory: A dedicated researcher
|
||||
llm: openai/gpt-4o # ← Native
|
||||
```
|
||||
|
||||
### الخطوة 5: إزالة LiteLLM
|
||||
|
||||
بمجرد انتقال جميع مراجع النماذج الخاصة بك:
|
||||
|
||||
```bash
|
||||
# Remove litellm from your project
|
||||
uv remove litellm
|
||||
|
||||
# Or if using pip
|
||||
pip uninstall litellm
|
||||
|
||||
# Update your pyproject.toml: change crewai[litellm] to your provider extra
|
||||
# e.g., crewai[openai], crewai[anthropic], crewai[gemini]
|
||||
```
|
||||
|
||||
### الخطوة 6: التحقق
|
||||
|
||||
شغّل مشروعك وتأكد من أن كل شيء يعمل:
|
||||
|
||||
```bash
|
||||
# Run your crew
|
||||
crewai run
|
||||
|
||||
# Or run your tests
|
||||
uv run pytest
|
||||
```
|
||||
|
||||
## مرجع سريع: خريطة سلاسل النماذج
|
||||
|
||||
فيما يلي مسارات الانتقال الشائعة من المزودين المعتمدين على LiteLLM إلى المزودين الأصليين:
|
||||
|
||||
```python
|
||||
from crewai import LLM
|
||||
|
||||
# ─── LiteLLM providers → Native alternatives ────────────────────
|
||||
|
||||
# Groq → OpenAI or Anthropic
|
||||
# llm = LLM(model="groq/llama-3.1-70b")
|
||||
llm = LLM(model="openai/gpt-4o-mini") # Fast & affordable
|
||||
llm = LLM(model="anthropic/claude-haiku-3-5") # Fast & affordable
|
||||
|
||||
# Together AI → OpenAI or Gemini
|
||||
# llm = LLM(model="together_ai/meta-llama/Meta-Llama-3.1-70B")
|
||||
llm = LLM(model="openai/gpt-4o") # High quality
|
||||
llm = LLM(model="gemini/gemini-2.0-flash") # Fast & capable
|
||||
|
||||
# Mistral → Anthropic or OpenAI
|
||||
# llm = LLM(model="mistral/mistral-large-latest")
|
||||
llm = LLM(model="anthropic/claude-sonnet-4-20250514") # High quality
|
||||
|
||||
# Ollama → OpenAI-compatible (keep using local models)
|
||||
# llm = LLM(model="ollama/llama3")
|
||||
llm = LLM(
|
||||
model="openai/llama3",
|
||||
base_url="http://localhost:11434/v1",
|
||||
api_key="ollama"
|
||||
)
|
||||
```
|
||||
|
||||
## الأسئلة الشائعة
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="هل أفقد أي وظائف بإزالة LiteLLM؟">
|
||||
لا، إذا كنت تستخدم أحد المزودين الخمسة المدعومين أصلياً (OpenAI، Anthropic، Gemini، Azure، Bedrock). تدعم هذه التكاملات الأصلية جميع ميزات CrewAI بما في ذلك البث واستدعاء الأدوات والمخرجات المنظمة والمزيد. ستفقد فقط الوصول إلى المزودين المتاحين حصرياً عبر LiteLLM (مثل Groq وTogether AI وMistral كمزودين من الدرجة الأولى).
|
||||
</Accordion>
|
||||
<Accordion title="هل يمكنني استخدام عدة مزودين أصليين في نفس الوقت؟">
|
||||
نعم. ثبّت إضافات متعددة واستخدم مزودين مختلفين لوكلاء مختلفين:
|
||||
```bash
|
||||
uv add "crewai[openai,anthropic,gemini]"
|
||||
```
|
||||
```python
|
||||
researcher = Agent(llm="openai/gpt-4o", ...)
|
||||
writer = Agent(llm="anthropic/claude-sonnet-4-20250514", ...)
|
||||
```
|
||||
</Accordion>
|
||||
<Accordion title="هل LiteLLM آمن للاستخدام الآن؟">
|
||||
بغض النظر عن حالة العزل، فإن تقليل سطح اعتمادياتك يُعد ممارسة أمنية جيدة. إذا كنت تحتاج فقط مزودين يدعمهم CrewAI أصلياً، فلا يوجد سبب لإبقاء LiteLLM مثبتاً.
|
||||
</Accordion>
|
||||
<Accordion title="ماذا عن متغيرات البيئة مثل OPENAI_API_KEY؟">
|
||||
يستخدم المزودون الأصليون نفس متغيرات البيئة التي اعتدت عليها. لا حاجة لتغييرات على `OPENAI_API_KEY` أو `ANTHROPIC_API_KEY` أو `GEMINI_API_KEY` وغيرها.
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## موارد ذات صلة
|
||||
|
||||
- [اتصالات LLM](/ar/learn/llm-connections) — الدليل الكامل لربط CrewAI مع أي LLM
|
||||
- [مفاهيم LLM](/ar/concepts/llms) — فهم نماذج اللغة الكبيرة في CrewAI
|
||||
- [دليل اختيار LLM](/ar/learn/llm-selection-guide) — اختيار النموذج المناسب لحالة استخدامك
|
||||
214
docs/ar/learn/llm-connections.mdx
Normal file
214
docs/ar/learn/llm-connections.mdx
Normal file
@@ -0,0 +1,214 @@
|
||||
---
|
||||
title: الاتصال بأي LLM
|
||||
description: دليل شامل لدمج CrewAI مع نماذج اللغة الكبيرة المختلفة (LLMs) باستخدام LiteLLM، بما في ذلك المزودون المدعومون وخيارات الإعداد.
|
||||
icon: brain-circuit
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## ربط CrewAI بنماذج اللغة الكبيرة
|
||||
|
||||
يتصل CrewAI بنماذج اللغة الكبيرة من خلال تكاملات SDK الأصلية لأكثر المزودين شيوعاً (OpenAI وAnthropic وGoogle Gemini وAzure وAWS Bedrock)، ويستخدم LiteLLM كاحتياط مرن لجميع المزودين الآخرين.
|
||||
|
||||
<Note>
|
||||
افتراضياً، يستخدم CrewAI نموذج `gpt-4o-mini`. يتم تحديد ذلك بواسطة متغير البيئة `OPENAI_MODEL_NAME`، الذي يكون قيمته الافتراضية "gpt-4o-mini" إذا لم يتم تعيينه.
|
||||
يمكنك بسهولة إعداد وكلائك لاستخدام نموذج أو مزود مختلف كما هو موضح في هذا الدليل.
|
||||
</Note>
|
||||
|
||||
## المزودون المدعومون
|
||||
|
||||
يدعم LiteLLM مجموعة واسعة من المزودين، بما في ذلك على سبيل المثال لا الحصر:
|
||||
|
||||
- OpenAI
|
||||
- Anthropic
|
||||
- Google (Vertex AI, Gemini)
|
||||
- Azure OpenAI
|
||||
- AWS (Bedrock, SageMaker)
|
||||
- Cohere
|
||||
- VoyageAI
|
||||
- Hugging Face
|
||||
- Ollama
|
||||
- Mistral AI
|
||||
- Replicate
|
||||
- Together AI
|
||||
- AI21
|
||||
- Cloudflare Workers AI
|
||||
- DeepInfra
|
||||
- Groq
|
||||
- SambaNova
|
||||
- Nebius AI Studio
|
||||
- [NVIDIA NIMs](https://docs.api.nvidia.com/nim/reference/models-1)
|
||||
- والمزيد!
|
||||
|
||||
للحصول على قائمة كاملة ومحدثة بالمزودين المدعومين، يرجى الرجوع إلى [وثائق مزودي LiteLLM](https://docs.litellm.ai/docs/providers).
|
||||
|
||||
<Info>
|
||||
لاستخدام أي مزود غير مغطى بتكامل أصلي، أضف LiteLLM كاعتمادية لمشروعك:
|
||||
```bash
|
||||
uv add 'crewai[litellm]'
|
||||
```
|
||||
يستخدم المزودون الأصليون (OpenAI، Anthropic، Google Gemini، Azure، AWS Bedrock) إضافات SDK الخاصة بهم — راجع [أمثلة إعداد المزودين](/ar/concepts/llms#provider-configuration-examples).
|
||||
</Info>
|
||||
|
||||
## تغيير نموذج اللغة الكبير
|
||||
|
||||
لاستخدام LLM مختلف مع وكلاء CrewAI، لديك عدة خيارات:
|
||||
|
||||
<Tabs>
|
||||
<Tab title="باستخدام معرف نصي">
|
||||
مرر اسم النموذج كسلسلة نصية عند تهيئة الوكيل:
|
||||
<CodeGroup>
|
||||
```python Code
|
||||
from crewai import Agent
|
||||
|
||||
# Using OpenAI's GPT-4
|
||||
openai_agent = Agent(
|
||||
role='OpenAI Expert',
|
||||
goal='Provide insights using GPT-4',
|
||||
backstory="An AI assistant powered by OpenAI's latest model.",
|
||||
llm='gpt-4'
|
||||
)
|
||||
|
||||
# Using Anthropic's Claude
|
||||
claude_agent = Agent(
|
||||
role='Anthropic Expert',
|
||||
goal='Analyze data using Claude',
|
||||
backstory="An AI assistant leveraging Anthropic's language model.",
|
||||
llm='claude-2'
|
||||
)
|
||||
```
|
||||
</CodeGroup>
|
||||
</Tab>
|
||||
<Tab title="باستخدام فئة LLM">
|
||||
لمزيد من الإعداد التفصيلي، استخدم فئة LLM:
|
||||
<CodeGroup>
|
||||
```python Code
|
||||
from crewai import Agent, LLM
|
||||
|
||||
llm = LLM(
|
||||
model="gpt-4",
|
||||
temperature=0.7,
|
||||
base_url="https://api.openai.com/v1",
|
||||
api_key="your-api-key-here"
|
||||
)
|
||||
|
||||
agent = Agent(
|
||||
role='Customized LLM Expert',
|
||||
goal='Provide tailored responses',
|
||||
backstory="An AI assistant with custom LLM settings.",
|
||||
llm=llm
|
||||
)
|
||||
```
|
||||
</CodeGroup>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## خيارات الإعداد
|
||||
|
||||
عند إعداد LLM لوكيلك، يمكنك الوصول إلى مجموعة واسعة من المعاملات:
|
||||
|
||||
| المعامل | النوع | الوصف |
|
||||
|:----------|:-----:|:-------------|
|
||||
| **model** | `str` | اسم النموذج المراد استخدامه (مثل "gpt-4"، "claude-2") |
|
||||
| **temperature** | `float` | يتحكم في العشوائية في المخرجات (0.0 إلى 1.0) |
|
||||
| **max_tokens** | `int` | الحد الأقصى لعدد الرموز المولدة |
|
||||
| **top_p** | `float` | يتحكم في تنوع المخرجات (0.0 إلى 1.0) |
|
||||
| **frequency_penalty** | `float` | يعاقب الرموز الجديدة بناءً على تكرارها في النص حتى الآن |
|
||||
| **presence_penalty** | `float` | يعاقب الرموز الجديدة بناءً على وجودها في النص حتى الآن |
|
||||
| **stop** | `str`, `List[str]` | تسلسل(ات) لإيقاف التوليد |
|
||||
| **base_url** | `str` | عنوان URL الأساسي لنقطة نهاية API |
|
||||
| **api_key** | `str` | مفتاح API الخاص بك للمصادقة |
|
||||
|
||||
للحصول على قائمة كاملة بالمعاملات وأوصافها، راجع وثائق فئة LLM.
|
||||
|
||||
## الاتصال بنماذج LLM المتوافقة مع OpenAI
|
||||
|
||||
يمكنك الاتصال بنماذج LLM المتوافقة مع OpenAI باستخدام متغيرات البيئة أو عن طريق تعيين خصائص محددة في فئة LLM:
|
||||
|
||||
<Tabs>
|
||||
<Tab title="باستخدام متغيرات البيئة">
|
||||
<CodeGroup>
|
||||
```python Generic
|
||||
import os
|
||||
|
||||
os.environ["OPENAI_API_KEY"] = "your-api-key"
|
||||
os.environ["OPENAI_API_BASE"] = "https://api.your-provider.com/v1"
|
||||
os.environ["OPENAI_MODEL_NAME"] = "your-model-name"
|
||||
```
|
||||
|
||||
```python Google
|
||||
import os
|
||||
|
||||
# Example using Gemini's OpenAI-compatible API.
|
||||
os.environ["OPENAI_API_KEY"] = "your-gemini-key" # Should start with AIza...
|
||||
os.environ["OPENAI_API_BASE"] = "https://generativelanguage.googleapis.com/v1beta/openai/"
|
||||
os.environ["OPENAI_MODEL_NAME"] = "openai/gemini-2.0-flash" # Add your Gemini model here, under openai/
|
||||
```
|
||||
</CodeGroup>
|
||||
</Tab>
|
||||
<Tab title="باستخدام خصائص فئة LLM">
|
||||
<CodeGroup>
|
||||
```python Generic
|
||||
llm = LLM(
|
||||
model="custom-model-name",
|
||||
api_key="your-api-key",
|
||||
base_url="https://api.your-provider.com/v1"
|
||||
)
|
||||
agent = Agent(llm=llm, ...)
|
||||
```
|
||||
|
||||
```python Google
|
||||
# Example using Gemini's OpenAI-compatible API
|
||||
llm = LLM(
|
||||
model="openai/gemini-2.0-flash",
|
||||
base_url="https://generativelanguage.googleapis.com/v1beta/openai/",
|
||||
api_key="your-gemini-key", # Should start with AIza...
|
||||
)
|
||||
agent = Agent(llm=llm, ...)
|
||||
```
|
||||
</CodeGroup>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## استخدام النماذج المحلية مع Ollama
|
||||
|
||||
للنماذج المحلية مثل تلك التي يوفرها Ollama:
|
||||
|
||||
<Steps>
|
||||
<Step title="تحميل وتثبيت Ollama">
|
||||
[انقر هنا لتحميل وتثبيت Ollama](https://ollama.com/download)
|
||||
</Step>
|
||||
<Step title="سحب النموذج المطلوب">
|
||||
على سبيل المثال، شغّل `ollama pull llama3.2` لتحميل النموذج.
|
||||
</Step>
|
||||
<Step title="إعداد وكيلك">
|
||||
<CodeGroup>
|
||||
```python Code
|
||||
agent = Agent(
|
||||
role='Local AI Expert',
|
||||
goal='Process information using a local model',
|
||||
backstory="An AI assistant running on local hardware.",
|
||||
llm=LLM(model="ollama/llama3.2", base_url="http://localhost:11434")
|
||||
)
|
||||
```
|
||||
</CodeGroup>
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## تغيير عنوان URL الأساسي لـ API
|
||||
|
||||
يمكنك تغيير عنوان URL الأساسي لـ API لأي مزود LLM عن طريق تعيين معامل `base_url`:
|
||||
|
||||
```python Code
|
||||
llm = LLM(
|
||||
model="custom-model-name",
|
||||
base_url="https://api.your-provider.com/v1",
|
||||
api_key="your-api-key"
|
||||
)
|
||||
agent = Agent(llm=llm, ...)
|
||||
```
|
||||
|
||||
هذا مفيد بشكل خاص عند العمل مع واجهات برمجة تطبيقات متوافقة مع OpenAI أو عندما تحتاج إلى تحديد نقطة نهاية مختلفة للمزود الذي اخترته.
|
||||
|
||||
## الخاتمة
|
||||
|
||||
من خلال الاستفادة من LiteLLM، يوفر CrewAI تكاملاً سلساً مع مجموعة واسعة من نماذج اللغة الكبيرة. تتيح لك هذه المرونة اختيار النموذج الأنسب لاحتياجاتك المحددة، سواء كنت تعطي الأولوية للأداء أو كفاءة التكلفة أو النشر المحلي. تذكر الرجوع إلى [وثائق LiteLLM](https://docs.litellm.ai/docs/) للحصول على أحدث المعلومات حول النماذج المدعومة وخيارات الإعداد.
|
||||
427
docs/ar/learn/llm-hooks.mdx
Normal file
427
docs/ar/learn/llm-hooks.mdx
Normal file
@@ -0,0 +1,427 @@
|
||||
---
|
||||
title: خطافات استدعاء LLM
|
||||
description: تعلم كيفية استخدام خطافات استدعاء LLM لاعتراض وتعديل والتحكم في تفاعلات نماذج اللغة في CrewAI
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
توفر خطافات استدعاء LLM تحكماً دقيقاً في تفاعلات نماذج اللغة أثناء تنفيذ الوكيل. تتيح لك هذه الخطافات اعتراض استدعاءات LLM وتعديل المطالبات وتحويل الاستجابات وتنفيذ بوابات الموافقة وإضافة تسجيل أو مراقبة مخصصة.
|
||||
|
||||
## نظرة عامة
|
||||
|
||||
تُنفذ خطافات LLM في نقطتين حرجتين:
|
||||
- **قبل استدعاء LLM**: تعديل الرسائل، التحقق من المدخلات، أو حظر التنفيذ
|
||||
- **بعد استدعاء LLM**: تحويل الاستجابات، تنقية المخرجات، أو تعديل سجل المحادثة
|
||||
|
||||
## أنواع الخطافات
|
||||
|
||||
### خطافات ما قبل استدعاء LLM
|
||||
|
||||
تُنفذ قبل كل استدعاء LLM، ويمكن لهذه الخطافات:
|
||||
- فحص وتعديل الرسائل المرسلة إلى LLM
|
||||
- حظر تنفيذ LLM بناءً على شروط
|
||||
- تنفيذ تحديد معدل أو بوابات موافقة
|
||||
- إضافة سياق أو رسائل نظام
|
||||
- تسجيل تفاصيل الطلب
|
||||
|
||||
**التوقيع:**
|
||||
```python
|
||||
def before_hook(context: LLMCallHookContext) -> bool | None:
|
||||
# Return False to block execution
|
||||
# Return True or None to allow execution
|
||||
...
|
||||
```
|
||||
|
||||
### خطافات ما بعد استدعاء LLM
|
||||
|
||||
تُنفذ بعد كل استدعاء LLM، ويمكن لهذه الخطافات:
|
||||
- تعديل أو تنقية استجابات LLM
|
||||
- إضافة بيانات وصفية أو تنسيق
|
||||
- تسجيل تفاصيل الاستجابة
|
||||
- تحديث سجل المحادثة
|
||||
- تنفيذ تصفية المحتوى
|
||||
|
||||
**التوقيع:**
|
||||
```python
|
||||
def after_hook(context: LLMCallHookContext) -> str | None:
|
||||
# Return modified response string
|
||||
# Return None to keep original response
|
||||
...
|
||||
```
|
||||
|
||||
## سياق خطاف LLM
|
||||
|
||||
يوفر كائن `LLMCallHookContext` وصولاً شاملاً لحالة التنفيذ:
|
||||
|
||||
```python
|
||||
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)
|
||||
```
|
||||
|
||||
### تعديل الرسائل
|
||||
|
||||
**مهم:** قم دائماً بتعديل الرسائل في مكانها:
|
||||
|
||||
```python
|
||||
# ✅ Correct - modify in-place
|
||||
def add_context(context: LLMCallHookContext) -> None:
|
||||
context.messages.append({"role": "system", "content": "Be concise"})
|
||||
|
||||
# ❌ Wrong - replaces list reference
|
||||
def wrong_approach(context: LLMCallHookContext) -> None:
|
||||
context.messages = [{"role": "system", "content": "Be concise"}]
|
||||
```
|
||||
|
||||
## طرق التسجيل
|
||||
|
||||
### 1. تسجيل الخطافات العامة
|
||||
|
||||
تسجيل خطافات تنطبق على جميع استدعاءات LLM عبر جميع الأطقم:
|
||||
|
||||
```python
|
||||
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. التسجيل باستخدام المزخرفات
|
||||
|
||||
استخدم المزخرفات لصياغة أنظف:
|
||||
|
||||
```python
|
||||
from crewai.hooks import before_llm_call, after_llm_call
|
||||
|
||||
@before_llm_call
|
||||
def validate_iteration_count(context):
|
||||
if context.iterations > 10:
|
||||
print("⚠️ Exceeded maximum iterations")
|
||||
return False # Block execution
|
||||
return None
|
||||
|
||||
@after_llm_call
|
||||
def sanitize_response(context):
|
||||
if context.response and "API_KEY" in context.response:
|
||||
return context.response.replace("API_KEY", "[REDACTED]")
|
||||
return None
|
||||
```
|
||||
|
||||
### 3. خطافات نطاق الطاقم
|
||||
|
||||
تسجيل خطافات لمثيل طاقم محدد:
|
||||
|
||||
```python
|
||||
@CrewBase
|
||||
class 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
|
||||
)
|
||||
```
|
||||
|
||||
## حالات الاستخدام الشائعة
|
||||
|
||||
### 1. تحديد التكرارات
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def 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 None
|
||||
```
|
||||
|
||||
### 2. بوابة الموافقة البشرية
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def 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 None
|
||||
```
|
||||
|
||||
### 3. إضافة سياق النظام
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def 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 None
|
||||
```
|
||||
|
||||
### 4. تنقية الاستجابات
|
||||
|
||||
```python
|
||||
@after_llm_call
|
||||
def 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 sanitized
|
||||
```
|
||||
|
||||
### 5. تتبع التكاليف
|
||||
|
||||
```python
|
||||
import tiktoken
|
||||
|
||||
@before_llm_call
|
||||
def 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_call
|
||||
def 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 None
|
||||
```
|
||||
|
||||
### 6. تسجيل التصحيح
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def 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_call
|
||||
def debug_response(context: LLMCallHookContext) -> None:
|
||||
if context.response:
|
||||
print(f"✅ Response Preview: {context.response[:100]}...")
|
||||
return None
|
||||
```
|
||||
|
||||
## إدارة الخطافات
|
||||
|
||||
### إلغاء تسجيل الخطافات
|
||||
|
||||
```python
|
||||
from crewai.hooks import (
|
||||
unregister_before_llm_call_hook,
|
||||
unregister_after_llm_call_hook
|
||||
)
|
||||
|
||||
# Unregister specific hook
|
||||
def my_hook(context):
|
||||
...
|
||||
|
||||
register_before_llm_call_hook(my_hook)
|
||||
# Later...
|
||||
unregister_before_llm_call_hook(my_hook) # Returns True if found
|
||||
```
|
||||
|
||||
### مسح الخطافات
|
||||
|
||||
```python
|
||||
from crewai.hooks import (
|
||||
clear_before_llm_call_hooks,
|
||||
clear_after_llm_call_hooks,
|
||||
clear_all_llm_call_hooks
|
||||
)
|
||||
|
||||
# Clear specific hook type
|
||||
count = clear_before_llm_call_hooks()
|
||||
print(f"Cleared {count} before hooks")
|
||||
|
||||
# Clear all LLM hooks
|
||||
before_count, after_count = clear_all_llm_call_hooks()
|
||||
print(f"Cleared {before_count} before and {after_count} after hooks")
|
||||
```
|
||||
|
||||
### عرض الخطافات المسجلة
|
||||
|
||||
```python
|
||||
from crewai.hooks import (
|
||||
get_before_llm_call_hooks,
|
||||
get_after_llm_call_hooks
|
||||
)
|
||||
|
||||
# Get current hooks
|
||||
before_hooks = get_before_llm_call_hooks()
|
||||
after_hooks = get_after_llm_call_hooks()
|
||||
|
||||
print(f"Registered: {len(before_hooks)} before, {len(after_hooks)} after")
|
||||
```
|
||||
|
||||
## أنماط متقدمة
|
||||
|
||||
### تنفيذ خطاف مشروط
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def 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
|
||||
```
|
||||
|
||||
### تعديلات واعية بالسياق
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def 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
|
||||
```
|
||||
|
||||
### ربط الخطافات
|
||||
|
||||
```python
|
||||
# Multiple hooks execute in registration order
|
||||
|
||||
@before_llm_call
|
||||
def first_hook(context):
|
||||
print("1. First hook executed")
|
||||
return None
|
||||
|
||||
@before_llm_call
|
||||
def second_hook(context):
|
||||
print("2. Second hook executed")
|
||||
return None
|
||||
|
||||
@before_llm_call
|
||||
def 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
|
||||
```
|
||||
|
||||
## أفضل الممارسات
|
||||
|
||||
1. **اجعل الخطافات مركزة**: يجب أن يكون لكل خطاف مسؤولية واحدة
|
||||
2. **تجنب الحسابات الثقيلة**: تُنفذ الخطافات في كل استدعاء LLM
|
||||
3. **تعامل مع الأخطاء بأناقة**: استخدم try-except لمنع فشل الخطافات من كسر التنفيذ
|
||||
4. **استخدم تلميحات الأنواع**: استفد من `LLMCallHookContext` لدعم أفضل في بيئة التطوير
|
||||
5. **وثّق سلوك الخطاف**: خاصة لشروط الحظر
|
||||
6. **اختبر الخطافات بشكل مستقل**: اختبر الخطافات وحدوياً قبل الاستخدام في الإنتاج
|
||||
7. **امسح الخطافات في الاختبارات**: استخدم `clear_all_llm_call_hooks()` بين تشغيلات الاختبار
|
||||
8. **عدّل في المكان**: قم دائماً بتعديل `context.messages` في مكانها، ولا تستبدلها
|
||||
|
||||
## معالجة الأخطاء
|
||||
|
||||
```python
|
||||
@before_llm_call
|
||||
def 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
|
||||
```
|
||||
|
||||
## أمان الأنواع
|
||||
|
||||
```python
|
||||
from crewai.hooks import LLMCallHookContext, BeforeLLMCallHookType, AfterLLMCallHookType
|
||||
|
||||
# Explicit type annotations
|
||||
def my_before_hook(context: LLMCallHookContext) -> bool | None:
|
||||
return None
|
||||
|
||||
def my_after_hook(context: LLMCallHookContext) -> str | None:
|
||||
return None
|
||||
|
||||
# Type-safe registration
|
||||
register_before_llm_call_hook(my_before_hook)
|
||||
register_after_llm_call_hook(my_after_hook)
|
||||
```
|
||||
|
||||
## استكشاف الأخطاء وإصلاحها
|
||||
|
||||
### الخطاف لا يُنفذ
|
||||
- تحقق من أن الخطاف مسجل قبل تنفيذ الطاقم
|
||||
- تحقق مما إذا كان خطاف سابق أرجع `False` (يحظر الخطافات اللاحقة)
|
||||
- تأكد من أن توقيع الخطاف يطابق النوع المتوقع
|
||||
|
||||
### تعديلات الرسائل لا تستمر
|
||||
- استخدم التعديلات في المكان: `context.messages.append()`
|
||||
- لا تستبدل القائمة: `context.messages = []`
|
||||
|
||||
### تعديلات الاستجابة لا تعمل
|
||||
- أرجع السلسلة النصية المعدلة من خطافات ما بعد
|
||||
- إرجاع `None` يحتفظ بالاستجابة الأصلية
|
||||
|
||||
## الخاتمة
|
||||
|
||||
توفر خطافات استدعاء LLM إمكانيات قوية للتحكم في تفاعلات نماذج اللغة ومراقبتها في CrewAI. استخدمها لتنفيذ حواجز الأمان وبوابات الموافقة والتسجيل وتتبع التكاليف وتنقية الاستجابات. مع معالجة الأخطاء المناسبة وأمان الأنواع، تُمكّن الخطافات أنظمة وكلاء قوية وجاهزة للإنتاج.
|
||||
823
docs/ar/learn/llm-selection-guide.mdx
Normal file
823
docs/ar/learn/llm-selection-guide.mdx
Normal file
@@ -0,0 +1,823 @@
|
||||
---
|
||||
title: "دليل اختيار LLM الاستراتيجي"
|
||||
description: "إطار عمل استراتيجي لاختيار نموذج اللغة الكبير المناسب لوكلاء الذكاء الاصطناعي في CrewAI وكتابة تعريفات فعالة للمهام والوكلاء"
|
||||
icon: "brain-circuit"
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## نهج CrewAI في اختيار LLM
|
||||
|
||||
بدلاً من توصيات نماذج محددة، ندعو إلى **إطار تفكير** يساعدك على اتخاذ قرارات مستنيرة بناءً على حالة استخدامك المحددة وقيودك ومتطلباتك. يتطور مشهد LLM بسرعة، مع ظهور نماذج جديدة بانتظام وتحديث النماذج الحالية بشكل متكرر. الأهم هو تطوير نهج منظم للتقييم يبقى ذا صلة بغض النظر عن النماذج المتاحة تحديداً.
|
||||
|
||||
<Note>
|
||||
يركز هذا الدليل على التفكير الاستراتيجي بدلاً من توصيات نماذج محددة،
|
||||
حيث يتطور مشهد LLM بسرعة.
|
||||
</Note>
|
||||
|
||||
## إطار القرار السريع
|
||||
|
||||
<Steps>
|
||||
<Step title="حلل مهامك">
|
||||
ابدأ بفهم عميق لما تتطلبه مهامك فعلاً. ضع في الاعتبار التعقيد المعرفي
|
||||
المطلوب وعمق الاستدلال اللازم وتنسيق المخرجات المتوقعة وحجم السياق الذي
|
||||
سيحتاج النموذج لمعالجته. سيوجه هذا التحليل الأساسي كل قرار لاحق.
|
||||
</Step>
|
||||
<Step title="خريطة قدرات النماذج">
|
||||
بمجرد فهم متطلباتك، اربطها بنقاط قوة النماذج. تتفوق عائلات النماذج
|
||||
المختلفة في أنواع مختلفة من العمل؛ بعضها محسّن للاستدلال والتحليل وبعضها
|
||||
للإبداع وتوليد المحتوى وبعضها للسرعة والكفاءة.
|
||||
</Step>
|
||||
<Step title="ضع في الاعتبار القيود">
|
||||
ضع في حسبانك قيودك التشغيلية الواقعية بما في ذلك قيود الميزانية ومتطلبات
|
||||
زمن الاستجابة واحتياجات خصوصية البيانات وقدرات البنية التحتية. قد لا يكون
|
||||
النموذج الأفضل نظرياً هو الخيار الأفضل عملياً لوضعك.
|
||||
</Step>
|
||||
<Step title="اختبر وكرر">
|
||||
ابدأ بنماذج موثوقة ومفهومة جيداً وحسّن بناءً على الأداء الفعلي في حالة
|
||||
استخدامك المحددة. غالباً ما تختلف النتائج الواقعية عن المعايير النظرية، لذا
|
||||
فإن الاختبار التجريبي ضروري.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Core Selection Framework
|
||||
|
||||
### a. Task-First Thinking
|
||||
|
||||
The most critical step in LLM selection is understanding what your task actually demands. Too often, teams select models based on general reputation or benchmark scores without carefully analyzing their specific requirements. This approach leads to either over-engineering simple tasks with expensive, complex models, or under-powering sophisticated work with models that lack the necessary capabilities.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Reasoning Complexity">
|
||||
- **Simple Tasks** represent the majority of everyday AI work and include basic instruction following, straightforward data processing, and simple formatting operations. These tasks typically have clear inputs and outputs with minimal ambiguity. The cognitive load is low, and the model primarily needs to follow explicit instructions rather than engage in complex reasoning.
|
||||
|
||||
- **Complex Tasks** require multi-step reasoning, strategic thinking, and the ability to handle ambiguous or incomplete information. These might involve analyzing multiple data sources, developing comprehensive strategies, or solving problems that require breaking down into smaller components. The model needs to maintain context across multiple reasoning steps and often must make inferences that aren't explicitly stated.
|
||||
|
||||
- **Creative Tasks** demand a different type of cognitive capability focused on generating novel, engaging, and contextually appropriate content. This includes storytelling, marketing copy creation, and creative problem-solving. The model needs to understand nuance, tone, and audience while producing content that feels authentic and engaging rather than formulaic.
|
||||
|
||||
</Tab>
|
||||
|
||||
<Tab title="Output Requirements">
|
||||
- **Structured Data** tasks require precision and consistency in format adherence. When working with JSON, XML, or database formats, the model must reliably produce syntactically correct output that can be programmatically processed. These tasks often have strict validation requirements and little tolerance for format errors, making reliability more important than creativity.
|
||||
|
||||
- **Creative Content** outputs demand a balance of technical competence and creative flair. The model needs to understand audience, tone, and brand voice while producing content that engages readers and achieves specific communication goals. Quality here is often subjective and requires models that can adapt their writing style to different contexts and purposes.
|
||||
|
||||
- **Technical Content** sits between structured data and creative content, requiring both precision and clarity. Documentation, code generation, and technical analysis need to be accurate and comprehensive while remaining accessible to the intended audience. The model must understand complex technical concepts and communicate them effectively.
|
||||
|
||||
</Tab>
|
||||
|
||||
<Tab title="Context Needs">
|
||||
- **Short Context** scenarios involve focused, immediate tasks where the model needs to process limited information quickly. These are often transactional interactions where speed and efficiency matter more than deep understanding. The model doesn't need to maintain extensive conversation history or process large documents.
|
||||
|
||||
- **Long Context** requirements emerge when working with substantial documents, extended conversations, or complex multi-part tasks. The model needs to maintain coherence across thousands of tokens while referencing earlier information accurately. This capability becomes crucial for document analysis, comprehensive research, and sophisticated dialogue systems.
|
||||
|
||||
- **Very Long Context** scenarios push the boundaries of what's currently possible, involving massive document processing, extensive research synthesis, or complex multi-session interactions. These use cases require models specifically designed for extended context handling and often involve trade-offs between context length and processing speed.
|
||||
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### b. Model Capability Mapping
|
||||
|
||||
Understanding model capabilities requires looking beyond marketing claims and benchmark scores to understand the fundamental strengths and limitations of different model architectures and training approaches.
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="Reasoning Models" icon="brain">
|
||||
Reasoning models represent a specialized category designed specifically for complex, multi-step thinking tasks. These models excel when problems require careful analysis, strategic planning, or systematic problem decomposition. They typically employ techniques like chain-of-thought reasoning or tree-of-thought processing to work through complex problems step by step.
|
||||
|
||||
The strength of reasoning models lies in their ability to maintain logical consistency across extended reasoning chains and to break down complex problems into manageable components. They're particularly valuable for strategic planning, complex analysis, and situations where the quality of reasoning matters more than speed of response.
|
||||
|
||||
However, reasoning models often come with trade-offs in terms of speed and cost. They may also be less suitable for creative tasks or simple operations where their sophisticated reasoning capabilities aren't needed. Consider these models when your tasks involve genuine complexity that benefits from systematic, step-by-step analysis.
|
||||
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="General Purpose Models" icon="microchip">
|
||||
General purpose models offer the most balanced approach to LLM selection, providing solid performance across a wide range of tasks without extreme specialization in any particular area. These models are trained on diverse datasets and optimized for versatility rather than peak performance in specific domains.
|
||||
|
||||
The primary advantage of general purpose models is their reliability and predictability across different types of work. They handle most standard business tasks competently, from research and analysis to content creation and data processing. This makes them excellent choices for teams that need consistent performance across varied workflows.
|
||||
|
||||
While general purpose models may not achieve the peak performance of specialized alternatives in specific domains, they offer operational simplicity and reduced complexity in model management. They're often the best starting point for new projects, allowing teams to understand their specific needs before potentially optimizing with more specialized models.
|
||||
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Fast & Efficient Models" icon="bolt">
|
||||
Fast and efficient models prioritize speed, cost-effectiveness, and resource efficiency over sophisticated reasoning capabilities. These models are optimized for high-throughput scenarios where quick responses and low operational costs are more important than nuanced understanding or complex reasoning.
|
||||
|
||||
These models excel in scenarios involving routine operations, simple data processing, function calling, and high-volume tasks where the cognitive requirements are relatively straightforward. They're particularly valuable for applications that need to process many requests quickly or operate within tight budget constraints.
|
||||
|
||||
The key consideration with efficient models is ensuring that their capabilities align with your task requirements. While they can handle many routine operations effectively, they may struggle with tasks requiring nuanced understanding, complex reasoning, or sophisticated content generation. They're best used for well-defined, routine operations where speed and cost matter more than sophistication.
|
||||
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Creative Models" icon="pen">
|
||||
Creative models are specifically optimized for content generation, writing quality, and creative thinking tasks. These models typically excel at understanding nuance, tone, and style while producing engaging, contextually appropriate content that feels natural and authentic.
|
||||
|
||||
The strength of creative models lies in their ability to adapt writing style to different audiences, maintain consistent voice and tone, and generate content that engages readers effectively. They often perform better on tasks involving storytelling, marketing copy, brand communications, and other content where creativity and engagement are primary goals.
|
||||
|
||||
When selecting creative models, consider not just their ability to generate text, but their understanding of audience, context, and purpose. The best creative models can adapt their output to match specific brand voices, target different audience segments, and maintain consistency across extended content pieces.
|
||||
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Open Source Models" icon="code">
|
||||
Open source models offer unique advantages in terms of cost control, customization potential, data privacy, and deployment flexibility. These models can be run locally or on private infrastructure, providing complete control over data handling and model behavior.
|
||||
|
||||
The primary benefits of open source models include elimination of per-token costs, ability to fine-tune for specific use cases, complete data privacy, and independence from external API providers. They're particularly valuable for organizations with strict data privacy requirements, budget constraints, or specific customization needs.
|
||||
|
||||
However, open source models require more technical expertise to deploy and maintain effectively. Teams need to consider infrastructure costs, model management complexity, and the ongoing effort required to keep models updated and optimized. The total cost of ownership may be higher than cloud-based alternatives when factoring in technical overhead.
|
||||
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Strategic Configuration Patterns
|
||||
|
||||
### a. Multi-Model Approach
|
||||
|
||||
<Tip>
|
||||
Use different models for different purposes within the same crew to optimize
|
||||
both performance and cost.
|
||||
</Tip>
|
||||
|
||||
The most sophisticated CrewAI implementations often employ multiple models strategically, assigning different models to different agents based on their specific roles and requirements. This approach allows teams to optimize for both performance and cost by using the most appropriate model for each type of work.
|
||||
|
||||
Planning agents benefit from reasoning models that can handle complex strategic thinking and multi-step analysis. These agents often serve as the "brain" of the operation, developing strategies and coordinating other agents' work. Content agents, on the other hand, perform best with creative models that excel at writing quality and audience engagement. Processing agents handling routine operations can use efficient models that prioritize speed and cost-effectiveness.
|
||||
|
||||
**Example: Research and Analysis Crew**
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew, LLM
|
||||
|
||||
# High-capability reasoning model for strategic planning
|
||||
manager_llm = LLM(model="gemini-2.5-flash-preview-05-20", temperature=0.1)
|
||||
|
||||
# Creative model for content generation
|
||||
content_llm = LLM(model="claude-3-5-sonnet-20241022", temperature=0.7)
|
||||
|
||||
# Efficient model for data processing
|
||||
processing_llm = LLM(model="gpt-4o-mini", temperature=0)
|
||||
|
||||
research_manager = Agent(
|
||||
role="Research Strategy Manager",
|
||||
goal="Develop comprehensive research strategies and coordinate team efforts",
|
||||
backstory="Expert research strategist with deep analytical capabilities",
|
||||
llm=manager_llm, # High-capability model for complex reasoning
|
||||
verbose=True
|
||||
)
|
||||
|
||||
content_writer = Agent(
|
||||
role="Research Content Writer",
|
||||
goal="Transform research findings into compelling, well-structured reports",
|
||||
backstory="Skilled writer who excels at making complex topics accessible",
|
||||
llm=content_llm, # Creative model for engaging content
|
||||
verbose=True
|
||||
)
|
||||
|
||||
data_processor = Agent(
|
||||
role="Data Analysis Specialist",
|
||||
goal="Extract and organize key data points from research sources",
|
||||
backstory="Detail-oriented analyst focused on accuracy and efficiency",
|
||||
llm=processing_llm, # Fast, cost-effective model for routine tasks
|
||||
verbose=True
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[research_manager, content_writer, data_processor],
|
||||
tasks=[...], # Your specific tasks
|
||||
manager_llm=manager_llm, # Manager uses the reasoning model
|
||||
verbose=True
|
||||
)
|
||||
```
|
||||
|
||||
The key to successful multi-model implementation is understanding how different agents interact and ensuring that model capabilities align with agent responsibilities. This requires careful planning but can result in significant improvements in both output quality and operational efficiency.
|
||||
|
||||
### b. Component-Specific Selection
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Manager LLM">
|
||||
The manager LLM plays a crucial role in hierarchical CrewAI processes, serving as the coordination point for multiple agents and tasks. This model needs to excel at delegation, task prioritization, and maintaining context across multiple concurrent operations.
|
||||
|
||||
Effective manager LLMs require strong reasoning capabilities to make good delegation decisions, consistent performance to ensure predictable coordination, and excellent context management to track the state of multiple agents simultaneously. The model needs to understand the capabilities and limitations of different agents while optimizing task allocation for efficiency and quality.
|
||||
|
||||
Cost considerations are particularly important for manager LLMs since they're involved in every operation. The model needs to provide sufficient capability for effective coordination while remaining cost-effective for frequent use. This often means finding models that offer good reasoning capabilities without the premium pricing of the most sophisticated options.
|
||||
|
||||
</Tab>
|
||||
|
||||
<Tab title="Function Calling LLM">
|
||||
Function calling LLMs handle tool usage across all agents, making them critical for crews that rely heavily on external tools and APIs. These models need to excel at understanding tool capabilities, extracting parameters accurately, and handling tool responses effectively.
|
||||
|
||||
The most important characteristics for function calling LLMs are precision and reliability rather than creativity or sophisticated reasoning. The model needs to consistently extract the correct parameters from natural language requests and handle tool responses appropriately. Speed is also important since tool usage often involves multiple round trips that can impact overall performance.
|
||||
|
||||
Many teams find that specialized function calling models or general purpose models with strong tool support work better than creative or reasoning-focused models for this role. The key is ensuring that the model can reliably bridge the gap between natural language instructions and structured tool calls.
|
||||
|
||||
</Tab>
|
||||
|
||||
<Tab title="Agent-Specific Overrides">
|
||||
Individual agents can override crew-level LLM settings when their specific needs differ significantly from the general crew requirements. This capability allows for fine-tuned optimization while maintaining operational simplicity for most agents.
|
||||
|
||||
Consider agent-specific overrides when an agent's role requires capabilities that differ substantially from other crew members. For example, a creative writing agent might benefit from a model optimized for content generation, while a data analysis agent might perform better with a reasoning-focused model.
|
||||
|
||||
The challenge with agent-specific overrides is balancing optimization with operational complexity. Each additional model adds complexity to deployment, monitoring, and cost management. Teams should focus overrides on agents where the performance improvement justifies the additional complexity.
|
||||
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Task Definition Framework
|
||||
|
||||
### a. Focus on Clarity Over Complexity
|
||||
|
||||
Effective task definition is often more important than model selection in determining the quality of CrewAI outputs. Well-defined tasks provide clear direction and context that enable even modest models to perform well, while poorly defined tasks can cause even sophisticated models to produce unsatisfactory results.
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="Effective Task Descriptions" icon="list-check">
|
||||
The best task descriptions strike a balance between providing sufficient detail and maintaining clarity. They should define the specific objective clearly enough that there's no ambiguity about what success looks like, while explaining the approach or methodology in enough detail that the agent understands how to proceed.
|
||||
|
||||
Effective task descriptions include relevant context and constraints that help the agent understand the broader purpose and any limitations they need to work within. They break complex work into focused steps that can be executed systematically, rather than presenting overwhelming, multi-faceted objectives that are difficult to approach systematically.
|
||||
|
||||
Common mistakes include being too vague about objectives, failing to provide necessary context, setting unclear success criteria, or combining multiple unrelated tasks into a single description. The goal is to provide enough information for the agent to succeed while maintaining focus on a single, clear objective.
|
||||
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Expected Output Guidelines" icon="bullseye">
|
||||
Expected output guidelines serve as a contract between the task definition and the agent, clearly specifying what the deliverable should look like and how it will be evaluated. These guidelines should describe both the format and structure needed, as well as the key elements that must be included for the output to be considered complete.
|
||||
|
||||
The best output guidelines provide concrete examples of quality indicators and define completion criteria clearly enough that both the agent and human reviewers can assess whether the task has been completed successfully. This reduces ambiguity and helps ensure consistent results across multiple task executions.
|
||||
|
||||
Avoid generic output descriptions that could apply to any task, missing format specifications that leave agents guessing about structure, unclear quality standards that make evaluation difficult, or failing to provide examples or templates that help agents understand expectations.
|
||||
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
### b. Task Sequencing Strategy
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Sequential Dependencies">
|
||||
Sequential task dependencies are essential when tasks build upon previous outputs, information flows from one task to another, or quality depends on the completion of prerequisite work. This approach ensures that each task has access to the information and context it needs to succeed.
|
||||
|
||||
Implementing sequential dependencies effectively requires using the context parameter to chain related tasks, building complexity gradually through task progression, and ensuring that each task produces outputs that serve as meaningful inputs for subsequent tasks. The goal is to maintain logical flow between dependent tasks while avoiding unnecessary bottlenecks.
|
||||
|
||||
Sequential dependencies work best when there's a clear logical progression from one task to another and when the output of one task genuinely improves the quality or feasibility of subsequent tasks. However, they can create bottlenecks if not managed carefully, so it's important to identify which dependencies are truly necessary versus those that are merely convenient.
|
||||
|
||||
</Tab>
|
||||
|
||||
<Tab title="Parallel Execution">
|
||||
Parallel execution becomes valuable when tasks are independent of each other, time efficiency is important, or different expertise areas are involved that don't require coordination. This approach can significantly reduce overall execution time while allowing specialized agents to work on their areas of strength simultaneously.
|
||||
|
||||
Successful parallel execution requires identifying tasks that can truly run independently, grouping related but separate work streams effectively, and planning for result integration when parallel tasks need to be combined into a final deliverable. The key is ensuring that parallel tasks don't create conflicts or redundancies that reduce overall quality.
|
||||
|
||||
Consider parallel execution when you have multiple independent research streams, different types of analysis that don't depend on each other, or content creation tasks that can be developed simultaneously. However, be mindful of resource allocation and ensure that parallel execution doesn't overwhelm your available model capacity or budget.
|
||||
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Optimizing Agent Configuration for LLM Performance
|
||||
|
||||
### a. Role-Driven LLM Selection
|
||||
|
||||
<Warning>
|
||||
Generic agent roles make it impossible to select the right LLM. Specific roles
|
||||
enable targeted model optimization.
|
||||
</Warning>
|
||||
|
||||
The specificity of your agent roles directly determines which LLM capabilities matter most for optimal performance. This creates a strategic opportunity to match precise model strengths with agent responsibilities.
|
||||
|
||||
**Generic vs. Specific Role Impact on LLM Choice:**
|
||||
|
||||
When defining roles, think about the specific domain knowledge, working style, and decision-making frameworks that would be most valuable for the tasks the agent will handle. The more specific and contextual the role definition, the better the model can embody that role effectively.
|
||||
|
||||
```python
|
||||
# ✅ Specific role - clear LLM requirements
|
||||
specific_agent = Agent(
|
||||
role="SaaS Revenue Operations Analyst", # Clear domain expertise needed
|
||||
goal="Analyze recurring revenue metrics and identify growth opportunities",
|
||||
backstory="Specialist in SaaS business models with deep understanding of ARR, churn, and expansion revenue",
|
||||
llm=LLM(model="gpt-4o") # Reasoning model justified for complex analysis
|
||||
)
|
||||
```
|
||||
|
||||
**Role-to-Model Mapping Strategy:**
|
||||
|
||||
- **"Research Analyst"** → Reasoning model (GPT-4o, Claude Sonnet) for complex analysis
|
||||
- **"Content Editor"** → Creative model (Claude, GPT-4o) for writing quality
|
||||
- **"Data Processor"** → Efficient model (GPT-4o-mini, Gemini Flash) for structured tasks
|
||||
- **"API Coordinator"** → Function-calling optimized model (GPT-4o, Claude) for tool usage
|
||||
|
||||
### b. Backstory as Model Context Amplifier
|
||||
|
||||
<Info>
|
||||
Strategic backstories multiply your chosen LLM's effectiveness by providing
|
||||
domain-specific context that generic prompting cannot achieve.
|
||||
</Info>
|
||||
|
||||
A well-crafted backstory transforms your LLM choice from generic capability to specialized expertise. This is especially crucial for cost optimization - a well-contextualized efficient model can outperform a premium model without proper context.
|
||||
|
||||
**Context-Driven Performance Example:**
|
||||
|
||||
```python
|
||||
# Context amplifies model effectiveness
|
||||
domain_expert = Agent(
|
||||
role="B2B SaaS Marketing Strategist",
|
||||
goal="Develop comprehensive go-to-market strategies for enterprise software",
|
||||
backstory="""
|
||||
You have 10+ years of experience scaling B2B SaaS companies from Series A to IPO.
|
||||
You understand the nuances of enterprise sales cycles, the importance of product-market
|
||||
fit in different verticals, and how to balance growth metrics with unit economics.
|
||||
You've worked with companies like Salesforce, HubSpot, and emerging unicorns, giving
|
||||
you perspective on both established and disruptive go-to-market strategies.
|
||||
""",
|
||||
llm=LLM(model="claude-3-5-sonnet", temperature=0.3) # Balanced creativity with domain knowledge
|
||||
)
|
||||
|
||||
# This context enables Claude to perform like a domain expert
|
||||
# Without it, even it would produce generic marketing advice
|
||||
```
|
||||
|
||||
**Backstory Elements That Enhance LLM Performance:**
|
||||
|
||||
- **Domain Experience**: "10+ years in enterprise SaaS sales"
|
||||
- **Specific Expertise**: "Specializes in technical due diligence for Series B+ rounds"
|
||||
- **Working Style**: "Prefers data-driven decisions with clear documentation"
|
||||
- **Quality Standards**: "Insists on citing sources and showing analytical work"
|
||||
|
||||
### c. Holistic Agent-LLM Optimization
|
||||
|
||||
The most effective agent configurations create synergy between role specificity, backstory depth, and LLM selection. Each element reinforces the others to maximize model performance.
|
||||
|
||||
**Optimization Framework:**
|
||||
|
||||
```python
|
||||
# Example: Technical Documentation Agent
|
||||
tech_writer = Agent(
|
||||
role="API Documentation Specialist", # Specific role for clear LLM requirements
|
||||
goal="Create comprehensive, developer-friendly API documentation",
|
||||
backstory="""
|
||||
You're a technical writer with 8+ years documenting REST APIs, GraphQL endpoints,
|
||||
and SDK integration guides. You've worked with developer tools companies and
|
||||
understand what developers need: clear examples, comprehensive error handling,
|
||||
and practical use cases. You prioritize accuracy and usability over marketing fluff.
|
||||
""",
|
||||
llm=LLM(
|
||||
model="claude-3-5-sonnet", # Excellent for technical writing
|
||||
temperature=0.1 # Low temperature for accuracy
|
||||
),
|
||||
tools=[code_analyzer_tool, api_scanner_tool],
|
||||
verbose=True
|
||||
)
|
||||
```
|
||||
|
||||
**Alignment Checklist:**
|
||||
|
||||
- ✅ **Role Specificity**: Clear domain and responsibilities
|
||||
- ✅ **LLM Match**: Model strengths align with role requirements
|
||||
- ✅ **Backstory Depth**: Provides domain context the LLM can leverage
|
||||
- ✅ **Tool Integration**: Tools support the agent's specialized function
|
||||
- ✅ **Parameter Tuning**: Temperature and settings optimize for role needs
|
||||
|
||||
The key is creating agents where every configuration choice reinforces your LLM selection strategy, maximizing performance while optimizing costs.
|
||||
|
||||
## Practical Implementation Checklist
|
||||
|
||||
Rather than repeating the strategic framework, here's a tactical checklist for implementing your LLM selection decisions in CrewAI:
|
||||
|
||||
<Steps>
|
||||
<Step title="Audit Your Current Setup" icon="clipboard-check">
|
||||
**What to Review:**
|
||||
- Are all agents using the same LLM by default?
|
||||
- Which agents handle the most complex reasoning tasks?
|
||||
- Which agents primarily do data processing or formatting?
|
||||
- Are any agents heavily tool-dependent?
|
||||
|
||||
**Action**: Document current agent roles and identify optimization opportunities.
|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Implement Crew-Level Strategy" icon="users-gear">
|
||||
**Set Your Baseline:**
|
||||
```python
|
||||
# Start with a reliable default for the crew
|
||||
default_crew_llm = LLM(model="gpt-4o-mini") # Cost-effective baseline
|
||||
|
||||
crew = Crew(
|
||||
agents=[...],
|
||||
tasks=[...],
|
||||
memory=True
|
||||
)
|
||||
```
|
||||
|
||||
**Action**: Establish your crew's default LLM before optimizing individual agents.
|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Optimize High-Impact Agents" icon="star">
|
||||
**Identify and Upgrade Key Agents:**
|
||||
```python
|
||||
# Manager or coordination agents
|
||||
manager_agent = Agent(
|
||||
role="Project Manager",
|
||||
llm=LLM(model="gemini-2.5-flash-preview-05-20"), # Premium for coordination
|
||||
# ... rest of config
|
||||
)
|
||||
|
||||
# Creative or customer-facing agents
|
||||
content_agent = Agent(
|
||||
role="Content Creator",
|
||||
llm=LLM(model="claude-3-5-sonnet"), # Best for writing
|
||||
# ... rest of config
|
||||
)
|
||||
```
|
||||
|
||||
**Action**: Upgrade 20% of your agents that handle 80% of the complexity.
|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Validate with Enterprise Testing" icon="test-tube">
|
||||
**Once you deploy your agents to production:**
|
||||
- Use [CrewAI AMP platform](https://app.crewai.com) to A/B test your model selections
|
||||
- Run multiple iterations with real inputs to measure consistency and performance
|
||||
- Compare cost vs. performance across your optimized setup
|
||||
- Share results with your team for collaborative decision-making
|
||||
|
||||
**Action**: Replace guesswork with data-driven validation using the testing platform.
|
||||
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
### When to Use Different Model Types
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Reasoning Models">
|
||||
Reasoning models become essential when tasks require genuine multi-step logical thinking, strategic planning, or high-level decision making that benefits from systematic analysis. These models excel when problems need to be broken down into components and analyzed systematically rather than handled through pattern matching or simple instruction following.
|
||||
|
||||
Consider reasoning models for business strategy development, complex data analysis that requires drawing insights from multiple sources, multi-step problem solving where each step depends on previous analysis, and strategic planning tasks that require considering multiple variables and their interactions.
|
||||
|
||||
However, reasoning models often come with higher costs and slower response times, so they're best reserved for tasks where their sophisticated capabilities provide genuine value rather than being used for simple operations that don't require complex reasoning.
|
||||
|
||||
</Tab>
|
||||
|
||||
<Tab title="Creative Models">
|
||||
Creative models become valuable when content generation is the primary output and the quality, style, and engagement level of that content directly impact success. These models excel when writing quality and style matter significantly, creative ideation or brainstorming is needed, or brand voice and tone are important considerations.
|
||||
|
||||
Use creative models for blog post writing and article creation, marketing copy that needs to engage and persuade, creative storytelling and narrative development, and brand communications where voice and tone are crucial. These models often understand nuance and context better than general purpose alternatives.
|
||||
|
||||
Creative models may be less suitable for technical or analytical tasks where precision and factual accuracy are more important than engagement and style. They're best used when the creative and communicative aspects of the output are primary success factors.
|
||||
|
||||
</Tab>
|
||||
|
||||
<Tab title="Efficient Models">
|
||||
Efficient models are ideal for high-frequency, routine operations where speed and cost optimization are priorities. These models work best when tasks have clear, well-defined parameters and don't require sophisticated reasoning or creative capabilities.
|
||||
|
||||
Consider efficient models for data processing and transformation tasks, simple formatting and organization operations, function calling and tool usage where precision matters more than sophistication, and high-volume operations where cost per operation is a significant factor.
|
||||
|
||||
The key with efficient models is ensuring that their capabilities align with task requirements. They can handle many routine operations effectively but may struggle with tasks requiring nuanced understanding, complex reasoning, or sophisticated content generation.
|
||||
|
||||
</Tab>
|
||||
|
||||
<Tab title="Open Source Models">
|
||||
Open source models become attractive when budget constraints are significant, data privacy requirements exist, customization needs are important, or local deployment is required for operational or compliance reasons.
|
||||
|
||||
Consider open source models for internal company tools where data privacy is paramount, privacy-sensitive applications that can't use external APIs, cost-optimized deployments where per-token pricing is prohibitive, and situations requiring custom model modifications or fine-tuning.
|
||||
|
||||
However, open source models require more technical expertise to deploy and maintain effectively. Consider the total cost of ownership including infrastructure, technical overhead, and ongoing maintenance when evaluating open source options.
|
||||
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Common CrewAI Model Selection Pitfalls
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="The 'One Model Fits All' Trap" icon="triangle-exclamation">
|
||||
**The Problem**: Using the same LLM for all agents in a crew, regardless of their specific roles and responsibilities. This is often the default approach but rarely optimal.
|
||||
|
||||
**Real Example**: Using GPT-4o for both a strategic planning manager and a data extraction agent. The manager needs reasoning capabilities worth the premium cost, but the data extractor could perform just as well with GPT-4o-mini at a fraction of the price.
|
||||
|
||||
**CrewAI Solution**: Leverage agent-specific LLM configuration to match model capabilities with agent roles:
|
||||
```python
|
||||
# Strategic agent gets premium model
|
||||
manager = Agent(role="Strategy Manager", llm=LLM(model="gpt-4o"))
|
||||
|
||||
# Processing agent gets efficient model
|
||||
processor = Agent(role="Data Processor", llm=LLM(model="gpt-4o-mini"))
|
||||
```
|
||||
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Ignoring Crew-Level vs Agent-Level LLM Hierarchy" icon="shuffle">
|
||||
**The Problem**: Not understanding how CrewAI's LLM hierarchy works - crew LLM, manager LLM, and agent LLM settings can conflict or be poorly coordinated.
|
||||
|
||||
**Real Example**: Setting a crew to use Claude, but having agents configured with GPT models, creating inconsistent behavior and unnecessary model switching overhead.
|
||||
|
||||
**CrewAI Solution**: Plan your LLM hierarchy strategically:
|
||||
```python
|
||||
crew = Crew(
|
||||
agents=[agent1, agent2],
|
||||
tasks=[task1, task2],
|
||||
manager_llm=LLM(model="gpt-4o"), # For crew coordination
|
||||
process=Process.hierarchical # When using manager_llm
|
||||
)
|
||||
|
||||
# Agents inherit crew LLM unless specifically overridden
|
||||
agent1 = Agent(llm=LLM(model="claude-3-5-sonnet")) # Override for specific needs
|
||||
```
|
||||
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Function Calling Model Mismatch" icon="screwdriver-wrench">
|
||||
**The Problem**: Choosing models based on general capabilities while ignoring function calling performance for tool-heavy CrewAI workflows.
|
||||
|
||||
**Real Example**: Selecting a creative-focused model for an agent that primarily needs to call APIs, search tools, or process structured data. The agent struggles with tool parameter extraction and reliable function calls.
|
||||
|
||||
**CrewAI Solution**: Prioritize function calling capabilities for tool-heavy agents:
|
||||
```python
|
||||
# For agents that use many tools
|
||||
tool_agent = Agent(
|
||||
role="API Integration Specialist",
|
||||
tools=[search_tool, api_tool, data_tool],
|
||||
llm=LLM(model="gpt-4o"), # Excellent function calling
|
||||
# OR
|
||||
llm=LLM(model="claude-3-5-sonnet") # Also strong with tools
|
||||
)
|
||||
```
|
||||
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Premature Optimization Without Testing" icon="gear">
|
||||
**The Problem**: Making complex model selection decisions based on theoretical performance without validating with actual CrewAI workflows and tasks.
|
||||
|
||||
**Real Example**: Implementing elaborate model switching logic based on task types without testing if the performance gains justify the operational complexity.
|
||||
|
||||
**CrewAI Solution**: Start simple, then optimize based on real performance data:
|
||||
```python
|
||||
# Start with this
|
||||
crew = Crew(agents=[...], tasks=[...], llm=LLM(model="gpt-4o-mini"))
|
||||
|
||||
# Test performance, then optimize specific agents as needed
|
||||
# Use Enterprise platform testing to validate improvements
|
||||
```
|
||||
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Overlooking Context and Memory Limitations" icon="brain">
|
||||
**The Problem**: Not considering how model context windows interact with CrewAI's memory and context sharing between agents.
|
||||
|
||||
**Real Example**: Using a short-context model for agents that need to maintain conversation history across multiple task iterations, or in crews with extensive agent-to-agent communication.
|
||||
|
||||
**CrewAI Solution**: Match context capabilities to crew communication patterns.
|
||||
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Testing and Iteration Strategy
|
||||
|
||||
<Steps>
|
||||
<Step title="Start Simple" icon="play">
|
||||
Begin with reliable, general-purpose models that are well-understood and
|
||||
widely supported. This provides a stable foundation for understanding your
|
||||
specific requirements and performance expectations before optimizing for
|
||||
specialized needs.
|
||||
</Step>
|
||||
<Step title="Measure What Matters" icon="chart-line">
|
||||
Develop metrics that align with your specific use case and business
|
||||
requirements rather than relying solely on general benchmarks. Focus on
|
||||
measuring outcomes that directly impact your success rather than theoretical
|
||||
performance indicators.
|
||||
</Step>
|
||||
<Step title="Iterate Based on Results" icon="arrows-rotate">
|
||||
Make model changes based on observed performance in your specific context
|
||||
rather than theoretical considerations or general recommendations.
|
||||
Real-world performance often differs significantly from benchmark results or
|
||||
general reputation.
|
||||
</Step>
|
||||
<Step title="Consider Total Cost" icon="calculator">
|
||||
Evaluate the complete cost of ownership including model costs, development
|
||||
time, maintenance overhead, and operational complexity. The cheapest model
|
||||
per token may not be the most cost-effective choice when considering all
|
||||
factors.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<Tip>
|
||||
Focus on understanding your requirements first, then select models that best
|
||||
match those needs. The best LLM choice is the one that consistently delivers
|
||||
the results you need within your operational constraints.
|
||||
</Tip>
|
||||
|
||||
### Enterprise-Grade Model Validation
|
||||
|
||||
For teams serious about optimizing their LLM selection, the **CrewAI AMP platform** provides sophisticated testing capabilities that go far beyond basic CLI testing. The platform enables comprehensive model evaluation that helps you make data-driven decisions about your LLM strategy.
|
||||
|
||||
<Frame>
|
||||

|
||||
</Frame>
|
||||
|
||||
**Advanced Testing Features:**
|
||||
|
||||
- **Multi-Model Comparison**: Test multiple LLMs simultaneously across the same tasks and inputs. Compare performance between GPT-4o, Claude, Llama, Groq, Cerebras, and other leading models in parallel to identify the best fit for your specific use case.
|
||||
|
||||
- **Statistical Rigor**: Configure multiple iterations with consistent inputs to measure reliability and performance variance. This helps identify models that not only perform well but do so consistently across runs.
|
||||
|
||||
- **Real-World Validation**: Use your actual crew inputs and scenarios rather than synthetic benchmarks. The platform allows you to test with your specific industry context, company information, and real use cases for more accurate evaluation.
|
||||
|
||||
- **Comprehensive Analytics**: Access detailed performance metrics, execution times, and cost analysis across all tested models. This enables data-driven decision making rather than relying on general model reputation or theoretical capabilities.
|
||||
|
||||
- **Team Collaboration**: Share testing results and model performance data across your team, enabling collaborative decision-making and consistent model selection strategies across projects.
|
||||
|
||||
Go to [app.crewai.com](https://app.crewai.com) to get started!
|
||||
|
||||
<Info>
|
||||
The Enterprise platform transforms model selection from guesswork into a
|
||||
data-driven process, enabling you to validate the principles in this guide
|
||||
with your actual use cases and requirements.
|
||||
</Info>
|
||||
|
||||
## Key Principles Summary
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Task-Driven Selection" icon="bullseye">
|
||||
Choose models based on what the task actually requires, not theoretical capabilities or general reputation.
|
||||
</Card>
|
||||
|
||||
{" "}
|
||||
<Card title="Capability Matching" icon="puzzle-piece">
|
||||
Align model strengths with agent roles and responsibilities for optimal
|
||||
performance.
|
||||
</Card>
|
||||
|
||||
{" "}
|
||||
<Card title="Strategic Consistency" icon="link">
|
||||
Maintain coherent model selection strategy across related components and
|
||||
workflows.
|
||||
</Card>
|
||||
|
||||
{" "}
|
||||
<Card title="Practical Testing" icon="flask">
|
||||
Validate choices through real-world usage rather than benchmarks alone.
|
||||
</Card>
|
||||
|
||||
{" "}
|
||||
<Card title="Iterative Improvement" icon="arrow-up">
|
||||
Start simple and optimize based on actual performance and needs.
|
||||
</Card>
|
||||
|
||||
<Card title="Operational Balance" icon="scale-balanced">
|
||||
Balance performance requirements with cost and complexity constraints.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Check>
|
||||
Remember: The best LLM choice is the one that consistently delivers the
|
||||
results you need within your operational constraints. Focus on understanding
|
||||
your requirements first, then select models that best match those needs.
|
||||
</Check>
|
||||
|
||||
## Current Model Landscape (June 2025)
|
||||
|
||||
<Warning>
|
||||
**Snapshot in Time**: The following model rankings represent current
|
||||
leaderboard standings as of June 2025, compiled from [LMSys
|
||||
Arena](https://arena.lmsys.org/), [Artificial
|
||||
Analysis](https://artificialanalysis.ai/), and other leading benchmarks. LLM
|
||||
performance, availability, and pricing change rapidly. Always conduct your own
|
||||
evaluations with your specific use cases and data.
|
||||
</Warning>
|
||||
|
||||
### Leading Models by Category
|
||||
|
||||
The tables below show a representative sample of current top-performing models across different categories, with guidance on their suitability for CrewAI agents:
|
||||
|
||||
<Note>
|
||||
These tables/metrics showcase selected leading models in each category and are
|
||||
not exhaustive. Many excellent models exist beyond those listed here. The goal
|
||||
is to illustrate the types of capabilities to look for rather than provide a
|
||||
complete catalog.
|
||||
</Note>
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Reasoning & Planning">
|
||||
**Best for Manager LLMs and Complex Analysis**
|
||||
|
||||
| Model | Intelligence Score | Cost ($/M tokens) | Speed | Best Use in CrewAI |
|
||||
|:------|:------------------|:------------------|:------|:------------------|
|
||||
| **o3** | 70 | $17.50 | Fast | Manager LLM for complex multi-agent coordination |
|
||||
| **Gemini 2.5 Pro** | 69 | $3.44 | Fast | Strategic planning agents, research coordination |
|
||||
| **DeepSeek R1** | 68 | $0.96 | Moderate | Cost-effective reasoning for budget-conscious crews |
|
||||
| **Claude 4 Sonnet** | 53 | $6.00 | Fast | Analysis agents requiring nuanced understanding |
|
||||
| **Qwen3 235B (Reasoning)** | 62 | $2.63 | Moderate | Open-source alternative for reasoning tasks |
|
||||
|
||||
These models excel at multi-step reasoning and are ideal for agents that need to develop strategies, coordinate other agents, or analyze complex information.
|
||||
|
||||
</Tab>
|
||||
|
||||
<Tab title="Coding & Technical">
|
||||
**Best for Development and Tool-Heavy Workflows**
|
||||
|
||||
| Model | Coding Performance | Tool Use Score | Cost ($/M tokens) | Best Use in CrewAI |
|
||||
|:------|:------------------|:---------------|:------------------|:------------------|
|
||||
| **Claude 4 Sonnet** | Excellent | 72.7% | $6.00 | Primary coding agent, technical documentation |
|
||||
| **Claude 4 Opus** | Excellent | 72.5% | $30.00 | Complex software architecture, code review |
|
||||
| **DeepSeek V3** | Very Good | High | $0.48 | Cost-effective coding for routine development |
|
||||
| **Qwen2.5 Coder 32B** | Very Good | Medium | $0.15 | Budget-friendly coding agent |
|
||||
| **Llama 3.1 405B** | Good | 81.1% | $3.50 | Function calling LLM for tool-heavy workflows |
|
||||
|
||||
These models are optimized for code generation, debugging, and technical problem-solving, making them ideal for development-focused crews.
|
||||
|
||||
</Tab>
|
||||
|
||||
<Tab title="Speed & Efficiency">
|
||||
**Best for High-Throughput and Real-Time Applications**
|
||||
|
||||
| Model | Speed (tokens/s) | Latency (TTFT) | Cost ($/M tokens) | Best Use in CrewAI |
|
||||
|:------|:-----------------|:---------------|:------------------|:------------------|
|
||||
| **Llama 4 Scout** | 2,600 | 0.33s | $0.27 | High-volume processing agents |
|
||||
| **Gemini 2.5 Flash** | 376 | 0.30s | $0.26 | Real-time response agents |
|
||||
| **DeepSeek R1 Distill** | 383 | Variable | $0.04 | Cost-optimized high-speed processing |
|
||||
| **Llama 3.3 70B** | 2,500 | 0.52s | $0.60 | Balanced speed and capability |
|
||||
| **Nova Micro** | High | 0.30s | $0.04 | Simple, fast task execution |
|
||||
|
||||
These models prioritize speed and efficiency, perfect for agents handling routine operations or requiring quick responses. **Pro tip**: Pairing these models with fast inference providers like Groq can achieve even better performance, especially for open-source models like Llama.
|
||||
|
||||
</Tab>
|
||||
|
||||
<Tab title="Balanced Performance">
|
||||
**Best All-Around Models for General Crews**
|
||||
|
||||
| Model | Overall Score | Versatility | Cost ($/M tokens) | Best Use in CrewAI |
|
||||
|:------|:--------------|:------------|:------------------|:------------------|
|
||||
| **GPT-4.1** | 53 | Excellent | $3.50 | General-purpose crew LLM |
|
||||
| **Claude 3.7 Sonnet** | 48 | Very Good | $6.00 | Balanced reasoning and creativity |
|
||||
| **Gemini 2.0 Flash** | 48 | Good | $0.17 | Cost-effective general use |
|
||||
| **Llama 4 Maverick** | 51 | Good | $0.37 | Open-source general purpose |
|
||||
| **Qwen3 32B** | 44 | Good | $1.23 | Budget-friendly versatility |
|
||||
|
||||
These models offer good performance across multiple dimensions, suitable for crews with diverse task requirements.
|
||||
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### Selection Framework for Current Models
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="High-Performance Crews" icon="rocket">
|
||||
**When performance is the priority**: Use top-tier models like **o3**, **Gemini 2.5 Pro**, or **Claude 4 Sonnet** for manager LLMs and critical agents. These models excel at complex reasoning and coordination but come with higher costs.
|
||||
|
||||
**Strategy**: Implement a multi-model approach where premium models handle strategic thinking while efficient models handle routine operations.
|
||||
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Cost-Conscious Crews" icon="dollar-sign">
|
||||
**When budget is a primary constraint**: Focus on models like **DeepSeek R1**, **Llama 4 Scout**, or **Gemini 2.0 Flash**. These provide strong performance at significantly lower costs.
|
||||
|
||||
**Strategy**: Use cost-effective models for most agents, reserving premium models only for the most critical decision-making roles.
|
||||
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Specialized Workflows" icon="screwdriver-wrench">
|
||||
**For specific domain expertise**: Choose models optimized for your primary use case. **Claude 4** series for coding, **Gemini 2.5 Pro** for research, **Llama 405B** for function calling.
|
||||
|
||||
**Strategy**: Select models based on your crew's primary function, ensuring the core capability aligns with model strengths.
|
||||
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Enterprise & Privacy" icon="shield">
|
||||
**For data-sensitive operations**: Consider open-source models like **Llama 4** series, **DeepSeek V3**, or **Qwen3** that can be deployed locally while maintaining competitive performance.
|
||||
|
||||
**Strategy**: Deploy open-source models on private infrastructure, accepting potential performance trade-offs for data control.
|
||||
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
### Key Considerations for Model Selection
|
||||
|
||||
- **Performance Trends**: The current landscape shows strong competition between reasoning-focused models (o3, Gemini 2.5 Pro) and balanced models (Claude 4, GPT-4.1). Specialized models like DeepSeek R1 offer excellent cost-performance ratios.
|
||||
|
||||
- **Speed vs. Intelligence Trade-offs**: Models like Llama 4 Scout prioritize speed (2,600 tokens/s) while maintaining reasonable intelligence, whereas models like o3 maximize reasoning capability at the cost of speed and price.
|
||||
|
||||
- **Open Source Viability**: The gap between open-source and proprietary models continues to narrow, with models like Llama 4 Maverick and DeepSeek V3 offering competitive performance at attractive price points. Fast inference providers particularly shine with open-source models, often delivering better speed-to-cost ratios than proprietary alternatives.
|
||||
|
||||
<Info>
|
||||
**Testing is Essential**: Leaderboard rankings provide general guidance, but
|
||||
your specific use case, prompting style, and evaluation criteria may produce
|
||||
different results. Always test candidate models with your actual tasks and
|
||||
data before making final decisions.
|
||||
</Info>
|
||||
|
||||
### Practical Implementation Strategy
|
||||
|
||||
<Steps>
|
||||
<Step title="Start with Proven Models">
|
||||
Begin with well-established models like **GPT-4.1**, **Claude 3.7 Sonnet**, or **Gemini 2.0 Flash** that offer good performance across multiple dimensions and have extensive real-world validation.
|
||||
</Step>
|
||||
|
||||
{" "}
|
||||
<Step title="Identify Specialized Needs">
|
||||
Determine if your crew has specific requirements (coding, reasoning, speed)
|
||||
that would benefit from specialized models like **Claude 4 Sonnet** for
|
||||
development or **o3** for complex analysis. For speed-critical applications,
|
||||
consider fast inference providers like **Groq** alongside model selection.
|
||||
</Step>
|
||||
|
||||
{" "}
|
||||
<Step title="Implement Multi-Model Strategy">
|
||||
Use different models for different agents based on their roles.
|
||||
High-capability models for managers and complex tasks, efficient models for
|
||||
routine operations.
|
||||
</Step>
|
||||
|
||||
<Step title="Monitor and Optimize">
|
||||
Track performance metrics relevant to your use case and be prepared to adjust model selections as new models are released or pricing changes.
|
||||
</Step>
|
||||
</Steps>
|
||||
141
docs/ar/learn/multimodal-agents.mdx
Normal file
141
docs/ar/learn/multimodal-agents.mdx
Normal file
@@ -0,0 +1,141 @@
|
||||
---
|
||||
title: استخدام الوكلاء متعددي الوسائط
|
||||
description: تعلم كيفية تفعيل واستخدام القدرات متعددة الوسائط في وكلائك لمعالجة الصور والمحتوى غير النصي ضمن إطار عمل CrewAI.
|
||||
icon: video
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## استخدام الوكلاء متعددي الوسائط
|
||||
|
||||
يدعم CrewAI الوكلاء متعددي الوسائط القادرين على معالجة المحتوى النصي وغير النصي مثل الصور. سيوضح لك هذا الدليل كيفية تفعيل واستخدام القدرات متعددة الوسائط في وكلائك.
|
||||
|
||||
### تفعيل القدرات متعددة الوسائط
|
||||
|
||||
لإنشاء وكيل متعدد الوسائط، ما عليك سوى تعيين معامل `multimodal` إلى `True` عند تهيئة وكيلك:
|
||||
|
||||
```python
|
||||
from crewai import Agent
|
||||
|
||||
agent = Agent(
|
||||
role="Image Analyst",
|
||||
goal="Analyze and extract insights from images",
|
||||
backstory="An expert in visual content interpretation with years of experience in image analysis",
|
||||
multimodal=True # This enables multimodal capabilities
|
||||
)
|
||||
```
|
||||
|
||||
عند تعيين `multimodal=True`، يتم إعداد الوكيل تلقائياً بالأدوات اللازمة للتعامل مع المحتوى غير النصي، بما في ذلك `AddImageTool`.
|
||||
|
||||
### العمل مع الصور
|
||||
|
||||
يأتي الوكيل متعدد الوسائط مُعداً مسبقاً بأداة `AddImageTool`، التي تتيح له معالجة الصور. لا تحتاج إلى إضافة هذه الأداة يدوياً — فهي مضمنة تلقائياً عند تفعيل القدرات متعددة الوسائط.
|
||||
|
||||
إليك مثالاً كاملاً يوضح كيفية استخدام وكيل متعدد الوسائط لتحليل صورة:
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
|
||||
# Create a multimodal agent
|
||||
image_analyst = Agent(
|
||||
role="Product Analyst",
|
||||
goal="Analyze product images and provide detailed descriptions",
|
||||
backstory="Expert in visual product analysis with deep knowledge of design and features",
|
||||
multimodal=True
|
||||
)
|
||||
|
||||
# Create a task for image analysis
|
||||
task = Task(
|
||||
description="Analyze the product image at https://example.com/product.jpg and provide a detailed description",
|
||||
expected_output="A detailed description of the product image",
|
||||
agent=image_analyst
|
||||
)
|
||||
|
||||
# Create and run the crew
|
||||
crew = Crew(
|
||||
agents=[image_analyst],
|
||||
tasks=[task]
|
||||
)
|
||||
|
||||
result = crew.kickoff()
|
||||
```
|
||||
|
||||
### الاستخدام المتقدم مع السياق
|
||||
|
||||
يمكنك تقديم سياق إضافي أو أسئلة محددة حول الصورة عند إنشاء مهام للوكلاء متعددي الوسائط. يمكن أن يتضمن وصف المهمة جوانب محددة تريد أن يركز عليها الوكيل:
|
||||
|
||||
```python
|
||||
from crewai import Agent, Task, Crew
|
||||
|
||||
# Create a multimodal agent for detailed analysis
|
||||
expert_analyst = Agent(
|
||||
role="Visual Quality Inspector",
|
||||
goal="Perform detailed quality analysis of product images",
|
||||
backstory="Senior quality control expert with expertise in visual inspection",
|
||||
multimodal=True # AddImageTool is automatically included
|
||||
)
|
||||
|
||||
# Create a task with specific analysis requirements
|
||||
inspection_task = Task(
|
||||
description="""
|
||||
Analyze the product image at https://example.com/product.jpg with focus on:
|
||||
1. Quality of materials
|
||||
2. Manufacturing defects
|
||||
3. Compliance with standards
|
||||
Provide a detailed report highlighting any issues found.
|
||||
""",
|
||||
expected_output="A detailed report highlighting any issues found",
|
||||
agent=expert_analyst
|
||||
)
|
||||
|
||||
# Create and run the crew
|
||||
crew = Crew(
|
||||
agents=[expert_analyst],
|
||||
tasks=[inspection_task]
|
||||
)
|
||||
|
||||
result = crew.kickoff()
|
||||
```
|
||||
|
||||
### تفاصيل الأداة
|
||||
|
||||
عند العمل مع الوكلاء متعددي الوسائط، يتم إعداد `AddImageTool` تلقائياً بالمخطط التالي:
|
||||
|
||||
```python
|
||||
class AddImageToolSchema:
|
||||
image_url: str # Required: The URL or path of the image to process
|
||||
action: Optional[str] = None # Optional: Additional context or specific questions about the image
|
||||
```
|
||||
|
||||
سيتعامل الوكيل متعدد الوسائط تلقائياً مع معالجة الصور من خلال أدواته المدمجة، مما يتيح له:
|
||||
- الوصول إلى الصور عبر عناوين URL أو مسارات الملفات المحلية
|
||||
- معالجة محتوى الصورة مع سياق اختياري أو أسئلة محددة
|
||||
- تقديم تحليلات ورؤى بناءً على المعلومات البصرية ومتطلبات المهمة
|
||||
|
||||
### أفضل الممارسات
|
||||
|
||||
عند العمل مع الوكلاء متعددي الوسائط، ضع هذه الممارسات في الاعتبار:
|
||||
|
||||
1. **الوصول إلى الصور**
|
||||
- تأكد من أن صورك قابلة للوصول عبر عناوين URL التي يمكن للوكيل الوصول إليها
|
||||
- للصور المحلية، فكر في استضافتها مؤقتاً أو استخدام مسارات ملفات مطلقة
|
||||
- تحقق من أن عناوين URL للصور صالحة وقابلة للوصول قبل تشغيل المهام
|
||||
|
||||
2. **وصف المهمة**
|
||||
- كن محدداً حول الجوانب التي تريد من الوكيل تحليلها في الصورة
|
||||
- قم بتضمين أسئلة أو متطلبات واضحة في وصف المهمة
|
||||
- فكر في استخدام معامل `action` الاختياري للتحليل المركز
|
||||
|
||||
3. **إدارة الموارد**
|
||||
- قد تتطلب معالجة الصور موارد حسابية أكثر من المهام النصية فقط
|
||||
- قد تتطلب بعض نماذج اللغة ترميز base64 لبيانات الصورة
|
||||
- فكر في المعالجة الدفعية لصور متعددة لتحسين الأداء
|
||||
|
||||
4. **إعداد البيئة**
|
||||
- تحقق من أن بيئتك تحتوي على الاعتماديات اللازمة لمعالجة الصور
|
||||
- تأكد من أن نموذج اللغة الخاص بك يدعم القدرات متعددة الوسائط
|
||||
- اختبر بصور صغيرة أولاً للتحقق من إعدادك
|
||||
|
||||
5. **معالجة الأخطاء**
|
||||
- نفّذ معالجة أخطاء مناسبة لحالات فشل تحميل الصور
|
||||
- ضع استراتيجيات احتياطية لحالات فشل معالجة الصور
|
||||
- راقب وسجل عمليات معالجة الصور لأغراض التصحيح
|
||||
159
docs/ar/learn/overview.mdx
Normal file
159
docs/ar/learn/overview.mdx
Normal file
@@ -0,0 +1,159 @@
|
||||
---
|
||||
title: "نظرة عامة"
|
||||
description: "تعلم كيفية بناء وتخصيص وتحسين تطبيقات CrewAI الخاصة بك مع أدلة وبرامج تعليمية شاملة"
|
||||
icon: "face-smile"
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## تعلم CrewAI
|
||||
|
||||
يوفر هذا القسم أدلة وبرامج تعليمية شاملة لمساعدتك في إتقان CrewAI، من المفاهيم الأساسية إلى التقنيات المتقدمة. سواء كنت قد بدأت للتو أو تبحث عن تحسين تطبيقاتك الحالية، ستوجهك هذه الموارد عبر كل جانب من جوانب بناء سير عمل وكلاء الذكاء الاصطناعي القوية.
|
||||
|
||||
## أدلة البدء
|
||||
|
||||
### المفاهيم الأساسية
|
||||
<CardGroup cols={2}>
|
||||
<Card title="العملية التسلسلية" icon="list-ol" href="/ar/learn/sequential-process">
|
||||
تعلم كيفية تنفيذ المهام بترتيب تسلسلي لسير عمل منظم.
|
||||
</Card>
|
||||
|
||||
<Card title="العملية الهرمية" icon="sitemap" href="/ar/learn/hierarchical-process">
|
||||
تنفيذ تنفيذ المهام الهرمي مع وكلاء مديرين يشرفون على سير العمل.
|
||||
</Card>
|
||||
|
||||
<Card title="المهام الشرطية" icon="code-branch" href="/ar/learn/conditional-tasks">
|
||||
إنشاء سير عمل ديناميكي مع تنفيذ مهام شرطي بناءً على النتائج.
|
||||
</Card>
|
||||
|
||||
<Card title="التشغيل غير المتزامن" icon="bolt" href="/ar/learn/kickoff-async">
|
||||
تنفيذ الأطقم بشكل غير متزامن لأداء وتزامن محسّن.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
### تطوير الوكلاء
|
||||
<CardGroup cols={2}>
|
||||
<Card title="تخصيص الوكلاء" icon="user-gear" href="/ar/learn/customizing-agents">
|
||||
تعلم كيفية تخصيص سلوك الوكلاء وأدوارهم وقدراتهم.
|
||||
</Card>
|
||||
|
||||
<Card title="وكلاء البرمجة" icon="code" href="/ar/learn/coding-agents">
|
||||
بناء وكلاء يمكنهم كتابة وتنفيذ وتصحيح الكود تلقائياً.
|
||||
</Card>
|
||||
|
||||
<Card title="الوكلاء متعددو الوسائط" icon="images" href="/ar/learn/multimodal-agents">
|
||||
إنشاء وكلاء يمكنهم معالجة النصوص والصور وأنواع الوسائط الأخرى.
|
||||
</Card>
|
||||
|
||||
<Card title="وكيل المدير المخصص" icon="user-tie" href="/ar/learn/custom-manager-agent">
|
||||
تنفيذ وكلاء مديرين مخصصين لسير العمل الهرمي المعقد.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## الميزات المتقدمة
|
||||
|
||||
### التحكم في سير العمل
|
||||
<CardGroup cols={2}>
|
||||
<Card title="الإنسان في الحلقة" icon="user-check" href="/ar/learn/human-in-the-loop">
|
||||
دمج الإشراف البشري والتدخل في سير عمل الوكلاء.
|
||||
</Card>
|
||||
|
||||
<Card title="الإدخال البشري أثناء التنفيذ" icon="hand-paper" href="/ar/learn/human-input-on-execution">
|
||||
السماح بالإدخال البشري أثناء تنفيذ المهام لاتخاذ قرارات ديناميكية.
|
||||
</Card>
|
||||
|
||||
<Card title="إعادة تشغيل المهام" icon="rotate-left" href="/ar/learn/replay-tasks-from-latest-crew-kickoff">
|
||||
إعادة تشغيل واستئناف المهام من عمليات تنفيذ الطاقم السابقة.
|
||||
</Card>
|
||||
|
||||
<Card title="التشغيل لكل عنصر" icon="repeat" href="/ar/learn/kickoff-for-each">
|
||||
تنفيذ الأطقم عدة مرات بمدخلات مختلفة بكفاءة.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
### التخصيص والتكامل
|
||||
<CardGroup cols={2}>
|
||||
<Card title="LLM مخصص" icon="brain" href="/ar/learn/custom-llm">
|
||||
دمج نماذج لغة ومزودين مخصصين مع CrewAI.
|
||||
</Card>
|
||||
|
||||
<Card title="اتصالات LLM" icon="link" href="/ar/learn/llm-connections">
|
||||
إعداد وإدارة الاتصالات بمزودي LLM المختلفين.
|
||||
</Card>
|
||||
|
||||
<Card title="إنشاء أدوات مخصصة" icon="wrench" href="/ar/learn/create-custom-tools">
|
||||
بناء أدوات مخصصة لتوسيع قدرات الوكلاء.
|
||||
</Card>
|
||||
|
||||
<Card title="استخدام التعليقات التوضيحية" icon="at" href="/ar/learn/using-annotations">
|
||||
استخدام تعليقات Python التوضيحية لكود أنظف وأسهل في الصيانة.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## التطبيقات المتخصصة
|
||||
|
||||
### المحتوى والوسائط
|
||||
<CardGroup cols={2}>
|
||||
<Card title="توليد صور DALL-E" icon="image" href="/ar/learn/dalle-image-generation">
|
||||
توليد الصور باستخدام تكامل DALL-E مع وكلائك.
|
||||
</Card>
|
||||
|
||||
<Card title="أحضر وكيلك الخاص" icon="user-plus" href="/ar/learn/bring-your-own-agent">
|
||||
دمج الوكلاء والنماذج الموجودة في سير عمل CrewAI.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
### إدارة الأدوات
|
||||
<CardGroup cols={2}>
|
||||
<Card title="فرض مخرجات الأداة كنتيجة" icon="hammer" href="/ar/learn/force-tool-output-as-result">
|
||||
إعداد الأدوات لإرجاع مخرجاتها مباشرة كنتائج للمهام.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## توصيات مسار التعلم
|
||||
|
||||
### للمبتدئين
|
||||
1. ابدأ بـ **العملية التسلسلية** لفهم تنفيذ سير العمل الأساسي
|
||||
2. تعلم **تخصيص الوكلاء** لإنشاء إعدادات وكلاء فعالة
|
||||
3. استكشف **إنشاء أدوات مخصصة** لتوسيع الوظائف
|
||||
4. جرب **الإنسان في الحلقة** لسير العمل التفاعلي
|
||||
|
||||
### للمستخدمين المتوسطين
|
||||
1. أتقن **العملية الهرمية** لأنظمة الوكلاء المتعددة المعقدة
|
||||
2. نفّذ **المهام الشرطية** لسير العمل الديناميكي
|
||||
3. استخدم **التشغيل غير المتزامن** لتحسين الأداء
|
||||
4. ادمج **LLM مخصص** للنماذج المتخصصة
|
||||
|
||||
### للمستخدمين المتقدمين
|
||||
1. ابنِ **وكلاء متعددي الوسائط** لمعالجة الوسائط المعقدة
|
||||
2. أنشئ **وكلاء مديرين مخصصين** للتنسيق المتطور
|
||||
3. نفّذ **أحضر وكيلك الخاص** للأنظمة الهجينة
|
||||
4. استخدم **إعادة تشغيل المهام** لاسترداد الأخطاء بشكل متين
|
||||
|
||||
## أفضل الممارسات
|
||||
|
||||
### التطوير
|
||||
- **ابدأ بالبساطة**: ابدأ بسير العمل التسلسلي الأساسي قبل إضافة التعقيد
|
||||
- **اختبر تدريجياً**: اختبر كل مكون قبل دمجه في أنظمة أكبر
|
||||
- **استخدم التعليقات التوضيحية**: استفد من تعليقات Python التوضيحية لكود أنظف وأسهل في الصيانة
|
||||
- **أدوات مخصصة**: ابنِ أدوات قابلة لإعادة الاستخدام يمكن مشاركتها عبر وكلاء مختلفين
|
||||
|
||||
### الإنتاج
|
||||
- **معالجة الأخطاء**: نفّذ معالجة أخطاء وآليات استرداد قوية
|
||||
- **الأداء**: استخدم التنفيذ غير المتزامن وحسّن استدعاءات LLM لأداء أفضل
|
||||
- **المراقبة**: ادمج أدوات المراقبة لتتبع أداء الوكلاء
|
||||
- **الإشراف البشري**: ضمّن نقاط تفتيش بشرية للقرارات الحرجة
|
||||
|
||||
### التحسين
|
||||
- **إدارة الموارد**: راقب وحسّن استخدام الرموز وتكاليف API
|
||||
- **تصميم سير العمل**: صمم سير عمل يقلل من استدعاءات LLM غير الضرورية
|
||||
- **كفاءة الأدوات**: أنشئ أدوات فعالة توفر أقصى قيمة بأقل حمل
|
||||
- **التحسين التكراري**: استخدم التغذية الراجعة والمقاييس لتحسين أداء الوكلاء باستمرار
|
||||
|
||||
## الحصول على المساعدة
|
||||
|
||||
- **التوثيق**: يتضمن كل دليل أمثلة وشروحات مفصلة
|
||||
- **المجتمع**: انضم إلى [منتدى CrewAI](https://community.crewai.com) للمناقشات والدعم
|
||||
- **الأمثلة**: تحقق من قسم الأمثلة للتطبيقات العاملة الكاملة
|
||||
- **الدعم**: تواصل مع [support@crewai.com](mailto:support@crewai.com) للمساعدة التقنية
|
||||
|
||||
ابدأ بالأدلة التي تتوافق مع احتياجاتك الحالية واستكشف تدريجياً المواضيع الأكثر تقدماً مع إتقانك للأساسيات.
|
||||
79
docs/ar/learn/replay-tasks-from-latest-crew-kickoff.mdx
Normal file
79
docs/ar/learn/replay-tasks-from-latest-crew-kickoff.mdx
Normal file
@@ -0,0 +1,79 @@
|
||||
---
|
||||
title: إعادة تشغيل المهام من آخر تنفيذ للطاقم
|
||||
description: إعادة تشغيل المهام من آخر crew.kickoff(...)
|
||||
icon: arrow-right
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## مقدمة
|
||||
|
||||
يوفر CrewAI القدرة على إعادة التشغيل من مهمة محددة من آخر تشغيل للطاقم. هذه الميزة مفيدة بشكل خاص عندما تكون قد أنهيت تشغيلاً وقد ترغب في إعادة محاولة مهام معينة أو لا تحتاج إلى إعادة جلب البيانات ووكلاؤك لديهم بالفعل السياق المحفوظ من تنفيذ التشغيل، لذا تحتاج فقط إلى إعادة تشغيل المهام التي تريدها.
|
||||
|
||||
<Note>
|
||||
يجب عليك تشغيل `crew.kickoff()` قبل أن تتمكن من إعادة تشغيل مهمة.
|
||||
حالياً، يُدعم فقط آخر تشغيل، لذا إذا استخدمت `kickoff_for_each`، فسيسمح لك فقط بإعادة التشغيل من أحدث تشغيل للطاقم.
|
||||
</Note>
|
||||
|
||||
إليك مثالاً على كيفية إعادة التشغيل من مهمة:
|
||||
|
||||
### إعادة التشغيل من مهمة محددة باستخدام CLI
|
||||
|
||||
لاستخدام ميزة إعادة التشغيل، اتبع هذه الخطوات:
|
||||
|
||||
<Steps>
|
||||
<Step title="افتح الطرفية أو موجه الأوامر."></Step>
|
||||
<Step title="انتقل إلى المجلد الذي يقع فيه مشروع CrewAI الخاص بك."></Step>
|
||||
<Step title="شغّل الأوامر التالية:">
|
||||
لعرض معرفات المهام من آخر تشغيل، استخدم:
|
||||
|
||||
```shell
|
||||
crewai log-tasks-outputs
|
||||
```
|
||||
|
||||
بمجرد حصولك على `task_id` لإعادة التشغيل، استخدم:
|
||||
|
||||
```shell
|
||||
crewai replay -t <task_id>
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<Note>
|
||||
تأكد من أن `crewai` مثبت ومُعد بشكل صحيح في بيئة التطوير الخاصة بك.
|
||||
</Note>
|
||||
|
||||
### إعادة التشغيل من مهمة برمجياً
|
||||
|
||||
لإعادة التشغيل من مهمة برمجياً، استخدم الخطوات التالية:
|
||||
|
||||
<Steps>
|
||||
<Step title="حدد معرف المهمة ومعاملات الإدخال لعملية إعادة التشغيل.">
|
||||
حدد `task_id` ومعاملات الإدخال لعملية إعادة التشغيل.
|
||||
</Step>
|
||||
<Step title="نفّذ أمر إعادة التشغيل ضمن كتلة try-except للتعامل مع الأخطاء المحتملة.">
|
||||
نفّذ أمر إعادة التشغيل ضمن كتلة try-except للتعامل مع الأخطاء المحتملة.
|
||||
<CodeGroup>
|
||||
```python Code
|
||||
def replay():
|
||||
"""
|
||||
Replay the crew execution from a specific task.
|
||||
"""
|
||||
task_id = '<task_id>'
|
||||
inputs = {"topic": "CrewAI Training"} # This is optional; you can pass in the inputs you want to replay; otherwise, it uses the previous kickoff's inputs.
|
||||
try:
|
||||
YourCrewName_Crew().crew().replay(task_id=task_id, inputs=inputs)
|
||||
|
||||
except subprocess.CalledProcessError as e:
|
||||
raise Exception(f"An error occurred while replaying the crew: {e}")
|
||||
|
||||
except Exception as e:
|
||||
raise Exception(f"An unexpected error occurred: {e}")
|
||||
```
|
||||
</CodeGroup>
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## الخاتمة
|
||||
|
||||
مع التحسينات المذكورة أعلاه والوظائف المفصلة، أصبحت إعادة تشغيل مهام محددة في CrewAI أكثر كفاءة ومتانة.
|
||||
تأكد من اتباع الأوامر والخطوات بدقة لتحقيق أقصى استفادة من هذه الميزات.
|
||||
128
docs/ar/learn/sequential-process.mdx
Normal file
128
docs/ar/learn/sequential-process.mdx
Normal file
@@ -0,0 +1,128 @@
|
||||
---
|
||||
title: العمليات التسلسلية
|
||||
description: دليل شامل لاستخدام العمليات التسلسلية لتنفيذ المهام في مشاريع CrewAI.
|
||||
icon: forward
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## مقدمة
|
||||
|
||||
يقدم CrewAI إطار عمل مرن لتنفيذ المهام بطريقة منظمة، يدعم كلاً من العمليات التسلسلية والهرمية.
|
||||
يوضح هذا الدليل كيفية تنفيذ هذه العمليات بفعالية لضمان تنفيذ المهام بكفاءة وإكمال المشروع.
|
||||
|
||||
## نظرة عامة على العملية التسلسلية
|
||||
|
||||
تضمن العملية التسلسلية تنفيذ المهام واحدة تلو الأخرى، باتباع تقدم خطي.
|
||||
هذا النهج مثالي للمشاريع التي تتطلب إكمال المهام بترتيب محدد.
|
||||
|
||||
### الميزات الرئيسية
|
||||
|
||||
- **تدفق مهام خطي**: يضمن تقدماً منظماً من خلال التعامل مع المهام بتسلسل محدد مسبقاً.
|
||||
- **البساطة**: الأنسب للمشاريع ذات المهام الواضحة خطوة بخطوة.
|
||||
- **سهولة المراقبة**: يسهل التتبع السهل لإكمال المهام وتقدم المشروع.
|
||||
|
||||
## تنفيذ العملية التسلسلية
|
||||
|
||||
لاستخدام العملية التسلسلية، قم بتجميع طاقمك وتعريف المهام بالترتيب الذي تحتاج إلى تنفيذها به.
|
||||
|
||||
```python Code
|
||||
from crewai import Crew, Process, Agent, Task, TaskOutput, CrewOutput
|
||||
|
||||
# Define your agents
|
||||
researcher = Agent(
|
||||
role='Researcher',
|
||||
goal='Conduct foundational research',
|
||||
backstory='An experienced researcher with a passion for uncovering insights'
|
||||
)
|
||||
analyst = Agent(
|
||||
role='Data Analyst',
|
||||
goal='Analyze research findings',
|
||||
backstory='A meticulous analyst with a knack for uncovering patterns'
|
||||
)
|
||||
writer = Agent(
|
||||
role='Writer',
|
||||
goal='Draft the final report',
|
||||
backstory='A skilled writer with a talent for crafting compelling narratives'
|
||||
)
|
||||
|
||||
# Define your tasks
|
||||
research_task = Task(
|
||||
description='Gather relevant data...',
|
||||
agent=researcher,
|
||||
expected_output='Raw Data'
|
||||
)
|
||||
analysis_task = Task(
|
||||
description='Analyze the data...',
|
||||
agent=analyst,
|
||||
expected_output='Data Insights'
|
||||
)
|
||||
writing_task = Task(
|
||||
description='Compose the report...',
|
||||
agent=writer,
|
||||
expected_output='Final Report'
|
||||
)
|
||||
|
||||
# Form the crew with a sequential process
|
||||
report_crew = Crew(
|
||||
agents=[researcher, analyst, writer],
|
||||
tasks=[research_task, analysis_task, writing_task],
|
||||
process=Process.sequential
|
||||
)
|
||||
|
||||
# Execute the crew
|
||||
result = report_crew.kickoff()
|
||||
|
||||
# Accessing the type-safe output
|
||||
task_output: TaskOutput = result.tasks[0].output
|
||||
crew_output: CrewOutput = result.output
|
||||
```
|
||||
|
||||
### ملاحظة:
|
||||
|
||||
يجب أن يكون لكل مهمة في عملية تسلسلية وكيل مُعيّن. تأكد من أن كل `Task` تتضمن معامل `agent`.
|
||||
|
||||
### سير العمل أثناء التنفيذ
|
||||
|
||||
1. **المهمة الأولى**: في العملية التسلسلية، يكمل الوكيل الأول مهمته ويشير إلى الإكمال.
|
||||
2. **المهام اللاحقة**: يلتقط الوكلاء مهامهم بناءً على نوع العملية، مع نتائج المهام السابقة أو التوجيهات التي تقود تنفيذهم.
|
||||
3. **الإكمال**: تنتهي العملية بمجرد تنفيذ المهمة النهائية، مما يؤدي إلى إكمال المشروع.
|
||||
|
||||
## الميزات المتقدمة
|
||||
|
||||
### تفويض المهام
|
||||
|
||||
في العمليات التسلسلية، إذا كان الوكيل لديه `allow_delegation` مُعيّن إلى `True`، يمكنه تفويض المهام إلى وكلاء آخرين في الطاقم.
|
||||
يتم إعداد هذه الميزة تلقائياً عندما يكون هناك عدة وكلاء في الطاقم.
|
||||
|
||||
### التنفيذ غير المتزامن
|
||||
|
||||
يمكن تنفيذ المهام بشكل غير متزامن، مما يسمح بالمعالجة المتوازية عند الاقتضاء.
|
||||
لإنشاء مهمة غير متزامنة، عيّن `async_execution=True` عند تعريف المهمة.
|
||||
|
||||
### الذاكرة والتخزين المؤقت
|
||||
|
||||
يدعم CrewAI كلاً من ميزتي الذاكرة والتخزين المؤقت:
|
||||
|
||||
- **الذاكرة**: فعّلها بتعيين `memory=True` عند إنشاء الطاقم. يتيح هذا للوكلاء الاحتفاظ بالمعلومات عبر المهام.
|
||||
- **التخزين المؤقت**: افتراضياً، التخزين المؤقت مفعّل. عيّن `cache=False` لتعطيله.
|
||||
|
||||
### دوال الاستدعاء الراجع
|
||||
|
||||
يمكنك تعيين دوال استدعاء راجع على مستوى المهمة والخطوة:
|
||||
|
||||
- `task_callback`: يُنفذ بعد إكمال كل مهمة.
|
||||
- `step_callback`: يُنفذ بعد كل خطوة في تنفيذ الوكيل.
|
||||
|
||||
### مقاييس الاستخدام
|
||||
|
||||
يتتبع CrewAI استخدام الرموز عبر جميع المهام والوكلاء. يمكنك الوصول إلى هذه المقاييس بعد التنفيذ.
|
||||
|
||||
## أفضل الممارسات للعمليات التسلسلية
|
||||
|
||||
1. **الترتيب مهم**: رتّب المهام بتسلسل منطقي حيث تبني كل مهمة على سابقتها.
|
||||
2. **أوصاف مهام واضحة**: قدم أوصافاً مفصلة لكل مهمة لتوجيه الوكلاء بفعالية.
|
||||
3. **اختيار الوكيل المناسب**: طابق مهارات وأدوار الوكلاء مع متطلبات كل مهمة.
|
||||
4. **استخدم السياق**: استفد من سياق المهام السابقة لإبلاغ المهام اللاحقة.
|
||||
|
||||
يضمن هذا التوثيق المحدث أن التفاصيل تعكس بدقة أحدث التغييرات في قاعدة الكود وتصف بوضوح كيفية الاستفادة من الميزات والإعدادات الجديدة.
|
||||
تم الحفاظ على بساطة المحتوى ومباشرته لضمان سهولة الفهم.
|
||||
356
docs/ar/learn/streaming-crew-execution.mdx
Normal file
356
docs/ar/learn/streaming-crew-execution.mdx
Normal file
@@ -0,0 +1,356 @@
|
||||
---
|
||||
title: بث تنفيذ الطاقم
|
||||
description: بث المخرجات في الوقت الفعلي من تنفيذ طاقم CrewAI الخاص بك
|
||||
icon: wave-pulse
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## مقدمة
|
||||
|
||||
يوفر CrewAI القدرة على بث المخرجات في الوقت الفعلي أثناء تنفيذ الطاقم، مما يتيح لك عرض النتائج فور توليدها بدلاً من انتظار اكتمال العملية بالكامل. هذه الميزة مفيدة بشكل خاص لبناء التطبيقات التفاعلية وتقديم تغذية راجعة للمستخدم ومراقبة العمليات طويلة التشغيل.
|
||||
|
||||
## كيف يعمل البث
|
||||
|
||||
عند تفعيل البث، يلتقط CrewAI استجابات LLM واستدعاءات الأدوات فور حدوثها، ويحزمها في أجزاء منظمة تتضمن سياقاً حول المهمة والوكيل المنفذ. يمكنك التكرار على هذه الأجزاء في الوقت الفعلي والوصول إلى النتيجة النهائية بمجرد اكتمال التنفيذ.
|
||||
|
||||
## تفعيل البث
|
||||
|
||||
لتفعيل البث، عيّن معامل `stream` إلى `True` عند إنشاء طاقمك:
|
||||
|
||||
```python Code
|
||||
from crewai import Agent, Crew, Task
|
||||
|
||||
# Create your agents and tasks
|
||||
researcher = Agent(
|
||||
role="Research Analyst",
|
||||
goal="Gather comprehensive information on topics",
|
||||
backstory="You are an experienced researcher with excellent analytical skills.",
|
||||
)
|
||||
|
||||
task = Task(
|
||||
description="Research the latest developments in AI",
|
||||
expected_output="A detailed report on recent AI advancements",
|
||||
agent=researcher,
|
||||
)
|
||||
|
||||
# Enable streaming
|
||||
crew = Crew(
|
||||
agents=[researcher],
|
||||
tasks=[task],
|
||||
stream=True # Enable streaming output
|
||||
)
|
||||
```
|
||||
|
||||
## البث المتزامن
|
||||
|
||||
عند استدعاء `kickoff()` على طاقم مع تفعيل البث، يُرجع كائن `CrewStreamingOutput` يمكنك التكرار عليه لاستلام الأجزاء فور وصولها:
|
||||
|
||||
```python Code
|
||||
# Start streaming execution
|
||||
streaming = crew.kickoff(inputs={"topic": "artificial intelligence"})
|
||||
|
||||
# Iterate over chunks as they arrive
|
||||
for chunk in streaming:
|
||||
print(chunk.content, end="", flush=True)
|
||||
|
||||
# Access the final result after streaming completes
|
||||
result = streaming.result
|
||||
print(f"\n\nFinal output: {result.raw}")
|
||||
```
|
||||
|
||||
### معلومات جزء البث
|
||||
|
||||
يوفر كل جزء سياقاً غنياً حول التنفيذ:
|
||||
|
||||
```python Code
|
||||
streaming = crew.kickoff(inputs={"topic": "AI"})
|
||||
|
||||
for chunk in streaming:
|
||||
print(f"Task: {chunk.task_name} (index {chunk.task_index})")
|
||||
print(f"Agent: {chunk.agent_role}")
|
||||
print(f"Content: {chunk.content}")
|
||||
print(f"Type: {chunk.chunk_type}") # TEXT or TOOL_CALL
|
||||
if chunk.tool_call:
|
||||
print(f"Tool: {chunk.tool_call.tool_name}")
|
||||
print(f"Arguments: {chunk.tool_call.arguments}")
|
||||
```
|
||||
|
||||
### الوصول إلى نتائج البث
|
||||
|
||||
يوفر كائن `CrewStreamingOutput` عدة خصائص مفيدة:
|
||||
|
||||
```python Code
|
||||
streaming = crew.kickoff(inputs={"topic": "AI"})
|
||||
|
||||
# Iterate and collect chunks
|
||||
for chunk in streaming:
|
||||
print(chunk.content, end="", flush=True)
|
||||
|
||||
# After iteration completes
|
||||
print(f"\nCompleted: {streaming.is_completed}")
|
||||
print(f"Full text: {streaming.get_full_text()}")
|
||||
print(f"All chunks: {len(streaming.chunks)}")
|
||||
print(f"Final result: {streaming.result.raw}")
|
||||
```
|
||||
|
||||
## البث غير المتزامن
|
||||
|
||||
للتطبيقات غير المتزامنة، يمكنك استخدام إما `akickoff()` (async أصلي) أو `kickoff_async()` (قائم على الخيوط) مع التكرار غير المتزامن:
|
||||
|
||||
### async أصلي مع `akickoff()`
|
||||
|
||||
توفر طريقة `akickoff()` تنفيذاً غير متزامن أصلياً حقيقياً عبر السلسلة بالكامل:
|
||||
|
||||
```python Code
|
||||
import asyncio
|
||||
|
||||
async def stream_crew():
|
||||
crew = Crew(
|
||||
agents=[researcher],
|
||||
tasks=[task],
|
||||
stream=True
|
||||
)
|
||||
|
||||
# Start native async streaming
|
||||
streaming = await crew.akickoff(inputs={"topic": "AI"})
|
||||
|
||||
# Async iteration over chunks
|
||||
async for chunk in streaming:
|
||||
print(chunk.content, end="", flush=True)
|
||||
|
||||
# Access final result
|
||||
result = streaming.result
|
||||
print(f"\n\nFinal output: {result.raw}")
|
||||
|
||||
asyncio.run(stream_crew())
|
||||
```
|
||||
|
||||
### async قائم على الخيوط مع `kickoff_async()`
|
||||
|
||||
للتكامل البسيط مع async أو التوافق مع الإصدارات السابقة:
|
||||
|
||||
```python Code
|
||||
import asyncio
|
||||
|
||||
async def stream_crew():
|
||||
crew = Crew(
|
||||
agents=[researcher],
|
||||
tasks=[task],
|
||||
stream=True
|
||||
)
|
||||
|
||||
# Start thread-based async streaming
|
||||
streaming = await crew.kickoff_async(inputs={"topic": "AI"})
|
||||
|
||||
# Async iteration over chunks
|
||||
async for chunk in streaming:
|
||||
print(chunk.content, end="", flush=True)
|
||||
|
||||
# Access final result
|
||||
result = streaming.result
|
||||
print(f"\n\nFinal output: {result.raw}")
|
||||
|
||||
asyncio.run(stream_crew())
|
||||
```
|
||||
|
||||
<Note>
|
||||
لأحمال العمل عالية التزامن، يُوصى باستخدام `akickoff()` لأنه يستخدم async أصلي لتنفيذ المهام وعمليات الذاكرة واسترجاع المعرفة. راجع دليل [تشغيل الطاقم بشكل غير متزامن](/ar/learn/kickoff-async) لمزيد من التفاصيل.
|
||||
</Note>
|
||||
|
||||
## البث مع kickoff_for_each
|
||||
|
||||
عند تنفيذ طاقم لمدخلات متعددة مع `kickoff_for_each()`، يعمل البث بشكل مختلف حسب ما إذا كنت تستخدم المتزامن أو غير المتزامن:
|
||||
|
||||
### kickoff_for_each المتزامن
|
||||
|
||||
مع `kickoff_for_each()` المتزامن، تحصل على قائمة كائنات `CrewStreamingOutput`، واحد لكل مدخل:
|
||||
|
||||
```python Code
|
||||
crew = Crew(
|
||||
agents=[researcher],
|
||||
tasks=[task],
|
||||
stream=True
|
||||
)
|
||||
|
||||
inputs_list = [
|
||||
{"topic": "AI in healthcare"},
|
||||
{"topic": "AI in finance"}
|
||||
]
|
||||
|
||||
# Returns list of streaming outputs
|
||||
streaming_outputs = crew.kickoff_for_each(inputs=inputs_list)
|
||||
|
||||
# Iterate over each streaming output
|
||||
for i, streaming in enumerate(streaming_outputs):
|
||||
print(f"\n=== Input {i + 1} ===")
|
||||
for chunk in streaming:
|
||||
print(chunk.content, end="", flush=True)
|
||||
|
||||
result = streaming.result
|
||||
print(f"\n\nResult {i + 1}: {result.raw}")
|
||||
```
|
||||
|
||||
### kickoff_for_each_async غير المتزامن
|
||||
|
||||
مع `kickoff_for_each_async()` غير المتزامن، تحصل على `CrewStreamingOutput` واحد يُخرج أجزاء من جميع الأطقم فور وصولها بشكل متزامن:
|
||||
|
||||
```python Code
|
||||
import asyncio
|
||||
|
||||
async def stream_multiple_crews():
|
||||
crew = Crew(
|
||||
agents=[researcher],
|
||||
tasks=[task],
|
||||
stream=True
|
||||
)
|
||||
|
||||
inputs_list = [
|
||||
{"topic": "AI in healthcare"},
|
||||
{"topic": "AI in finance"}
|
||||
]
|
||||
|
||||
# Returns single streaming output for all crews
|
||||
streaming = await crew.kickoff_for_each_async(inputs=inputs_list)
|
||||
|
||||
# Chunks from all crews arrive as they're generated
|
||||
async for chunk in streaming:
|
||||
print(f"[{chunk.task_name}] {chunk.content}", end="", flush=True)
|
||||
|
||||
# Access all results
|
||||
results = streaming.results # List of CrewOutput objects
|
||||
for i, result in enumerate(results):
|
||||
print(f"\n\nResult {i + 1}: {result.raw}")
|
||||
|
||||
asyncio.run(stream_multiple_crews())
|
||||
```
|
||||
|
||||
## أنواع أجزاء البث
|
||||
|
||||
يمكن أن تكون الأجزاء من أنواع مختلفة، يُشار إليها بحقل `chunk_type`:
|
||||
|
||||
### أجزاء TEXT
|
||||
|
||||
محتوى نصي قياسي من استجابات LLM:
|
||||
|
||||
```python Code
|
||||
for chunk in streaming:
|
||||
if chunk.chunk_type == StreamChunkType.TEXT:
|
||||
print(chunk.content, end="", flush=True)
|
||||
```
|
||||
|
||||
### أجزاء TOOL_CALL
|
||||
|
||||
معلومات حول استدعاءات الأدوات الجارية:
|
||||
|
||||
```python Code
|
||||
for chunk in streaming:
|
||||
if chunk.chunk_type == StreamChunkType.TOOL_CALL:
|
||||
print(f"\nCalling tool: {chunk.tool_call.tool_name}")
|
||||
print(f"Arguments: {chunk.tool_call.arguments}")
|
||||
```
|
||||
|
||||
## مثال عملي: بناء واجهة مستخدم مع البث
|
||||
|
||||
إليك مثالاً كاملاً يوضح كيفية بناء تطبيق تفاعلي مع البث:
|
||||
|
||||
```python Code
|
||||
import asyncio
|
||||
from crewai import Agent, Crew, Task
|
||||
from crewai.types.streaming import StreamChunkType
|
||||
|
||||
async def interactive_research():
|
||||
# Create crew with streaming enabled
|
||||
researcher = Agent(
|
||||
role="Research Analyst",
|
||||
goal="Provide detailed analysis on any topic",
|
||||
backstory="You are an expert researcher with broad knowledge.",
|
||||
)
|
||||
|
||||
task = Task(
|
||||
description="Research and analyze: {topic}",
|
||||
expected_output="A comprehensive analysis with key insights",
|
||||
agent=researcher,
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[researcher],
|
||||
tasks=[task],
|
||||
stream=True,
|
||||
verbose=False
|
||||
)
|
||||
|
||||
# Get user input
|
||||
topic = input("Enter a topic to research: ")
|
||||
|
||||
print(f"\n{'='*60}")
|
||||
print(f"Researching: {topic}")
|
||||
print(f"{'='*60}\n")
|
||||
|
||||
# Start streaming execution
|
||||
streaming = await crew.kickoff_async(inputs={"topic": topic})
|
||||
|
||||
current_task = ""
|
||||
async for chunk in streaming:
|
||||
# Show task transitions
|
||||
if chunk.task_name != current_task:
|
||||
current_task = chunk.task_name
|
||||
print(f"\n[{chunk.agent_role}] Working on: {chunk.task_name}")
|
||||
print("-" * 60)
|
||||
|
||||
# Display text chunks
|
||||
if chunk.chunk_type == StreamChunkType.TEXT:
|
||||
print(chunk.content, end="", flush=True)
|
||||
|
||||
# Display tool calls
|
||||
elif chunk.chunk_type == StreamChunkType.TOOL_CALL and chunk.tool_call:
|
||||
print(f"\n🔧 Using tool: {chunk.tool_call.tool_name}")
|
||||
|
||||
# Show final result
|
||||
result = streaming.result
|
||||
print(f"\n\n{'='*60}")
|
||||
print("Analysis Complete!")
|
||||
print(f"{'='*60}")
|
||||
print(f"\nToken Usage: {result.token_usage}")
|
||||
|
||||
asyncio.run(interactive_research())
|
||||
```
|
||||
|
||||
## حالات الاستخدام
|
||||
|
||||
البث ذو قيمة خاصة لـ:
|
||||
|
||||
- **التطبيقات التفاعلية**: تقديم تغذية راجعة فورية للمستخدمين أثناء عمل الوكلاء
|
||||
- **المهام طويلة التشغيل**: عرض التقدم للبحث والتحليل أو توليد المحتوى
|
||||
- **التصحيح والمراقبة**: مراقبة سلوك الوكلاء واتخاذ القرارات في الوقت الفعلي
|
||||
- **تجربة المستخدم**: تقليل زمن الاستجابة المتصور بعرض نتائج تدريجية
|
||||
- **لوحات المعلومات الحية**: بناء واجهات مراقبة تعرض حالة تنفيذ الطاقم
|
||||
|
||||
## ملاحظات مهمة
|
||||
|
||||
- يفعّل البث تلقائياً بث LLM لجميع الوكلاء في الطاقم
|
||||
- يجب التكرار عبر جميع الأجزاء قبل الوصول إلى خاصية `.result`
|
||||
- لـ `kickoff_for_each_async()` مع البث، استخدم `.results` (بصيغة الجمع) للحصول على جميع المخرجات
|
||||
- يضيف البث حملاً ضئيلاً ويمكن أن يحسن الأداء المتصور فعلياً
|
||||
- يتضمن كل جزء سياقاً كاملاً (المهمة، الوكيل، نوع الجزء) لواجهات مستخدم غنية
|
||||
|
||||
## معالجة الأخطاء
|
||||
|
||||
التعامل مع الأخطاء أثناء تنفيذ البث:
|
||||
|
||||
```python Code
|
||||
streaming = crew.kickoff(inputs={"topic": "AI"})
|
||||
|
||||
try:
|
||||
for chunk in streaming:
|
||||
print(chunk.content, end="", flush=True)
|
||||
|
||||
result = streaming.result
|
||||
print(f"\nSuccess: {result.raw}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"\nError during streaming: {e}")
|
||||
if streaming.is_completed:
|
||||
print("Streaming completed but an error occurred")
|
||||
```
|
||||
|
||||
من خلال الاستفادة من البث، يمكنك بناء تطبيقات أكثر استجابة وتفاعلية مع CrewAI، مما يوفر للمستخدمين رؤية فورية لتنفيذ الوكلاء والنتائج.
|
||||
450
docs/ar/learn/streaming-flow-execution.mdx
Normal file
450
docs/ar/learn/streaming-flow-execution.mdx
Normal file
@@ -0,0 +1,450 @@
|
||||
---
|
||||
title: بث تنفيذ التدفق
|
||||
description: بث المخرجات في الوقت الفعلي من تنفيذ تدفق CrewAI الخاص بك
|
||||
icon: wave-pulse
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
## مقدمة
|
||||
|
||||
تدعم تدفقات CrewAI بث المخرجات، مما يتيح لك استلام تحديثات فورية أثناء تنفيذ تدفقك. تمكّنك هذه الميزة من بناء تطبيقات متجاوبة تعرض النتائج تدريجياً وتوفر تحديثات تقدم حية وتخلق تجربة مستخدم أفضل لسير العمل طويلة التشغيل.
|
||||
|
||||
## كيف يعمل بث التدفق
|
||||
|
||||
عند تفعيل البث في تدفق، يلتقط CrewAI ويبث المخرجات من أي أطقم أو استدعاءات LLM داخل التدفق. يقدم البث أجزاء منظمة تحتوي على المحتوى وسياق المهمة ومعلومات الوكيل مع تقدم التنفيذ.
|
||||
|
||||
## تفعيل البث
|
||||
|
||||
لتفعيل البث، عيّن خاصية `stream` إلى `True` في فئة التدفق الخاصة بك:
|
||||
|
||||
```python Code
|
||||
from crewai.flow.flow import Flow, listen, start
|
||||
from crewai import Agent, Crew, Task
|
||||
|
||||
class ResearchFlow(Flow):
|
||||
stream = True # Enable streaming for the entire flow
|
||||
|
||||
@start()
|
||||
def initialize(self):
|
||||
return {"topic": "AI trends"}
|
||||
|
||||
@listen(initialize)
|
||||
def research_topic(self, data):
|
||||
researcher = Agent(
|
||||
role="Research Analyst",
|
||||
goal="Research topics thoroughly",
|
||||
backstory="Expert researcher with analytical skills",
|
||||
)
|
||||
|
||||
task = Task(
|
||||
description="Research {topic} and provide insights",
|
||||
expected_output="Detailed research findings",
|
||||
agent=researcher,
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[researcher],
|
||||
tasks=[task],
|
||||
)
|
||||
|
||||
return crew.kickoff(inputs=data)
|
||||
```
|
||||
|
||||
## البث المتزامن
|
||||
|
||||
عند استدعاء `kickoff()` على تدفق مع تفعيل البث، يُرجع كائن `FlowStreamingOutput` يمكنك التكرار عليه:
|
||||
|
||||
```python Code
|
||||
flow = ResearchFlow()
|
||||
|
||||
# Start streaming execution
|
||||
streaming = flow.kickoff()
|
||||
|
||||
# Iterate over chunks as they arrive
|
||||
for chunk in streaming:
|
||||
print(chunk.content, end="", flush=True)
|
||||
|
||||
# Access the final result after streaming completes
|
||||
result = streaming.result
|
||||
print(f"\n\nFinal output: {result}")
|
||||
```
|
||||
|
||||
### معلومات جزء البث
|
||||
|
||||
يوفر كل جزء سياقاً حول مصدره في التدفق:
|
||||
|
||||
```python Code
|
||||
streaming = flow.kickoff()
|
||||
|
||||
for chunk in streaming:
|
||||
print(f"Agent: {chunk.agent_role}")
|
||||
print(f"Task: {chunk.task_name}")
|
||||
print(f"Content: {chunk.content}")
|
||||
print(f"Type: {chunk.chunk_type}") # TEXT or TOOL_CALL
|
||||
```
|
||||
|
||||
### الوصول إلى خصائص البث
|
||||
|
||||
يوفر كائن `FlowStreamingOutput` خصائص وطرق مفيدة:
|
||||
|
||||
```python Code
|
||||
streaming = flow.kickoff()
|
||||
|
||||
# Iterate and collect chunks
|
||||
for chunk in streaming:
|
||||
print(chunk.content, end="", flush=True)
|
||||
|
||||
# After iteration completes
|
||||
print(f"\nCompleted: {streaming.is_completed}")
|
||||
print(f"Full text: {streaming.get_full_text()}")
|
||||
print(f"Total chunks: {len(streaming.chunks)}")
|
||||
print(f"Final result: {streaming.result}")
|
||||
```
|
||||
|
||||
## البث غير المتزامن
|
||||
|
||||
للتطبيقات غير المتزامنة، استخدم `kickoff_async()` مع التكرار غير المتزامن:
|
||||
|
||||
```python Code
|
||||
import asyncio
|
||||
|
||||
async def stream_flow():
|
||||
flow = ResearchFlow()
|
||||
|
||||
# Start async streaming
|
||||
streaming = await flow.kickoff_async()
|
||||
|
||||
# Async iteration over chunks
|
||||
async for chunk in streaming:
|
||||
print(chunk.content, end="", flush=True)
|
||||
|
||||
# Access final result
|
||||
result = streaming.result
|
||||
print(f"\n\nFinal output: {result}")
|
||||
|
||||
asyncio.run(stream_flow())
|
||||
```
|
||||
|
||||
## البث مع التدفقات متعددة الخطوات
|
||||
|
||||
يعمل البث بسلاسة عبر خطوات تدفق متعددة، بما في ذلك التدفقات التي تنفذ أطقم متعددة:
|
||||
|
||||
```python Code
|
||||
from crewai.flow.flow import Flow, listen, start
|
||||
from crewai import Agent, Crew, Task
|
||||
|
||||
class MultiStepFlow(Flow):
|
||||
stream = True
|
||||
|
||||
@start()
|
||||
def research_phase(self):
|
||||
"""First crew: Research the topic."""
|
||||
researcher = Agent(
|
||||
role="Research Analyst",
|
||||
goal="Gather comprehensive information",
|
||||
backstory="Expert at finding relevant information",
|
||||
)
|
||||
|
||||
task = Task(
|
||||
description="Research AI developments in healthcare",
|
||||
expected_output="Research findings on AI in healthcare",
|
||||
agent=researcher,
|
||||
)
|
||||
|
||||
crew = Crew(agents=[researcher], tasks=[task])
|
||||
result = crew.kickoff()
|
||||
|
||||
self.state["research"] = result.raw
|
||||
return result.raw
|
||||
|
||||
@listen(research_phase)
|
||||
def analysis_phase(self, research_data):
|
||||
"""Second crew: Analyze the research."""
|
||||
analyst = Agent(
|
||||
role="Data Analyst",
|
||||
goal="Analyze information and extract insights",
|
||||
backstory="Expert at identifying patterns and trends",
|
||||
)
|
||||
|
||||
task = Task(
|
||||
description="Analyze this research: {research}",
|
||||
expected_output="Key insights and trends",
|
||||
agent=analyst,
|
||||
)
|
||||
|
||||
crew = Crew(agents=[analyst], tasks=[task])
|
||||
return crew.kickoff(inputs={"research": research_data})
|
||||
|
||||
|
||||
# Stream across both phases
|
||||
flow = MultiStepFlow()
|
||||
streaming = flow.kickoff()
|
||||
|
||||
current_step = ""
|
||||
for chunk in streaming:
|
||||
# Track which flow step is executing
|
||||
if chunk.task_name != current_step:
|
||||
current_step = chunk.task_name
|
||||
print(f"\n\n=== {chunk.task_name} ===\n")
|
||||
|
||||
print(chunk.content, end="", flush=True)
|
||||
|
||||
result = streaming.result
|
||||
print(f"\n\nFinal analysis: {result}")
|
||||
```
|
||||
|
||||
## مثال عملي: لوحة معلومات التقدم
|
||||
|
||||
إليك مثالاً كاملاً يوضح كيفية بناء لوحة معلومات تقدم مع البث:
|
||||
|
||||
```python Code
|
||||
import asyncio
|
||||
from crewai.flow.flow import Flow, listen, start
|
||||
from crewai import Agent, Crew, Task
|
||||
from crewai.types.streaming import StreamChunkType
|
||||
|
||||
class ResearchPipeline(Flow):
|
||||
stream = True
|
||||
|
||||
@start()
|
||||
def gather_data(self):
|
||||
researcher = Agent(
|
||||
role="Data Gatherer",
|
||||
goal="Collect relevant information",
|
||||
backstory="Skilled at finding quality sources",
|
||||
)
|
||||
|
||||
task = Task(
|
||||
description="Gather data on renewable energy trends",
|
||||
expected_output="Collection of relevant data points",
|
||||
agent=researcher,
|
||||
)
|
||||
|
||||
crew = Crew(agents=[researcher], tasks=[task])
|
||||
result = crew.kickoff()
|
||||
self.state["data"] = result.raw
|
||||
return result.raw
|
||||
|
||||
@listen(gather_data)
|
||||
def analyze_data(self, data):
|
||||
analyst = Agent(
|
||||
role="Data Analyst",
|
||||
goal="Extract meaningful insights",
|
||||
backstory="Expert at data analysis",
|
||||
)
|
||||
|
||||
task = Task(
|
||||
description="Analyze: {data}",
|
||||
expected_output="Key insights and trends",
|
||||
agent=analyst,
|
||||
)
|
||||
|
||||
crew = Crew(agents=[analyst], tasks=[task])
|
||||
return crew.kickoff(inputs={"data": data})
|
||||
|
||||
|
||||
async def run_with_dashboard():
|
||||
flow = ResearchPipeline()
|
||||
|
||||
print("="*60)
|
||||
print("RESEARCH PIPELINE DASHBOARD")
|
||||
print("="*60)
|
||||
|
||||
streaming = await flow.kickoff_async()
|
||||
|
||||
current_agent = ""
|
||||
current_task = ""
|
||||
chunk_count = 0
|
||||
|
||||
async for chunk in streaming:
|
||||
chunk_count += 1
|
||||
|
||||
# Display phase transitions
|
||||
if chunk.task_name != current_task:
|
||||
current_task = chunk.task_name
|
||||
current_agent = chunk.agent_role
|
||||
print(f"\n\n📋 Phase: {current_task}")
|
||||
print(f"👤 Agent: {current_agent}")
|
||||
print("-" * 60)
|
||||
|
||||
# Display text output
|
||||
if chunk.chunk_type == StreamChunkType.TEXT:
|
||||
print(chunk.content, end="", flush=True)
|
||||
|
||||
# Display tool usage
|
||||
elif chunk.chunk_type == StreamChunkType.TOOL_CALL and chunk.tool_call:
|
||||
print(f"\n🔧 Tool: {chunk.tool_call.tool_name}")
|
||||
|
||||
# Show completion summary
|
||||
result = streaming.result
|
||||
print(f"\n\n{'='*60}")
|
||||
print("PIPELINE COMPLETE")
|
||||
print(f"{'='*60}")
|
||||
print(f"Total chunks: {chunk_count}")
|
||||
print(f"Final output length: {len(str(result))} characters")
|
||||
|
||||
asyncio.run(run_with_dashboard())
|
||||
```
|
||||
|
||||
## البث مع إدارة الحالة
|
||||
|
||||
يعمل البث بشكل طبيعي مع إدارة حالة التدفق:
|
||||
|
||||
```python Code
|
||||
from pydantic import BaseModel
|
||||
|
||||
class AnalysisState(BaseModel):
|
||||
topic: str = ""
|
||||
research: str = ""
|
||||
insights: str = ""
|
||||
|
||||
class StatefulStreamingFlow(Flow[AnalysisState]):
|
||||
stream = True
|
||||
|
||||
@start()
|
||||
def research(self):
|
||||
# State is available during streaming
|
||||
topic = self.state.topic
|
||||
print(f"Researching: {topic}")
|
||||
|
||||
researcher = Agent(
|
||||
role="Researcher",
|
||||
goal="Research topics thoroughly",
|
||||
backstory="Expert researcher",
|
||||
)
|
||||
|
||||
task = Task(
|
||||
description=f"Research {topic}",
|
||||
expected_output="Research findings",
|
||||
agent=researcher,
|
||||
)
|
||||
|
||||
crew = Crew(agents=[researcher], tasks=[task])
|
||||
result = crew.kickoff()
|
||||
|
||||
self.state.research = result.raw
|
||||
return result.raw
|
||||
|
||||
@listen(research)
|
||||
def analyze(self, research):
|
||||
# Access updated state
|
||||
print(f"Analyzing {len(self.state.research)} chars of research")
|
||||
|
||||
analyst = Agent(
|
||||
role="Analyst",
|
||||
goal="Extract insights",
|
||||
backstory="Expert analyst",
|
||||
)
|
||||
|
||||
task = Task(
|
||||
description="Analyze: {research}",
|
||||
expected_output="Key insights",
|
||||
agent=analyst,
|
||||
)
|
||||
|
||||
crew = Crew(agents=[analyst], tasks=[task])
|
||||
result = crew.kickoff(inputs={"research": research})
|
||||
|
||||
self.state.insights = result.raw
|
||||
return result.raw
|
||||
|
||||
|
||||
# Run with streaming
|
||||
flow = StatefulStreamingFlow()
|
||||
streaming = flow.kickoff(inputs={"topic": "quantum computing"})
|
||||
|
||||
for chunk in streaming:
|
||||
print(chunk.content, end="", flush=True)
|
||||
|
||||
result = streaming.result
|
||||
print(f"\n\nFinal state:")
|
||||
print(f"Topic: {flow.state.topic}")
|
||||
print(f"Research length: {len(flow.state.research)}")
|
||||
print(f"Insights length: {len(flow.state.insights)}")
|
||||
```
|
||||
|
||||
## حالات الاستخدام
|
||||
|
||||
بث التدفق ذو قيمة خاصة لـ:
|
||||
|
||||
- **سير العمل متعددة المراحل**: عرض التقدم عبر مراحل البحث والتحليل والتوليف
|
||||
- **خطوط الأنابيب المعقدة**: توفير رؤية لتدفقات معالجة البيانات طويلة التشغيل
|
||||
- **التطبيقات التفاعلية**: بناء واجهات مستخدم متجاوبة تعرض النتائج الوسيطة
|
||||
- **المراقبة والتصحيح**: مراقبة تنفيذ التدفق وتفاعلات الأطقم في الوقت الفعلي
|
||||
- **تتبع التقدم**: إظهار المرحلة الحالية من سير العمل للمستخدمين
|
||||
- **لوحات المعلومات الحية**: إنشاء واجهات مراقبة لتدفقات الإنتاج
|
||||
|
||||
## أنواع أجزاء البث
|
||||
|
||||
مثل بث الطاقم، يمكن أن تكون أجزاء التدفق من أنواع مختلفة:
|
||||
|
||||
### أجزاء TEXT
|
||||
|
||||
محتوى نصي قياسي من استجابات LLM:
|
||||
|
||||
```python Code
|
||||
for chunk in streaming:
|
||||
if chunk.chunk_type == StreamChunkType.TEXT:
|
||||
print(chunk.content, end="", flush=True)
|
||||
```
|
||||
|
||||
### أجزاء TOOL_CALL
|
||||
|
||||
معلومات حول استدعاءات الأدوات داخل التدفق:
|
||||
|
||||
```python Code
|
||||
for chunk in streaming:
|
||||
if chunk.chunk_type == StreamChunkType.TOOL_CALL and chunk.tool_call:
|
||||
print(f"\nTool: {chunk.tool_call.tool_name}")
|
||||
print(f"Args: {chunk.tool_call.arguments}")
|
||||
```
|
||||
|
||||
## معالجة الأخطاء
|
||||
|
||||
التعامل مع الأخطاء بأناقة أثناء البث:
|
||||
|
||||
```python Code
|
||||
flow = ResearchFlow()
|
||||
streaming = flow.kickoff()
|
||||
|
||||
try:
|
||||
for chunk in streaming:
|
||||
print(chunk.content, end="", flush=True)
|
||||
|
||||
result = streaming.result
|
||||
print(f"\nSuccess! Result: {result}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"\nError during flow execution: {e}")
|
||||
if streaming.is_completed:
|
||||
print("Streaming completed but flow encountered an error")
|
||||
```
|
||||
|
||||
## ملاحظات مهمة
|
||||
|
||||
- يفعّل البث تلقائياً بث LLM لأي أطقم مستخدمة داخل التدفق
|
||||
- يجب التكرار عبر جميع الأجزاء قبل الوصول إلى خاصية `.result`
|
||||
- يعمل البث مع كل من حالة التدفق المنظمة وغير المنظمة
|
||||
- يلتقط بث التدفق المخرجات من جميع الأطقم واستدعاءات LLM في التدفق
|
||||
- يتضمن كل جزء سياقاً حول الوكيل والمهمة التي ولدته
|
||||
- يضيف البث حملاً ضئيلاً لتنفيذ التدفق
|
||||
|
||||
## الدمج مع تصور التدفق
|
||||
|
||||
يمكنك دمج البث مع تصور التدفق لتوفير صورة كاملة:
|
||||
|
||||
```python Code
|
||||
# Generate flow visualization
|
||||
flow = ResearchFlow()
|
||||
flow.plot("research_flow") # Creates HTML visualization
|
||||
|
||||
# Run with streaming
|
||||
streaming = flow.kickoff()
|
||||
for chunk in streaming:
|
||||
print(chunk.content, end="", flush=True)
|
||||
|
||||
result = streaming.result
|
||||
print(f"\nFlow complete! View structure at: research_flow.html")
|
||||
```
|
||||
|
||||
من خلال الاستفادة من بث التدفق، يمكنك بناء تطبيقات متطورة ومتجاوبة توفر للمستخدمين رؤية فورية لسير العمل المعقدة متعددة المراحل، مما يجعل أتمتة الذكاء الاصطناعي الخاصة بك أكثر شفافية وجاذبية.
|
||||
480
docs/ar/learn/tool-hooks.mdx
Normal file
480
docs/ar/learn/tool-hooks.mdx
Normal file
@@ -0,0 +1,480 @@
|
||||
---
|
||||
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. استخدمها لتنفيذ حواجز السلامة وبوابات الموافقة والتحقق من المدخلات وتنقية النتائج والتسجيل والتحليلات. مع معالجة الأخطاء المناسبة وأمان الأنواع، تُمكّن الخطافات أنظمة وكلاء آمنة وجاهزة للإنتاج مع مراقبة شاملة.
|
||||
151
docs/ar/learn/using-annotations.mdx
Normal file
151
docs/ar/learn/using-annotations.mdx
Normal file
@@ -0,0 +1,151 @@
|
||||
---
|
||||
title: "استخدام التعليقات التوضيحية في crew.py"
|
||||
description: "تعلم كيفية استخدام التعليقات التوضيحية لتنظيم الوكلاء والمهام والمكونات بشكل صحيح في CrewAI"
|
||||
icon: "at"
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
يشرح هذا الدليل كيفية استخدام التعليقات التوضيحية للإشارة بشكل صحيح إلى **الوكلاء** و**المهام** والمكونات الأخرى في ملف `crew.py`.
|
||||
|
||||
## مقدمة
|
||||
|
||||
تُستخدم التعليقات التوضيحية في إطار عمل CrewAI لتزيين الفئات والطرق، مما يوفر بيانات وصفية ووظائف للمكونات المختلفة في طاقمك. تساعد هذه التعليقات التوضيحية في تنظيم وهيكلة الكود الخاص بك، مما يجعله أكثر قابلية للقراءة والصيانة.
|
||||
|
||||
## التعليقات التوضيحية المتاحة
|
||||
|
||||
يوفر إطار عمل CrewAI التعليقات التوضيحية التالية:
|
||||
|
||||
- `@CrewBase`: تُستخدم لتزيين فئة الطاقم الرئيسية.
|
||||
- `@agent`: تزين الطرق التي تعرّف وتُرجع كائنات Agent.
|
||||
- `@task`: تزين الطرق التي تعرّف وتُرجع كائنات Task.
|
||||
- `@crew`: تزين الطريقة التي تنشئ وتُرجع كائن Crew.
|
||||
- `@llm`: تزين الطرق التي تهيئ وتُرجع كائنات نماذج اللغة.
|
||||
- `@tool`: تزين الطرق التي تهيئ وتُرجع كائنات الأدوات.
|
||||
- `@callback`: تُستخدم لتعريف طرق الاستدعاء الراجع.
|
||||
- `@output_json`: تُستخدم للطرق التي تُخرج بيانات JSON.
|
||||
- `@output_pydantic`: تُستخدم للطرق التي تُخرج نماذج Pydantic.
|
||||
- `@cache_handler`: تُستخدم لتعريف طرق معالجة التخزين المؤقت.
|
||||
|
||||
## أمثلة الاستخدام
|
||||
|
||||
لنمر عبر أمثلة لكيفية استخدام هذه التعليقات التوضيحية:
|
||||
|
||||
### 1. فئة الطاقم الأساسية
|
||||
|
||||
```python
|
||||
@CrewBase
|
||||
class LinkedinProfileCrew():
|
||||
"""LinkedinProfile crew"""
|
||||
agents_config = 'config/agents.yaml'
|
||||
tasks_config = 'config/tasks.yaml'
|
||||
```
|
||||
|
||||
تُستخدم التعليقة التوضيحية `@CrewBase` لتزيين فئة الطاقم الرئيسية. تحتوي هذه الفئة عادةً على الإعدادات والطرق لإنشاء الوكلاء والمهام والطاقم نفسه.
|
||||
|
||||
<Tip>
|
||||
`@CrewBase` تفعل أكثر من مجرد تسجيل الفئة:
|
||||
|
||||
- **تمهيد الإعدادات:** تبحث عن `agents_config` و `tasks_config` (القيمة الافتراضية `config/agents.yaml` و `config/tasks.yaml`) بجانب ملف الفئة، وتحملها عند الإنشاء، وتتراجع بأمان إلى قواميس فارغة إذا كانت الملفات مفقودة.
|
||||
- **تنسيق المزخرفات:** تحتفظ بمراجع محفوظة لكل طريقة مُعلّمة بـ `@agent` أو `@task` أو `@before_kickoff` أو `@after_kickoff` بحيث يتم إنشاؤها مرة واحدة لكل طاقم وتُنفذ بترتيب الإعلان.
|
||||
- **ربط الخطافات:** تربط تلقائياً خطافات التشغيل المحفوظة بكائن `Crew` المُرجع من طريقة `@crew`، مما يجعلها تعمل قبل وبعد `.kickoff()`.
|
||||
- **تكامل MCP:** عندما تعرّف الفئة `mcp_server_params`، ينشئ `get_mcp_tools()` بكسل محول MCP server، ويملأ الأدوات المُعلنة، ويوقف خطاف ما بعد التشغيل الداخلي المحول. راجع [نظرة عامة على MCP](/ar/mcp/overview) لتفاصيل إعداد المحول.
|
||||
</Tip>
|
||||
|
||||
### 2. تعريف الأداة
|
||||
|
||||
```python
|
||||
@tool
|
||||
def myLinkedInProfileTool(self):
|
||||
return LinkedInProfileTool()
|
||||
```
|
||||
|
||||
تُستخدم التعليقة التوضيحية `@tool` لتزيين الطرق التي تُرجع كائنات أدوات. يمكن للوكلاء استخدام هذه الأدوات لأداء مهام محددة.
|
||||
|
||||
### 3. تعريف LLM
|
||||
|
||||
```python
|
||||
@llm
|
||||
def groq_llm(self):
|
||||
api_key = os.getenv('api_key')
|
||||
return ChatGroq(api_key=api_key, temperature=0, model_name="mixtral-8x7b-32768")
|
||||
```
|
||||
|
||||
تُستخدم التعليقة التوضيحية `@llm` لتزيين الطرق التي تهيئ وتُرجع كائنات نماذج اللغة. تستخدم هذه النماذج من قبل الوكلاء لمهام معالجة اللغة الطبيعية.
|
||||
|
||||
### 4. تعريف الوكيل
|
||||
|
||||
```python
|
||||
@agent
|
||||
def researcher(self) -> Agent:
|
||||
return Agent(
|
||||
config=self.agents_config['researcher']
|
||||
)
|
||||
```
|
||||
|
||||
تُستخدم التعليقة التوضيحية `@agent` لتزيين الطرق التي تعرّف وتُرجع كائنات Agent.
|
||||
|
||||
### 5. تعريف المهمة
|
||||
|
||||
```python
|
||||
@task
|
||||
def research_task(self) -> Task:
|
||||
return Task(
|
||||
config=self.tasks_config['research_linkedin_task'],
|
||||
agent=self.researcher()
|
||||
)
|
||||
```
|
||||
|
||||
تُستخدم التعليقة التوضيحية `@task` لتزيين الطرق التي تعرّف وتُرجع كائنات Task. تحدد هذه الطرق إعداد المهمة والوكيل المسؤول عنها.
|
||||
|
||||
### 6. إنشاء الطاقم
|
||||
|
||||
```python
|
||||
@crew
|
||||
def crew(self) -> Crew:
|
||||
"""Creates the LinkedinProfile crew"""
|
||||
return Crew(
|
||||
agents=self.agents,
|
||||
tasks=self.tasks,
|
||||
process=Process.sequential,
|
||||
verbose=True
|
||||
)
|
||||
```
|
||||
|
||||
تُستخدم التعليقة التوضيحية `@crew` لتزيين الطريقة التي تنشئ وتُرجع كائن `Crew`. تجمع هذه الطريقة جميع المكونات (الوكلاء والمهام) في طاقم وظيفي.
|
||||
|
||||
## إعداد YAML
|
||||
|
||||
تُخزن إعدادات الوكلاء عادةً في ملف YAML. إليك مثالاً على كيفية ظهور ملف `agents.yaml` لوكيل الباحث:
|
||||
|
||||
```yaml
|
||||
researcher:
|
||||
role: >
|
||||
LinkedIn Profile Senior Data Researcher
|
||||
goal: >
|
||||
Uncover detailed LinkedIn profiles based on provided name {name} and domain {domain}
|
||||
Generate a Dall-E image based on domain {domain}
|
||||
backstory: >
|
||||
You're a seasoned researcher with a knack for uncovering the most relevant LinkedIn profiles.
|
||||
Known for your ability to navigate LinkedIn efficiently, you excel at gathering and presenting
|
||||
professional information clearly and concisely.
|
||||
allow_delegation: False
|
||||
verbose: True
|
||||
llm: groq_llm
|
||||
tools:
|
||||
- myLinkedInProfileTool
|
||||
- mySerperDevTool
|
||||
- myDallETool
|
||||
```
|
||||
|
||||
يتوافق إعداد YAML هذا مع وكيل الباحث المُعرّف في فئة `LinkedinProfileCrew`. يحدد الإعداد دور الوكيل وهدفه وخلفيته وخصائص أخرى مثل LLM والأدوات التي يستخدمها.
|
||||
|
||||
لاحظ كيف يتوافق `llm` و `tools` في ملف YAML مع الطرق المزينة بـ `@llm` و `@tool` في فئة Python.
|
||||
|
||||
## أفضل الممارسات
|
||||
|
||||
- **تسمية متسقة**: استخدم اصطلاحات تسمية واضحة ومتسقة لطرقك. على سبيل المثال، يمكن تسمية طرق الوكلاء بأسماء أدوارهم (مثل researcher، reporting_analyst).
|
||||
- **متغيرات البيئة**: استخدم متغيرات البيئة للمعلومات الحساسة مثل مفاتيح API.
|
||||
- **المرونة**: صمم طاقمك ليكون مرناً بالسماح بإضافة أو إزالة الوكلاء والمهام بسهولة.
|
||||
- **توافق YAML-الكود**: تأكد من أن الأسماء والهياكل في ملفات YAML تتوافق بشكل صحيح مع الطرق المزينة في كود Python الخاص بك.
|
||||
|
||||
باتباع هذه الإرشادات واستخدام التعليقات التوضيحية بشكل صحيح، يمكنك إنشاء أطقم منظمة جيداً وسهلة الصيانة باستخدام إطار عمل CrewAI.
|
||||
Reference in New Issue
Block a user