- Content creation crew מלא — researcher, writer, editor שעובדים יחד לייצר תוכן מקצועי
- השוואה מעשית — Sequential vs Hierarchical: אותו workflow בשתי גישות, כולל ניתוח תוצאות
- Custom tools — כלים מותאמים אישית ל-market research עם
@tooldecorator ו-BaseTool - Crew עם delegation — סוכנים שמבקשים עזרה אחד מהשני כשצריך
- Memory מופעל — short-term, long-term, ו-entity memory שהופכים את ה-crew לחכם יותר
- Flow מלא — שלושה crews שמחוברים ב-pipeline: research → analysis → report
- פרויקט CrewAI מלא עם 4+ agents, multiple tools, ו-structured output
- תוכלו להגדיר סוכנים עם role, goal, backstory ו-tools — ולארגן אותם ב-Crew
- תוכלו לבחור בין Sequential ו-Hierarchical processes לפי סוג ה-workflow
- תוכלו ליצור כלים מותאמים אישית ולחבר MCP servers ל-CrewAI
- תוכלו להפעיל delegation בין סוכנים ולנהל collaboration patterns
- תוכלו לתזמר מספר crews עם CrewAI Flows להרכבת pipelines מורכבים
- פרקים קודמים: פרק 1 (מה זה סוכן, לולאת ReAct), פרק 2 (ארכיטקטורות, multi-agent patterns), פרק 3 (Tool Calling), פרק 8 (LangGraph)
- מה תצטרכו: Python 3.11+, מפתח API אחד לפחות (Anthropic / OpenAI / Google), עורך קוד (VS Code / Cursor)
- ידע נדרש: Python בינוני, הכרת Pydantic בסיסית, הבנת concept של agents
- זמן משוער: 3-4 שעות (כולל תרגילים)
- עלות API משוערת: $5-10
בפרקים 5-8 בניתם סוכנים עם SDKs שונים — Anthropic, Vercel, OpenAI ו-LangGraph. כל אחד מהם התמקד בסוכן בודד (או supervisor שמנהל workers). בפרק הזה עוברים לגישה שונה לגמרי: צוותים של סוכנים. במקום לכתוב graph nodes ו-edges, תגדירו סוכנים כ-"עובדים" — עם תפקיד, מטרה, ו-backstory — ותתנו להם לעבוד יחד. ה-tools שבניתם בפרק 3 יתחברו ישירות ל-agents שלכם. בפרק 10 תכירו את Google ADK ו-Pydantic AI — עוד שתי גישות שמשלימות את התמונה.
| מונח (English) | עברית | הסבר |
|---|---|---|
| CrewAI | קרו-אי-איי | Framework לבניית צוותי סוכני AI עם role-playing. מתייחס לסוכנים כאנשי צוות עם תפקידים ומטרות. קוד פתוח + פלטפורמה מסחרית (AMP) |
| Agent | סוכן | יחידה אוטונומית עם role (תפקיד), goal (מטרה), backstory (רקע), tools (כלים) ו-llm (מודל). ה-building block הבסיסי ב-CrewAI |
| Task | משימה | הקצאה ספציפית לסוכן. כוללת description, expected_output, agent שמבצע, ו-context (תלויות במשימות אחרות) |
| Crew | צוות | קבוצת סוכנים שעובדים יחד על משימות. מגדיר agents, tasks, process type, ו-memory settings |
| Sequential Process | תהליך סדרתי | משימות רצות אחת אחרי השנייה, הפלט של כל אחת מוזן לבאה. כמו assembly line |
| Hierarchical Process | תהליך היררכי | סוכן manager מחליט דינמית מי עובד על מה. כמו מנהל צוות שמחלק עבודה |
| Delegation | האצלה | יכולת של סוכן לבקש עזרה מסוכן אחר ב-crew. נשלטת דרך allow_delegation |
| Backstory | סיפור רקע | הקשר שמעצב את התנהגות הסוכן. למשל: "20 שנה ניסיון ב-SEO, עבד בחברות Fortune 500" |
| Flow | זרימה | מנגנון לתזמור מספר crews ולוגיקה. משתמש ב-decorators כמו @start, @listen, @router |
| CrewAI AMP | פלטפורמת AMP | הפלטפורמה המסחרית של CrewAI — Studio ויזואלי, triggers, RBAC, ו-deployment management |
| @tool | דקורטור כלי | Decorator ליצירת כלי מותאם אישית מפונקציית Python רגילה. הדרך הפשוטה ביותר להגדיר tool |
| BaseTool | כלי בסיס | Class base ליצירת כלים מורכבים יותר עם validation, error handling, ו-state |
| Entity Memory | זיכרון ישויות | סוג memory ב-CrewAI שזוכר ישויות מרכזיות (אנשים, חברות, מוצרים) ויחסים ביניהן |
| Kickoff | הפעלה | הפונקציה crew.kickoff() שמתחילה את ריצת ה-crew. מחזירה CrewOutput עם תוצאות כל המשימות |
סקירה ופילוסופיה — למה CrewAI
CrewAI הוא framework לבניית צוותי סוכני AI שעובדים יחד — כמו צוות אנושי אמיתי. בזמן ש-LangGraph (פרק 8) מתייחס לסוכנים כ-state machines עם nodes ו-edges, CrewAI מתייחס אליהם כ-אנשי צוות עם תפקידים, מטרות, וסיפורי רקע. זו הגישה הכי אינטואיטיבית לבניית multi-agent systems — מי שיודע לנהל צוות אנושי, יודע לנהל CrewAI crew.
הפילוסופיה של CrewAI:
- Agents as employees: כל סוכן הוא "עובד" עם role (מה הוא עושה), goal (מה הוא רוצה להשיג), ו-backstory (ניסיון ורקע). ככה ה-LLM "נכנס לתפקיד"
- Tasks as assignments: כל משימה מתוארת בשפה טבעית — מה צריך לעשות, מה התוצאה הצפויה, ומי אחראי
- Crews as teams: צוות = סוכנים + משימות + process type. כמו צוות בחברה שמקבל פרויקט
- Simplicity over control: בניגוד ל-LangGraph שנותן שליטה מקסימלית, CrewAI נותן פשטות מקסימלית. הגישה המהירה ביותר מרעיון ל-multi-agent team עובד
- סוג: Framework קוד פתוח + פלטפורמת CrewAI AMP מסחרית
- תמחור AMP: Basic חינם (50 executions/חודש, seat אחד), Professional ($25/חודש, 100 executions, 2 seats, $0.50 לכל נוסף), Enterprise (custom, עד 30K executions, unlimited seats, SOC2, SSO, RBAC)
- שפה: Python בלבד
- חדש ב-2026: CrewAI Studio — עורך ויזואלי no-code, triggers ל-Gmail/Slack/Salesforce, RBAC ו-deployment management
- אינטגרציות: Gmail, Microsoft Teams, Notion, HubSpot, Salesforce, Slack
- אקוסיסטם: CrewAI (framework) + AMP (platform) + Studio (visual editor) + Marketplace (pre-built crews)
CrewAI מול LangGraph — מתי להשתמש בכל אחד
שני ה-frameworks האלה פותרים בעיות שונות. הם לא מתחרים — הם משלימים:
| קריטריון | CrewAI | LangGraph |
|---|---|---|
| מודל מנטלי | צוות עובדים | State machine / גרף |
| Learning curve | נמוכה — שעה ליצור crew עובד | גבוהה — צריך להבין graphs, state, edges |
| שליטה | High-level — מגדירים מה, לא איך | Low-level — שליטה על כל node ו-edge |
| Multi-agent | מובנה — ככה CrewAI עובד | אפשרי — דרך sub-graphs ו-supervisor |
| Durable execution | מוגבל | מצוין — checkpointing בכל צעד |
| Human-in-the-loop | בסיסי (callback) | מתקדם — interrupt() בכל node |
| מתאים ל... | Prototyping, business automation, non-technical stakeholders | Complex workflows, regulated industries, maximum reliability |
התקינו את CrewAI ואת ה-dependencies:
# יצירת פרויקט חדש
mkdir crewai-project && cd crewai-project
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
# התקנה
pip install crewai crewai-tools
# קובץ .env
echo "OPENAI_API_KEY=sk-..." > .env
echo "ANTHROPIC_API_KEY=sk-ant-..." >> .env
echo "SERPER_API_KEY=..." >> .env # לחיפוש web (חינם עד 2500 queries)
CrewAI משתמש ב-OpenAI כברירת מחדל. אפשר לשנות לכל LLM — נראה איך בהמשך.
Core Concepts — Agent, Task, Crew
CrewAI בנוי על שלושה קונספטים מרכזיים. ברגע שתבינו את השלושה — תוכלו לבנות כל crew:
1. Agent — הסוכן
Agent ב-CrewAI הוא יחידה אוטונומית שמוגדרת על ידי ארבעה פרמטרים מרכזיים:
from crewai import Agent
researcher = Agent(
role="Senior Research Analyst",
goal="Find comprehensive, accurate data about the given topic",
backstory="""You are a veteran research analyst with 15 years of
experience at top consulting firms. You're known for finding
hidden insights in data and never publishing unverified claims.
You always cite your sources.""",
tools=[search_tool, scrape_tool],
llm="gpt-4o", # ברירת מחדל: gpt-4o. אפשר claude, gemini...
verbose=True, # הדפסת כל צעד — מומלץ לפיתוח
allow_delegation=True, # יכול לבקש עזרה מסוכנים אחרים
max_iter=5, # מקסימום איטרציות
memory=True # הפעלת זיכרון
)
הנקודה המרכזית: ה-backstory הוא לא decoration — הוא prompt engineering. ככל שה-backstory יותר ספציפי ומפורט, הסוכן יפעל טוב יותר. "Senior Research Analyst with 15 years of experience" ייתן תוצאות שונות לגמרי מ-"Research Assistant".
2. Task — המשימה
Task היא ההקצאה הספציפית שסוכן מקבל:
from crewai import Task
research_task = Task(
description="""Research the current state of AI agents market
in Israel. Focus on:
1. Key companies (AI21, Tabnine, Run:ai, etc.)
2. Investment trends in 2025-2026
3. Most popular frameworks and tools
4. Unique advantages of the Israeli ecosystem""",
expected_output="""A detailed report with:
- Executive summary (3-4 sentences)
- List of top 10 Israeli AI agent companies with descriptions
- Investment data with sources
- Framework adoption trends
- At least 5 cited sources""",
agent=researcher,
output_file="research_report.md" # שמירה אוטומטית לקובץ
)
שני השדות הכי חשובים הם description (מה לעשות) ו-expected_output (מה צריכה להיות התוצאה). ככל שהם יותר ספציפיים — התוצאה יותר טובה.
3. Crew — הצוות
Crew מחבר סוכנים ומשימות ומריץ אותם:
from crewai import Crew, Process
crew = Crew(
agents=[researcher, writer, editor],
tasks=[research_task, writing_task, editing_task],
process=Process.sequential, # סדרתי — כל משימה אחרי הקודמת
verbose=True,
memory=True, # זיכרון משותף
max_rpm=10 # הגבלת API calls לדקה
)
# הפעלת ה-crew
result = crew.kickoff()
print(result)
צייר את ה-Mental Model: חשבו על צוות אמיתי שעבדתם בו. רשמו 3 חברי צוות, את התפקיד של כל אחד, ואת המשימות שהם עושים. עכשיו תרגמו את זה ל-CrewAI: כל אדם = Agent (עם role, goal, backstory), כל משימה = Task (עם description, expected_output), והצוות כולו = Crew.
בניית ה-Crew הראשון — Content Creation
בואו נבנה crew שלם ליצירת תוכן. שלושה סוכנים: researcher שאוסף מידע, writer שכותב מאמר, ו-editor שעורך ומשפר.
from crewai import Agent, Task, Crew, Process
from crewai_tools import SerperDevTool, ScrapeWebsiteTool
from dotenv import load_dotenv
import os
load_dotenv()
# === כלים ===
search_tool = SerperDevTool() # חיפוש Google (צריך SERPER_API_KEY)
scrape_tool = ScrapeWebsiteTool() # גרידת תוכן מאתרים
# === Agent 1: Researcher ===
researcher = Agent(
role="Senior Research Analyst",
goal="Find accurate, comprehensive data about the given topic",
backstory="""You are a veteran research analyst with 15 years
of experience. You specialize in technology market research
and are known for uncovering hidden trends. You always verify
information from multiple sources before reporting.""",
tools=[search_tool, scrape_tool],
verbose=True,
allow_delegation=False # researcher עובד לבד
)
# === Agent 2: Writer ===
writer = Agent(
role="Senior Content Writer",
goal="Write engaging, well-structured articles based on research",
backstory="""You are an award-winning content writer who has
published in TechCrunch, Wired, and The Verge. You turn complex
technical topics into clear, engaging content that both experts
and beginners can understand. You write in a conversational yet
authoritative tone.""",
verbose=True,
allow_delegation=False
)
# === Agent 3: Editor ===
editor = Agent(
role="Chief Editor",
goal="Ensure all content is polished, accurate, and publication-ready",
backstory="""You are a meticulous editor with an eye for detail.
You check facts, fix grammar, improve flow, and ensure consistency.
You've edited for major tech publications and have zero tolerance
for unverified claims or sloppy writing.""",
verbose=True,
allow_delegation=True # יכול לבקש מ-researcher לאמת facts
)
# === Task 1: Research ===
research_task = Task(
description="""Research the topic: '{topic}'.
Find:
1. Current state and key players
2. Recent developments (2025-2026)
3. Key statistics and data points
4. Expert opinions and predictions
Include at least 5 sources with URLs.""",
expected_output="""A comprehensive research brief with:
- Executive summary (100-150 words)
- Key findings organized by sub-topic
- Data points with citations
- Source list with URLs""",
agent=researcher
)
# === Task 2: Write ===
writing_task = Task(
description="""Write a professional article based on the
research provided. The article should be:
- 800-1000 words
- Include an attention-grabbing headline
- Have clear sections with subheadings
- Include data points from the research
- End with actionable takeaways""",
expected_output="""A complete article with:
- Headline
- Introduction (hook + thesis)
- 3-4 body sections with subheadings
- Conclusion with takeaways
- 800-1000 words total""",
agent=writer,
context=[research_task] # תלוי בתוצאת ה-research
)
# === Task 3: Edit ===
editing_task = Task(
description="""Edit and polish the article. Check for:
1. Factual accuracy — verify all claims against the research
2. Grammar and spelling
3. Flow and readability
4. Consistent tone
5. SEO optimization (title, headings, meta description)""",
expected_output="""The final polished article, publication-ready,
with a separate 'Editor Notes' section listing changes made.""",
agent=editor,
context=[research_task, writing_task], # גישה ל-research ול-draft
output_file="final_article.md"
)
# === Crew ===
content_crew = Crew(
agents=[researcher, writer, editor],
tasks=[research_task, writing_task, editing_task],
process=Process.sequential,
verbose=True
)
# === הפעלה ===
result = content_crew.kickoff(
inputs={"topic": "AI Agents in Israeli Startups 2026"}
)
print("=" * 50)
print("Final Result:")
print(result)
מה קורה כשמריצים את ה-code הזה:
- Researcher מקבל את המשימה, משתמש ב-search_tool ו-scrape_tool כדי לאסוף מידע, ומייצר research brief
- Writer מקבל את ה-research brief (דרך
context=[research_task]) וכותב מאמר - Editor מקבל גם את ה-research וגם את ה-draft (דרך
context), בודק accuracy, עורך, ומייצר את הגרסה הסופית
כל זה קורה אוטומטית — ה-Process.sequential מבטיח שכל task רצה אחרי הקודמת.
הריצו את ה-Content Creation Crew. העתיקו את הקוד, שנו את ה-topic לנושא שמעניין אתכם, והריצו. שימו לב לאיך כל סוכן "נכנס לתפקיד" — ה-researcher חוקר כמו analyst, ה-writer כותב כמו עיתונאי, וה-editor מתקן כמו עורך מנוסה. אם אין לכם SERPER_API_KEY, הורידו את ה-tools מה-researcher — הוא יעבוד גם בלי חיפוש (עם ידע הבסיסי של ה-LLM).
שימוש ב-LLM שונים
CrewAI תומך בכל ספקי ה-LLM המרכזיים. אפשר אפילו לתת לכל סוכן מודל שונה:
# סוכן שמשתמש ב-Claude (מצוין למחקר ודיוק)
researcher = Agent(
role="Senior Research Analyst",
goal="Find accurate data",
backstory="...",
llm="anthropic/claude-sonnet-4-5-20250514"
)
# סוכן שמשתמש ב-GPT-4o (טוב לכתיבה יצירתית)
writer = Agent(
role="Content Writer",
goal="Write engaging articles",
backstory="...",
llm="gpt-4o" # ברירת מחדל
)
# סוכן שמשתמש ב-Gemini (זול, טוב לעריכה)
editor = Agent(
role="Editor",
goal="Polish articles",
backstory="...",
llm="gemini/gemini-2.5-flash"
)
# סוכן עם מודל זול למשימות פשוטות
formatter = Agent(
role="Formatter",
goal="Format the final output",
backstory="...",
llm="gpt-4o-mini" # $0.15/M input — חסכוני מאוד
)
טיפ חשוב: מיקוס מודלים הוא אחת האסטרטגיות הכי חכמות בעבודה עם CrewAI. תנו מודל יקר ומדויק (Claude Sonnet, GPT-4o) ל-agents שעושים reasoning מורכב, ומודל זול (GPT-4o-mini, Gemini Flash) ל-agents שעושים formatting או משימות פשוטות.
Process Types — Sequential vs Hierarchical
CrewAI מציע שני סוגי processes מרכזיים שקובעים איך הסוכנים עובדים יחד:
Sequential — פס ייצור
משימות רצות בסדר קבוע, אחת אחרי השנייה. הפלט של כל משימה מועבר לבאה:
research ──→ write ──→ edit ──→ format
crew = Crew(
agents=[researcher, writer, editor],
tasks=[research_task, writing_task, editing_task],
process=Process.sequential # ברירת מחדל
)
# סדר הריצה: research → writing → editing
# כל task מקבל את הפלט של הקודם דרך context
מתי להשתמש: כשיש סדר טבעי — research לפני כתיבה, כתיבה לפני עריכה. כשכל שלב תלוי בשלב הקודם.
Hierarchical — מנהל צוות
סוכן manager נוצר אוטומטית ומחליט דינמית מי עובד על מה:
┌── researcher
manager ─┤── writer
└── editor
crew = Crew(
agents=[researcher, writer, editor],
tasks=[research_task, writing_task, editing_task],
process=Process.hierarchical,
manager_llm="gpt-4o" # המודל ל-manager agent
)
# ה-manager יחליט דינמית:
# - מי עובד על מה
# - באיזה סדר
# - האם צריך לחזור לשלב קודם
# - מתי הפרויקט מוכן
מתי להשתמש: כשסדר העבודה לא קבוע מראש, כשצריך routing דינמי, כשה-manager צריך להחליט על פי תוצאות ביניים.
השוואה מעשית
| קריטריון | Sequential | Hierarchical |
|---|---|---|
| שליטה | צפוי, דטרמיניסטי | דינמי, ה-manager מחליט |
| מהירות | מהיר יותר (פחות overhead) | איטי יותר (manager calls) |
| עלות | זולה יותר | יקרה יותר (extra LLM calls לmanager) |
| מורכבות | פשוט | מורכב יותר |
| Best for | Pipelines, assembly lines | Complex projects, variable order |
השוו Sequential vs Hierarchical: קחו את ה-Content Creation Crew מלמעלה והריצו אותו פעמיים — פעם עם Process.sequential ופעם עם Process.hierarchical. השוו את התוצאות: איכות, זמן ריצה, ועלות (API calls). שימו לב ל-verbose output — בגרסה ההיררכית תראו את ה-manager מחליט מי עובד ומתי.
כלים ב-CrewAI — Built-in ו-Custom
כלים מובנים
CrewAI מגיע עם ספרייה של כלים מוכנים:
from crewai_tools import (
SerperDevTool, # חיפוש Google (דרך Serper API)
ScrapeWebsiteTool, # גרידת תוכן מאתרים
FileReadTool, # קריאת קבצים מקומיים
DirectoryReadTool, # קריאת תוכן תיקייה
WebsiteSearchTool, # חיפוש בתוך אתר ספציפי
PDFSearchTool, # חיפוש בתוך PDF
YoutubeVideoSearchTool, # חיפוש בסרטוני YouTube
)
# שימוש
search = SerperDevTool() # צריך SERPER_API_KEY ב-.env
scraper = ScrapeWebsiteTool()
file_reader = FileReadTool(file_path="./data/report.csv")
dir_reader = DirectoryReadTool(directory="./data/")
# הקצאה לסוכנים
researcher = Agent(
role="Researcher",
goal="Find information",
backstory="...",
tools=[search, scraper] # הסוכן יכול לחפש ולגרד
)
כלים מותאמים אישית — @tool Decorator
הדרך הפשוטה ביותר ליצור כלי מותאם:
from crewai.tools import tool
import requests
@tool("Stock Price Checker")
def check_stock_price(symbol: str) -> str:
"""Check the current stock price for a given symbol.
Use this when you need to look up stock prices.
Args:
symbol: The stock ticker symbol (e.g., AAPL, GOOGL, TSLA)
"""
# סימולציה — בפרודקשן תחברו ל-API אמיתי
prices = {"AAPL": 245.50, "GOOGL": 195.30, "TSLA": 420.10,
"MSFT": 485.20, "NVDA": 890.40}
price = prices.get(symbol.upper(), None)
if price:
return f"{symbol.upper()} current price: ${price:.2f}"
return f"Symbol {symbol} not found. Available: {', '.join(prices.keys())}"
@tool("Company Info Lookup")
def lookup_company_info(company_name: str) -> str:
"""Look up detailed information about a company.
Use this when you need company background, market cap, or sector info.
Args:
company_name: The name of the company to look up
"""
# דוגמה פשוטה
companies = {
"AI21": {"sector": "AI/NLP", "location": "Tel Aviv",
"founded": 2017, "notable": "Jamba model"},
"Tabnine": {"sector": "AI Coding", "location": "Tel Aviv",
"founded": 2013, "notable": "AI code completion"},
}
info = companies.get(company_name)
if info:
return f"{company_name}: {info}"
return f"No info found for {company_name}"
# הקצאה לסוכן
analyst = Agent(
role="Financial Analyst",
goal="Analyze companies and stocks",
backstory="...",
tools=[check_stock_price, lookup_company_info]
)
כלים מותאמים — BaseTool Class
לכלים מורכבים יותר שצריכים validation, error handling, או state:
from crewai.tools import BaseTool
from pydantic import BaseModel, Field
from typing import Type
import json
class MarketResearchInput(BaseModel):
"""Input schema for MarketResearchTool."""
query: str = Field(..., description="The research query")
market: str = Field(
default="global",
description="Target market: 'global', 'israel', 'us', 'eu'"
)
max_results: int = Field(
default=5,
description="Maximum number of results to return"
)
class MarketResearchTool(BaseTool):
name: str = "Market Research Tool"
description: str = """Research market data including market size,
growth rates, key players, and trends. Use this for any market
analysis or competitive intelligence task."""
args_schema: Type[BaseModel] = MarketResearchInput
def _run(self, query: str, market: str = "global",
max_results: int = 5) -> str:
"""Execute the market research."""
# בפרודקשן — חיבור ל-API אמיתי (Statista, CB Insights, etc.)
results = {
"query": query,
"market": market,
"findings": [
f"Market size for '{query}' in {market}: $X.XB (2026)",
f"Growth rate: XX% CAGR (2024-2028)",
f"Key players: Company A, Company B, Company C",
f"Trend: Increasing adoption of AI agents",
f"Israel-specific: Strong ecosystem with Unit 8200 alumni"
][:max_results]
}
return json.dumps(results, indent=2)
# שימוש
market_tool = MarketResearchTool()
analyst = Agent(
role="Market Analyst",
goal="Provide market insights",
backstory="...",
tools=[market_tool]
)
חיבור MCP Servers
CrewAI תומך בחיבור MCP (Model Context Protocol) servers ככלים — מה שנותן גישה ל-10,000+ שרתי MCP קיימים:
from crewai import Agent
from crewai_tools import MCPTool
# חיבור לשרת MCP קיים
mcp_tool = MCPTool(
server_command="npx",
server_args=["-y", "@modelcontextprotocol/server-filesystem",
"/path/to/allowed/directory"]
)
# הסוכן מקבל גישה לכל הכלים שה-MCP server חושף
file_agent = Agent(
role="File Manager",
goal="Manage and analyze files",
backstory="...",
tools=[mcp_tool]
)
בנו custom tool: צרו כלי מותאם עם @tool decorator שעושה משהו שימושי לכם — אולי בדיקת מזג אוויר, המרת מטבע, או חיפוש במאגר נתונים מקומי. חברו אותו לסוכן והריצו task שמשתמש בו. שימו לב ל-docstring — ה-LLM משתמש בו כדי להבין מתי ואיך להשתמש בכלי.
מטרה: בניית crew ל-market research עם 3 סוכנים ו-2 custom tools.
- צרו 2 custom tools:
search_competitors(מחזיר רשימת מתחרים) ו-analyze_market_size(מחזיר גודל שוק) - הגדירו 3 agents:
Market Researcher,Competitive Analyst,Strategy Advisor - צרו 3 tasks: research market → analyze competitors → write strategy recommendations
- הריצו עם
Process.sequential - הוסיפו
output_fileל-task האחרון
Success criteria: ה-crew מייצר דוח strategy מבוסס על research ו-competitive analysis. כל סוכן משתמש ב-custom tools.
עלות: ~$0.50-1
Delegation ו-Collaboration
אחת התכונות הכי מעניינות של CrewAI היא delegation — היכולת של סוכן אחד לבקש עזרה מסוכן אחר. זה כמו עובד שפונה לקולגה: "היי, אתה מתמחה ב-SEO — אתה יכול לבדוק את הנקודה הזו?"
researcher = Agent(
role="Senior Researcher",
goal="Find comprehensive data",
backstory="...",
allow_delegation=False # Researcher עובד לבד — מומחה יחיד
)
writer = Agent(
role="Content Writer",
goal="Write excellent articles",
backstory="...",
allow_delegation=True # Writer יכול לבקש עזרה
)
editor = Agent(
role="Chief Editor",
goal="Ensure publication-quality content",
backstory="""You are meticulous about facts. When you encounter
an unverified claim, you ALWAYS delegate to the researcher
to verify it before publishing.""",
allow_delegation=True # Editor יכול לבקש מ-researcher לאמת
)
# כשה-editor רואה claim לא מאומת, הוא יפנה ל-researcher:
# "Hey Senior Researcher, can you verify this claim about...?"
ניהול delegation depth
בלי שליטה, delegation יכולה ליצור loops אינסופיים — A מאציל ל-B, B מאציל ל-A. CrewAI מנהל את זה עם max_iter:
# הגבלת עומק delegation
agent = Agent(
role="...",
goal="...",
backstory="...",
allow_delegation=True,
max_iter=5, # מקסימום 5 iteration cycles
max_retry_limit=2 # מקסימום 2 retries על שגיאות
)
# Pattern מומלץ:
# 1. Researcher: allow_delegation=False (מומחה — עובד לבד)
# 2. Writer: allow_delegation=True (יכול לבקש facts מ-researcher)
# 3. Editor: allow_delegation=True (יכול לבקש מ-researcher לאמת)
# 4. Formatter: allow_delegation=False (משימה טכנית — לא צריך עזרה)
דפוס ה-"Crew Meeting"
Pattern מתקדם — סוכנים ש"נפגשים" לדון לפני שמתחילים לעבוד:
# Task 0: Planning meeting
planning_task = Task(
description="""Before starting any work, discuss the project
approach with your team. Consider:
1. What information do we need?
2. What's the best structure for the final output?
3. What are the potential challenges?
Produce a brief project plan.""",
expected_output="""A project plan with:
- Key research questions
- Article structure
- Risk areas to watch
- Quality criteria""",
agent=editor # Editor leads the planning
)
# הוסיפו כ-task ראשון — כל ה-tasks הבאים יקבלו את ה-plan כ-context
writing_task = Task(
description="Write the article based on research AND the project plan...",
expected_output="...",
agent=writer,
context=[planning_task, research_task]
)
Memory — זיכרון קצר וארוך טווח
CrewAI מציע ארבעה סוגי memory שהופכים את ה-crew מ-"חד פעמי" ל-"חכם יותר עם הזמן":
| סוג Memory | מה הוא עושה | טווח | דוגמה |
|---|---|---|---|
| Short-term | שומר הקשר בתוך ריצה אחת | ריצה אחת | Researcher שיתף data → Writer יודע להשתמש בו |
| Long-term | שומר ידע בין ריצות | לצמיתות | ה-crew זוכר שעבד על "AI Agents" בפעם הקודמת |
| Entity | זוכר ישויות ויחסים | לצמיתות | "AI21 Labs — חברת AI ישראלית, מייסד: Yoav Shoham" |
| Contextual | זוכר הקשר ויחסים | לצמיתות | "כשכותבים על AI ישראלי, תמיד להזכיר את 8200" |
from crewai import Crew, Process
# הפעלת כל סוגי ה-memory
crew = Crew(
agents=[researcher, writer, editor],
tasks=[research_task, writing_task, editing_task],
process=Process.sequential,
memory=True, # מפעיל את כל סוגי ה-memory
verbose=True
)
# ריצה ראשונה — ה-crew לומד
result1 = crew.kickoff(inputs={"topic": "AI Agents Market"})
# ריצה שנייה — ה-crew *זוכר* מה עשה קודם
# ויכול לבנות על הידע הקודם
result2 = crew.kickoff(inputs={"topic": "AI Agents in Healthcare"})
# ^ ה-crew יזכור entities, patterns ומידע מהריצה הראשונה
Memory Storage Backends
ברירת המחדל היא שמירה מקומית בתיקיית הפרויקט. לפרודקשן אפשר להגדיר backends אחרים:
from crewai import Crew
# הגדרת memory מתקדמת
crew = Crew(
agents=[...],
tasks=[...],
memory=True,
# ברירת מחדל: שמירה מקומית בתיקיית db/
# long-term memory נשמר ב-SQLite
# entity memory משתמש בהטמעות (embeddings)
embedder={
"provider": "openai",
"config": {
"model": "text-embedding-3-small"
}
}
)
הפעילו memory: הוסיפו memory=True ל-crew שלכם והריצו אותו פעמיים על נושאים קשורים. בריצה השנייה, שימו לב אם הסוכנים מתייחסים למידע מהריצה הראשונה. זה ההבדל בין crew "חד פעמי" ל-crew ש"לומד".
Advanced Crew Patterns
Conditional Tasks
משימות שרצות רק אם תנאי מתקיים:
from crewai import Task
def should_fact_check(output) -> bool:
"""Run fact check only if the article mentions statistics."""
return any(word in output.raw.lower()
for word in ["percent", "%", "billion", "million", "study"])
# Task שרץ רק אם יש claim סטטיסטי
fact_check_task = Task(
description="Verify all statistical claims in the article...",
expected_output="Fact-check report with verified/unverified claims",
agent=researcher,
condition=should_fact_check, # רץ רק אם הפונקציה מחזירה True
context=[writing_task]
)
Structured Output עם Pydantic
במקום free-text, אפשר להכריח את הסוכן להחזיר structured data:
from pydantic import BaseModel, Field
from typing import List
class CompetitorAnalysis(BaseModel):
"""Structured output for competitive analysis."""
company_name: str = Field(description="Name of the competitor")
market_share: float = Field(description="Market share percentage")
strengths: List[str] = Field(description="Top 3 strengths")
weaknesses: List[str] = Field(description="Top 3 weaknesses")
threat_level: str = Field(description="low, medium, or high")
class MarketReport(BaseModel):
"""Complete market report."""
executive_summary: str
market_size_usd: float
growth_rate: float
competitors: List[CompetitorAnalysis]
recommendations: List[str]
# Task עם structured output
analysis_task = Task(
description="Analyze the competitive landscape for {topic}...",
expected_output="Structured market report",
agent=analyst,
output_pydantic=MarketReport # מכריח structured output!
)
# אחרי ריצה:
result = crew.kickoff(inputs={"topic": "AI Agents"})
report = result.pydantic # MarketReport object — type-safe!
print(f"Market size: ${report.market_size_usd:,.0f}")
for comp in report.competitors:
print(f" {comp.company_name}: {comp.threat_level} threat")
Callback Functions
הוספת לוגיקה לפני ואחרי כל task:
import time
def on_task_start(task_output):
"""Called before a task starts."""
print(f"[{time.strftime('%H:%M:%S')}] Starting task...")
def on_task_complete(task_output):
"""Called after a task completes."""
print(f"[{time.strftime('%H:%M:%S')}] Task completed!")
print(f" Output length: {len(task_output.raw)} chars")
# שמירה ל-database, שליחת notification, וכו'
if len(task_output.raw) < 100:
print(" WARNING: Output seems too short!")
research_task = Task(
description="...",
expected_output="...",
agent=researcher,
callback=on_task_complete # נקרא אחרי שה-task מסתיים
)
| שאלה | Sequential | Hierarchical | Flow (Multi-Crew) |
|---|---|---|---|
| כמה agents? | 2-4 | 3-6 | 6+ |
| סדר עבודה ידוע? | כן, קבוע | לא, דינמי | חלקית — crews ידועים, tasks דינמיים |
| תלות בין משימות? | ליניארית (A→B→C) | מורכבת | בין crews: ליניארית / מותנית |
| Budget concern? | כן — הכי זול | מתון | גבוה |
| דוגמה | Research → Write → Edit | Project manager + team | 3 crews: Research, Analysis, Report |
מטרה: בניית competitive analysis crew שמחזיר structured data.
- הגדירו Pydantic models:
CompetitorProfileו-CompetitiveReport - צרו 2 agents:
Research Analystו-Strategy Consultant - Task 1: Research 5 competitors (output: free text)
- Task 2: Produce structured competitive report (output:
output_pydantic=CompetitiveReport) - הדפיסו את התוצאה כ-JSON formatted
Success criteria: מקבלים CompetitiveReport object עם type-safe fields. אפשר לגשת ל-report.competitors[0].threat_level.
עלות: ~$0.30-0.50
CrewAI Flows — תזמור Multi-Crew
מה קורה כשפרויקט אחד צריך מספר crews? כמו חברה שיש בה מחלקת מחקר, מחלקת ניתוח, ומחלקת כתיבה — כל אחת צוות נפרד. CrewAI Flows מאפשרים לחבר crews ולוגיקה לתהליכים מורכבים.
Flow Basics
from crewai.flow.flow import Flow, listen, start, router
from pydantic import BaseModel
# === State שמנוהל לאורך כל ה-Flow ===
class MarketAnalysisState(BaseModel):
topic: str = ""
research_data: str = ""
analysis: str = ""
final_report: str = ""
class MarketAnalysisFlow(Flow[MarketAnalysisState]):
"""Flow that orchestrates research -> analysis -> report."""
@start()
def run_research_crew(self):
"""Step 1: Research crew gathers data."""
research_crew = Crew(
agents=[researcher],
tasks=[research_task],
process=Process.sequential
)
result = research_crew.kickoff(
inputs={"topic": self.state.topic}
)
self.state.research_data = result.raw
return result.raw
@listen(run_research_crew)
def run_analysis_crew(self):
"""Step 2: Analysis crew analyzes the research."""
analysis_crew = Crew(
agents=[analyst, statistician],
tasks=[analysis_task, stats_task],
process=Process.sequential
)
result = analysis_crew.kickoff(
inputs={"research": self.state.research_data}
)
self.state.analysis = result.raw
return result.raw
@listen(run_analysis_crew)
def run_report_crew(self):
"""Step 3: Report crew writes the final report."""
report_crew = Crew(
agents=[writer, editor],
tasks=[writing_task, editing_task],
process=Process.sequential
)
result = report_crew.kickoff(
inputs={
"research": self.state.research_data,
"analysis": self.state.analysis
}
)
self.state.final_report = result.raw
return result.raw
# === הפעלה ===
flow = MarketAnalysisFlow()
final = flow.kickoff(inputs={"topic": "AI Agents Market Israel 2026"})
print(final)
Router — ניתוב דינמי ב-Flow
ה-@router decorator מאפשר ניתוב דינמי — החלטה מה השלב הבא על בסיס תוצאות:
from crewai.flow.flow import Flow, listen, start, router, or_
class ContentFlow(Flow[ContentState]):
@start()
def gather_requirements(self):
"""Step 1: Understand what content is needed."""
# ... gather requirements logic ...
return self.state.requirements
@router(gather_requirements)
def decide_content_type(self):
"""Route based on content type."""
if "blog" in self.state.requirements.lower():
return "blog_crew"
elif "social" in self.state.requirements.lower():
return "social_crew"
else:
return "general_crew"
@listen("blog_crew")
def run_blog_crew(self):
"""Specialized blog writing crew."""
blog_crew = Crew(
agents=[seo_researcher, blog_writer, blog_editor],
tasks=[seo_task, blog_writing_task, blog_editing_task],
process=Process.sequential
)
return blog_crew.kickoff().raw
@listen("social_crew")
def run_social_crew(self):
"""Specialized social media crew."""
social_crew = Crew(
agents=[trend_analyst, copywriter],
tasks=[trend_task, social_copy_task],
process=Process.sequential
)
return social_crew.kickoff().raw
@listen("general_crew")
def run_general_crew(self):
"""General content crew."""
general_crew = Crew(
agents=[writer, editor],
tasks=[writing_task, editing_task],
process=Process.sequential
)
return general_crew.kickoff().raw
@listen(or_(run_blog_crew, run_social_crew, run_general_crew))
def quality_check(self):
"""Final quality check — runs regardless of which crew was used."""
# ... quality check logic ...
return self.state.final_output
בנו Flow פשוט: צרו flow עם שני crews — research_crew (עם researcher agent) ו-writing_crew (עם writer agent). ה-research crew אוסף מידע, ה-writing crew כותב מאמר על בסיס המידע. השתמשו ב-@start ו-@listen. הריצו את ה-flow על נושא שמעניין אתכם ובדקו שה-state עובר נכון בין ה-crews.
Real-World Examples — שיווק, פיתוח, מכירות
דוגמה 1: Marketing Crew — SEO + Content + Social
from crewai import Agent, Task, Crew, Process
from crewai_tools import SerperDevTool
search = SerperDevTool()
# === Agents ===
seo_researcher = Agent(
role="SEO Research Specialist",
goal="Find high-value keywords and content gaps",
backstory="""10 years in SEO. You understand search intent,
keyword difficulty, and content gaps. You use data-driven
approaches and always check search volume.""",
tools=[search],
llm="gpt-4o"
)
content_writer = Agent(
role="Senior Content Writer",
goal="Write SEO-optimized articles that rank and engage",
backstory="""You write content that ranks on Google AND
engages readers. You balance SEO keywords with readability.
You've helped clients increase organic traffic by 300%.""",
llm="anthropic/claude-sonnet-4-5-20250514"
)
social_manager = Agent(
role="Social Media Manager",
goal="Create engaging social posts that drive traffic to the article",
backstory="""You manage social media for tech brands.
You know what works on LinkedIn, X, and Instagram.
You adapt the message for each platform's audience.""",
llm="gpt-4o-mini" # מודל זול — מספיק ל-social posts
)
# === Tasks ===
seo_task = Task(
description="""Research SEO opportunity for: '{topic}'.
Provide: primary keyword, 5 secondary keywords, search intent,
top 3 ranking competitors, content gap analysis.""",
expected_output="SEO brief with keywords, competitors, and gaps",
agent=seo_researcher
)
content_task = Task(
description="""Write a 1500-word SEO-optimized article about '{topic}'.
Use the SEO brief from the researcher. Include:
- H1 with primary keyword
- H2s with secondary keywords
- Meta description (155 chars)
- Internal linking suggestions""",
expected_output="Complete SEO article with meta description",
agent=content_writer,
context=[seo_task]
)
social_task = Task(
description="""Create social media posts for the article:
- LinkedIn post (professional, 200-300 words)
- X/Twitter thread (5 tweets, each under 280 chars)
- Instagram caption (with emoji, hashtags)""",
expected_output="3 platform-specific social posts",
agent=social_manager,
context=[content_task],
output_file="social_posts.md"
)
# === Crew ===
marketing_crew = Crew(
agents=[seo_researcher, content_writer, social_manager],
tasks=[seo_task, content_task, social_task],
process=Process.sequential,
verbose=True
)
result = marketing_crew.kickoff(
inputs={"topic": "AI Agents for Digital Marketing 2026"}
)
דוגמה 2: Software Development Crew
pm = Agent(
role="Product Manager",
goal="Define clear requirements from user stories",
backstory="You translate vague requirements into clear specs...",
llm="gpt-4o"
)
developer = Agent(
role="Senior Python Developer",
goal="Write clean, tested, production-ready code",
backstory="""15 years Python experience. You write code that
follows PEP 8, has docstrings, and includes error handling.
You always write tests alongside your code.""",
llm="anthropic/claude-sonnet-4-5-20250514" # Claude מצוין לקוד
)
qa_engineer = Agent(
role="QA Engineer",
goal="Find bugs and verify requirements are met",
backstory="You have a talent for finding edge cases...",
llm="gpt-4o"
)
docs_writer = Agent(
role="Technical Writer",
goal="Write clear documentation for developers",
backstory="...",
llm="gpt-4o-mini" # מספיק לדוקומנטציה
)
# Tasks: spec → code → test → docs
spec_task = Task(
description="Write technical spec for: {feature}",
expected_output="PRD with requirements, acceptance criteria, edge cases",
agent=pm
)
code_task = Task(
description="Implement the feature based on the spec...",
expected_output="Python code with docstrings and type hints",
agent=developer,
context=[spec_task]
)
test_task = Task(
description="Review the code and write test cases...",
expected_output="Test report + pytest test cases",
agent=qa_engineer,
context=[spec_task, code_task]
)
docs_task = Task(
description="Write API documentation...",
expected_output="Markdown documentation with examples",
agent=docs_writer,
context=[spec_task, code_task],
output_file="api_docs.md"
)
dev_crew = Crew(
agents=[pm, developer, qa_engineer, docs_writer],
tasks=[spec_task, code_task, test_task, docs_task],
process=Process.sequential
)
דוגמה 3: Sales Crew לסטארטאפ ישראלי
lead_researcher = Agent(
role="Lead Research Specialist",
goal="Find and qualify potential leads",
backstory="""You specialize in B2B lead research for Israeli
tech companies selling to US enterprise clients. You understand
the unique challenges of selling from Israel to the US market
— timezone differences, cultural nuances, and the competitive
landscape.""",
tools=[search],
llm="gpt-4o"
)
outreach_specialist = Agent(
role="Outreach Specialist",
goal="Write personalized outreach messages that get responses",
backstory="""You've written outreach for Israeli startups
targeting Fortune 500 companies. You know that personalization
is everything — generic templates get 2% response rates,
your personalized messages get 15-20%.""",
llm="anthropic/claude-sonnet-4-5-20250514"
)
followup_manager = Agent(
role="Follow-up Manager",
goal="Create follow-up sequences that convert",
backstory="""You manage follow-up sequences for enterprise sales.
You know that 80% of sales require 5+ follow-ups. You write
sequences that add value at each step — never just 'checking in'.""",
llm="gpt-4o-mini"
)
# Tasks
research_leads = Task(
description="""Research potential leads for: '{product}'.
Target: VP/Director level at US companies with 500+ employees.
Find 5 leads with: name, title, company, pain point, linkedin URL.""",
expected_output="5 qualified leads with details",
agent=lead_researcher
)
write_outreach = Task(
description="""Write personalized outreach emails for each lead.
Each email should reference a specific pain point and how
'{product}' solves it. Keep emails under 150 words.""",
expected_output="5 personalized outreach emails",
agent=outreach_specialist,
context=[research_leads]
)
create_followups = Task(
description="""Create a 3-email follow-up sequence for each lead.
Follow-up 1 (day 3): value-add insight
Follow-up 2 (day 7): social proof / case study
Follow-up 3 (day 14): final touch with specific ask""",
expected_output="3 follow-up emails per lead (15 total)",
agent=followup_manager,
context=[research_leads, write_outreach],
output_file="outreach_sequences.md"
)
sales_crew = Crew(
agents=[lead_researcher, outreach_specialist, followup_manager],
tasks=[research_leads, write_outreach, create_followups],
process=Process.sequential,
memory=True # זוכר leads מריצות קודמות
)
מטרה: בניית crew מותאם אישית לתחום שלכם.
- בחרו use case מהתחום שלכם — שיווק, פיתוח, מכירות, HR, finance...
- הגדירו 3-4 agents עם roles, goals, ו-backstories ספציפיים
- צרו 3-4 tasks עם context dependencies
- הוסיפו לפחות custom tool אחד
- הוסיפו output_pydantic ל-task האחרון
- הריצו עם
memory=True
Success criteria: ה-crew מייצר תוצאה שימושית עם structured output. כל agent תורם ערך ייחודי.
עלות: ~$1-2
CrewAI בפרודקשן
Deployment Options
| אפשרות | מתאים ל... | מורכבות | עלות |
|---|---|---|---|
| CrewAI AMP | Managed platform, Studio ויזואלי | נמוכה | $25/חודש+ |
| Docker | Self-hosted, full control | בינונית | עלות server |
| Cloud Functions | Serverless, event-driven | בינונית | Pay per execution |
| FastAPI + Docker | REST API, custom infrastructure | גבוהה | עלות server + maintenance |
Monitoring ו-Error Handling
import time
import logging
from crewai import Crew, Process
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def run_crew_safe(crew, inputs, max_retries=3):
"""Run a crew with retry logic and monitoring."""
for attempt in range(max_retries):
try:
start_time = time.time()
result = crew.kickoff(inputs=inputs)
elapsed = time.time() - start_time
# Monitoring
logger.info(f"Crew completed in {elapsed:.1f}s")
logger.info(f"Output length: {len(result.raw)} chars")
# Basic quality check
if len(result.raw) < 50:
logger.warning("Output seems too short — may be low quality")
return result
except Exception as e:
logger.error(f"Attempt {attempt + 1} failed: {e}")
if attempt < max_retries - 1:
wait = 2 ** attempt # Exponential backoff
logger.info(f"Retrying in {wait}s...")
time.sleep(wait)
else:
logger.error("All retries exhausted")
raise
# שימוש
crew = Crew(
agents=[researcher, writer, editor],
tasks=[research_task, writing_task, editing_task],
process=Process.sequential,
max_rpm=10, # הגבלת rate — חשוב בפרודקשן!
verbose=False # False בפרודקשן — verbose רק ב-dev
)
result = run_crew_safe(
crew,
inputs={"topic": "AI Agents Market 2026"},
max_retries=3
)
Cost Optimization
עלות היא אחד האתגרים המרכזיים ב-CrewAI. כל agent עושה מספר LLM calls, ועם 4 agents ו-4 tasks — אפשר להגיע ל-20+ calls בריצה אחת.
# 1. מיקוס מודלים — מודל יקר רק למי שצריך
researcher = Agent(llm="gpt-4o", ...) # $2.50/M input — צריך quality
writer = Agent(llm="anthropic/claude-sonnet-4-5-20250514", ...) # $3/M — איכות כתיבה
formatter = Agent(llm="gpt-4o-mini", ...) # $0.15/M — מספיק ל-formatting
# 2. הגבלת iterations
agent = Agent(max_iter=3, ...) # ברירת מחדל: 15 (!)
# 3. הגבלת RPM
crew = Crew(max_rpm=10, ...) # מונע burst של API calls
# 4. תיאורי tasks קצרים — פחות tokens
# רע: תיאור של 500 מילים
# טוב: תיאור של 100-150 מילים ברורות
# 5. הימנעו מ-delegation מיותר
agent = Agent(allow_delegation=False, ...) # רק כשבאמת צריך
CrewAI Limitations — מה צריך לדעת
- Reliability at scale: CrewAI עובד מצוין ל-prototyping ו-medium workloads. לעומסים גבוהים (אלפי ריצות ביום) — LangGraph יציב יותר
- Debugging complexity: כשסוכן נכשל או מייצר תוצאה גרועה, קשה לדעת למה — אין tracing מובנה ברמת LangSmith
- Cost unpredictability: בגלל delegation ו-multiple iterations, קשה לחזות את העלות מראש
- Python only: אין תמיכה ב-TypeScript — מי שצריך JS/TS ילך ל-Vercel AI SDK או Mastra
| Use Case | CrewAI | LangGraph | Claude SDK | OpenAI SDK |
|---|---|---|---|---|
| Multi-agent (fast prototype) | Best | OK | -- | OK |
| Multi-agent (production) | OK | Best | -- | OK |
| Single agent + tools | Overkill | OK | Best | Best |
| Durable execution | Limited | Best | -- | -- |
| Non-technical stakeholders | Best (Studio) | -- | -- | -- |
| Business process automation | Best | OK | -- | OK |
| Israeli startup (lean team) | Best | OK | OK | OK |
Bottom line: CrewAI הוא הבחירה הנכונה כשרוצים multi-agent teams מהר — prototyping, business automation, non-technical stakeholders. לפרודקשן עם דרישות reliability גבוהות — LangGraph. לסוכן בודד פשוט — Claude SDK או OpenAI SDK.
מטרה: בניית flow שלם עם 3 crews, conditional routing, ו-structured output.
- צרו Flow class עם state שכולל: topic, research_data, content_type, final_output
- Crew 1 — Research: 2 agents (researcher + data analyst), 2 tasks
- Router: על בסיס ה-research, החליטו אם לייצר blog post, report, או social content
- Crew 2a (Blog): writer + editor
- Crew 2b (Report): analyst + technical writer
- Crew 2c (Social): social media manager
- Crew 3 — QA: quality reviewer שבודק את הפלט (runs always, regardless of route)
- הוסיפו
output_pydanticל-crew 3 עם structured quality report
Success criteria: Flow routes correctly based on research. QA crew produces structured quality report. Full pipeline runs end-to-end.
עלות: ~$3-5
טעויות נפוצות — ואיך להימנע מהן
מה קורה: כותבים backstory כמו "You are a helpful assistant" או "You are a researcher".
למה זה בעיה: ה-backstory הוא ה-prompt engineering של CrewAI. בלי backstory ספציפי, כל הסוכנים מתנהגים אותו דבר — generic ובינוני.
הפתרון: כתבו backstory מפורט עם: שנות ניסיון, התמחויות ספציפיות, סגנון עבודה, ומה הסוכן לא עושה. "15 years of SEO experience, worked with Fortune 500 clients, never publishes without data backing" → תוצאות טובות בהרבה.
מה קורה: מגדירים 8 agents כש-3 מספיקים.
למה זה בעיה: כל agent = LLM calls נוספים = עלות + זמן + סיכוי ל-errors. Agent שלא תורם ערך ייחודי הוא waste. גרוע יותר — delegation בין 8 agents יוצר chaos.
הפתרון: שאלו לגבי כל agent: "האם יש לו skill ייחודי שאף agent אחר לא יכול לעשות?" אם לא — מחקו אותו ותנו את המשימה שלו לagent קיים. 3-4 agents הוא ה-sweet spot ברוב המקרים.
מה קורה: כותבים expected_output="A good report".
למה זה בעיה: ה-LLM לא יודע מה "good" אומר. התוצאה תהיה רנדומלית — לפעמים 100 מילים, לפעמים 2000. לפעמים markdown, לפעמים plain text.
הפתרון: היו ספציפיים: "A report with: executive summary (100-150 words), 5 key findings as bullet points, data table with 3 columns (company, revenue, growth), conclusion (50 words)". ככל ש-expected_output יותר מדויק — התוצאה יותר טובה.
מה קורה: כל הסוכנים עם allow_delegation=True.
למה זה בעיה: Agent A מאציל ל-B, B מאציל ל-C, C מאציל ל-A. בז'רגון: delegation chain. בפועל: 20 LLM calls שלא מייצרים ערך, עלות x3, ותוצאה בינונית.
הפתרון: תנו delegation רק לsupervisor/editor agents. Specialist agents (researcher, writer) צריכים allow_delegation=False — הם מומחים, הם עושים את העבודה בעצמם.
מה קורה: Agent עם tools רץ שוב ושוב כי הוא לא מרוצה מהתוצאה.
למה זה בעיה: ברירת המחדל של max_iter היא 25 (!). סוכן שנתקע ב-loop = 25 LLM calls = $5-15 על task אחד. עם 4 agents — זה יכול להגיע ל-$50+ על ריצה אחת.
הפתרון: תמיד הגדירו max_iter=5 (או 3 ל-tasks פשוטים). בדקו שה-expected_output ברור מספיק כדי שהסוכן יסיים מוקדם.
| תדירות | משימה | זמן |
|---|---|---|
| יומי | בדקו crew runs — הצלחות, כשלונות, זמני ריצה | 5 דק' |
| יומי | בדקו API costs — עלות per crew run, agents יקרים | 5 דק' |
| שבועי | Review של backstories — עדכנו על בסיס תוצאות (prompt engineering) | 15 דק' |
| שבועי | בדקו CrewAI versions — pip install --upgrade crewai | 5 דק' |
| חודשי | Crew architecture review — האם צריך agents חדשים? האם יש agents מיותרים? | 20 דק' |
| חודשי | Model mix audit — האם יש agents שמשתמשים במודל יקר מדי למשימה שלהם? | 10 דק' |
בנו Content Creation Crew עם 3 agents (researcher, writer, editor), הריצו אותו על נושא שרלוונטי לעבודה שלכם, וקראו את ה-verbose output. ברגע שתראו איך כל סוכן "נכנס לתפקיד" ומייצר תוצאה שמשלימה את הקודם — תבינו למה multi-agent systems הם כל כך חזקים. וזה לוקח 20 שורות קוד.
הוסיפו async kickoff: שנו את crew.kickoff() ל-await crew.kickoff_async() ועטפו ב-async function. זה מאפשר להריץ crews במקביל — למשל marketing crew ו-sales crew על אותו topic. הריצו שני crews ב-asyncio.gather() ובדקו שהתוצאות חוזרות.
בדקו את CrewAI Studio: היכנסו ל-app.crewai.com וצרו חשבון חינם. נסו לבנות את אותו Content Creation Crew דרך ה-UI הויזואלי — בלי לכתוב שורת קוד. השוו את החוויה: מה יותר מהיר? מה נותן יותר שליטה? זו ההחלטה שתצטרכו לעשות בפרודקשן.
- מהם שלושת הקונספטים המרכזיים של CrewAI ואיך הם קשורים? (רמז: Agent, Task, Crew)
- מה ההבדל בין Sequential ל-Hierarchical process? תנו דוגמה מתי תשתמשו בכל אחד. (רמז: סדר ידוע vs manager דינמי)
- מה התפקיד של
backstoryולמה הוא כל כך חשוב? תנו דוגמה ל-backstory טוב ול-backstory רע. (רמז: prompt engineering, ספציפיות) - הסבירו את הסיכון ב-
allow_delegation=Trueלכל הסוכנים. איך מנהלים delegation נכון? (רמז: chains, max_iter, specialist vs supervisor) - מתי תבחרו CrewAI ומתי LangGraph? תנו 2 use cases לכל אחד. (רמז: simplicity vs control, prototype vs production)
עברתם 4 מתוך 5? מצוין — אתם מוכנים לפרק 10.
בפרק הזה למדתם לבנות צוותי סוכני AI עם CrewAI — ה-framework הכי אינטואיטיבי ל-multi-agent systems. התחלנו עם שלושת הקונספטים (Agent, Task, Crew), בנינו Content Creation Crew מלא, השווינו Sequential vs Hierarchical processes, יצרנו custom tools עם @tool ו-BaseTool, הפעלנו delegation בין סוכנים, הוספנו memory לזיכרון לטווח ארוך, ובנינו Flows שמתזמרים מספר crews. ראינו דוגמאות אמיתיות — marketing crew, development crew, ו-sales crew לסטארטאפ ישראלי.
הנקודה המרכזית: CrewAI הוא הדרך הכי מהירה לבנות multi-agent team שעובד — אבל עבור production-grade reliability תצטרכו LangGraph. הבחירה תלויה ב-use case: prototyping ו-business automation? CrewAI. Complex workflows ו-regulated industries? LangGraph.
בפרק הבא (פרק 10) תכירו את Google ADK ו-Pydantic AI — עוד שתי גישות שמשלימות את התמונה: Google ADK עם multimodal ו-GCP integration, ו-Pydantic AI עם type safety מקסימלי.
צ'קליסט — סיכום פרק 9
- מבין/ה את הפילוסופיה של CrewAI: סוכנים כאנשי צוות עם roles, goals, backstories
- יודע/ת להגדיר Agent עם role, goal, backstory, tools, ו-llm
- יודע/ת להגדיר Task עם description, expected_output, agent, ו-context
- בנית Crew שלם ובחרת Process type (Sequential / Hierarchical)
- בנית Content Creation Crew עם 3 agents שעובדים יחד
- יצרת custom tool עם
@tooldecorator - מבין/ה את ההבדל בין
@toolל-BaseTool - הגדרת delegation — יודע/ת מתי
allow_delegation=Trueומתי False - הפעלת memory ובדקת שה-crew זוכר מריצות קודמות
- השתמשת ב-
output_pydanticלקבלת structured output - בנית Flow עם
@startו-@listenשמחבר מספר crews - בנית לפחות real-world crew אחד (marketing, dev, או sales)
- יודע/ת לנהל עלויות — model mixing, max_iter, max_rpm
- עבדת על לפחות 3 מתוך 4 תרגילים
- עניתי על 4 מתוך 5 שאלות ב"בדוק את עצמך"