+
+
+ اللوحة اليسرى تجمع نقاط الحفظ حسب الفرع؛ التفرعات تتداخل تحت أبيها. اختيار نقطة حفظ يفتح لوحة التفاصيل مع بياناتها الوصفية وحالة الكيان وتقدم المهام. **Resume** يكمل التشغيل؛ **Fork** يبدأ فرعا جديدا.
+
+
+
+
+
+ لوحة التفاصيل تعرض منطقتين قابلتين للتحرير:
+
+ - **Inputs** — مدخلات الـ kickoff الأصلية، معبأة مسبقا وقابلة للتحرير.
+
+
+
+
+
+ - **مخرجات المهام** — مخرجات المهام المكتملة. تحرير مخرج والضغط على **Fork** يبطل المهام التابعة لتعاد بالسياق المعدل.
+
+
+
+
+
+
+
+
+
+
+
+
+تساعد هذه المصفوفة في تصور كيف تتوافق النهج المختلفة مع متطلبات متفاوتة للتعقيد والدقة. لنستكشف ما يعنيه كل ربع وكيف يوجه خياراتك المعمارية.
+
+## شرح مصفوفة التعقيد-الدقة
+
+### ما هو التعقيد؟
+
+في سياق تطبيقات CrewAI، يشير **التعقيد** إلى:
+
+- عدد الخطوات أو العمليات المميزة المطلوبة
+- تنوع المهام التي يجب تنفيذها
+- التبعيات المتبادلة بين المكونات المختلفة
+- الحاجة للمنطق الشرطي والتفرع
+- تطور سير العمل الكلي
+
+### ما هي الدقة؟
+
+**الدقة** في هذا السياق تشير إلى:
+
+- الدقة المطلوبة في المخرجات النهائية
+- الحاجة لنتائج منظمة وقابلة للتنبؤ
+- أهمية إمكانية التكرار
+- مستوى التحكم المطلوب في كل خطوة
+- تحمّل التباين في المخرجات
+
+### الأرباع الأربعة
+
+#### 1. تعقيد منخفض، دقة منخفضة
+
+**الخصائص:**
+- مهام بسيطة ومباشرة
+- تحمّل بعض التباين في المخرجات
+- عدد محدود من الخطوات
+- تطبيقات إبداعية أو استكشافية
+
+**النهج الموصى به:** Crews بسيطة مع عدد قليل من الـ Agents
+
+**أمثلة على حالات الاستخدام:**
+- إنشاء محتوى أساسي
+- العصف الذهني
+- مهام التلخيص البسيطة
+- مساعدة الكتابة الإبداعية
+
+#### 2. تعقيد منخفض، دقة عالية
+
+**الخصائص:**
+- سير عمل بسيطة تتطلب مخرجات دقيقة ومنظمة
+- حاجة لنتائج قابلة للتكرار
+- خطوات محدودة مع متطلبات دقة عالية
+- غالبًا تتضمن معالجة أو تحويل بيانات
+
+**النهج الموصى به:** Flows مع استدعاءات LLM مباشرة أو Crews بسيطة مع مخرجات منظمة
+
+**أمثلة على حالات الاستخدام:**
+- استخراج البيانات وتحويلها
+- ملء النماذج والتحقق منها
+- إنشاء محتوى منظم (JSON، XML)
+- مهام التصنيف البسيطة
+
+#### 3. تعقيد عالٍ، دقة منخفضة
+
+**الخصائص:**
+- عمليات متعددة المراحل بخطوات كثيرة
+- مخرجات إبداعية أو استكشافية
+- تفاعلات معقدة بين المكونات
+- تحمّل التباين في النتائج النهائية
+
+**النهج الموصى به:** Crews معقدة مع عدة Agents متخصصة
+
+**أمثلة على حالات الاستخدام:**
+- البحث والتحليل
+- خطوط إنتاج المحتوى
+- تحليل البيانات الاستكشافي
+- حل المشكلات الإبداعي
+
+#### 4. تعقيد عالٍ، دقة عالية
+
+**الخصائص:**
+- سير عمل معقدة تتطلب مخرجات منظمة
+- خطوات مترابطة متعددة مع متطلبات دقة صارمة
+- حاجة لمعالجة متطورة ونتائج دقيقة معًا
+- غالبًا تطبيقات حرجة المهمة
+
+**النهج الموصى به:** Flows تنسّق عدة Crews مع خطوات تحقق
+
+**أمثلة على حالات الاستخدام:**
+- أنظمة دعم القرار المؤسسية
+- خطوط معالجة بيانات معقدة
+- معالجة مستندات متعددة المراحل
+- تطبيقات الصناعات المنظمة
+
+## الاختيار بين Crews وFlows
+
+### متى تختار Crews
+
+الـ Crews مثالية عندما:
+
+1. **تحتاج ذكاء تعاوني** - عدة Agents بتخصصات مختلفة تحتاج للعمل معًا
+2. **المشكلة تتطلب تفكيرًا ناشئًا** - الحل يستفيد من منظورات ونُهج مختلفة
+3. **المهمة إبداعية أو تحليلية بالأساس** - العمل يتضمن بحثًا أو إنشاء محتوى أو تحليل
+4. **تقدّر القدرة على التكيف على الهيكل الصارم** - سير العمل يمكن أن يستفيد من استقلالية الـ Agent
+5. **تنسيق المخرجات يمكن أن يكون مرنًا نوعًا ما** - بعض التباين في هيكل المخرجات مقبول
+
+```python
+# Example: Research Crew for market analysis
+from crewai import Agent, Crew, Process, Task
+
+# Create specialized agents
+researcher = Agent(
+ role="Market Research Specialist",
+ goal="Find comprehensive market data on emerging technologies",
+ backstory="You are an expert at discovering market trends and gathering data."
+)
+
+analyst = Agent(
+ role="Market Analyst",
+ goal="Analyze market data and identify key opportunities",
+ backstory="You excel at interpreting market data and spotting valuable insights."
+)
+
+# Define their tasks
+research_task = Task(
+ description="Research the current market landscape for AI-powered healthcare solutions",
+ expected_output="Comprehensive market data including key players, market size, and growth trends",
+ agent=researcher
+)
+
+analysis_task = Task(
+ description="Analyze the market data and identify the top 3 investment opportunities",
+ expected_output="Analysis report with 3 recommended investment opportunities and rationale",
+ agent=analyst,
+ context=[research_task]
+)
+
+# Create the crew
+market_analysis_crew = Crew(
+ agents=[researcher, analyst],
+ tasks=[research_task, analysis_task],
+ process=Process.sequential,
+ verbose=True
+)
+
+# Run the crew
+result = market_analysis_crew.kickoff()
+```
+
+### متى تختار Flows
+
+الـ Flows مثالية عندما:
+
+1. **تحتاج تحكمًا دقيقًا في التنفيذ** - سير العمل يتطلب تسلسلًا دقيقًا وإدارة حالة
+2. **التطبيق له متطلبات حالة معقدة** - تحتاج لصيانة وتحويل الحالة عبر خطوات متعددة
+3. **تحتاج مخرجات منظمة وقابلة للتنبؤ** - التطبيق يتطلب نتائج متسقة ومنسّقة
+4. **سير العمل يتضمن منطقًا شرطيًا** - مسارات مختلفة يجب اتخاذها بناءً على نتائج وسيطة
+5. **تحتاج الجمع بين AI وكود إجرائي** - الحل يتطلب قدرات AI وبرمجة تقليدية معًا
+
+```python
+# Example: Customer Support Flow with structured processing
+from crewai.flow.flow import Flow, listen, router, start
+from pydantic import BaseModel
+from typing import List, Dict
+
+# Define structured state
+class SupportTicketState(BaseModel):
+ ticket_id: str = ""
+ customer_name: str = ""
+ issue_description: str = ""
+ category: str = ""
+ priority: str = "medium"
+ resolution: str = ""
+ satisfaction_score: int = 0
+
+class CustomerSupportFlow(Flow[SupportTicketState]):
+ @start()
+ def receive_ticket(self):
+ self.state.ticket_id = "TKT-12345"
+ self.state.customer_name = "Alex Johnson"
+ self.state.issue_description = "Unable to access premium features after payment"
+ return "Ticket received"
+
+ @listen(receive_ticket)
+ def categorize_ticket(self, _):
+ from crewai import LLM
+ llm = LLM(model="openai/gpt-4o-mini")
+
+ prompt = f"""
+ Categorize the following customer support issue into one of these categories:
+ - Billing
+ - Account Access
+ - Technical Issue
+ - Feature Request
+ - Other
+
+ Issue: {self.state.issue_description}
+
+ Return only the category name.
+ """
+
+ self.state.category = llm.call(prompt).strip()
+ return self.state.category
+
+ @router(categorize_ticket)
+ def route_by_category(self, category):
+ return category.lower().replace(" ", "_")
+
+ @listen("billing")
+ def handle_billing_issue(self):
+ self.state.priority = "high"
+ return "Billing issue handled"
+
+ @listen("account_access")
+ def handle_access_issue(self):
+ self.state.priority = "high"
+ return "Access issue handled"
+
+ @listen("billing", "account_access", "technical_issue", "feature_request", "other")
+ def resolve_ticket(self, resolution_info):
+ self.state.resolution = f"Issue resolved: {resolution_info}"
+ return self.state.resolution
+
+# Run the flow
+support_flow = CustomerSupportFlow()
+result = support_flow.kickoff()
+```
+
+### متى تجمع بين Crews وFlows
+
+أكثر التطبيقات تطورًا غالبًا تستفيد من الجمع بين Crews وFlows:
+
+1. **عمليات معقدة متعددة المراحل** - استخدم Flows لتنسيق العملية الكلية وCrews للمهام الفرعية المعقدة
+2. **تطبيقات تتطلب إبداعًا وهيكلاً معًا** - استخدم Crews للمهام الإبداعية وFlows للمعالجة المنظمة
+3. **تطبيقات AI مؤسسية** - استخدم Flows لإدارة الحالة وتدفق العمليات مع الاستفادة من Crews للعمل المتخصص
+
+```python
+# Example: Content Production Pipeline combining Crews and Flows
+from crewai.flow.flow import Flow, listen, start
+from crewai import Agent, Crew, Process, Task
+from pydantic import BaseModel
+from typing import List, Dict
+
+class ContentState(BaseModel):
+ topic: str = ""
+ target_audience: str = ""
+ content_type: str = ""
+ outline: Dict = {}
+ draft_content: str = ""
+ final_content: str = ""
+ seo_score: int = 0
+
+class ContentProductionFlow(Flow[ContentState]):
+ @start()
+ def initialize_project(self):
+ self.state.topic = "Sustainable Investing"
+ self.state.target_audience = "Millennial Investors"
+ self.state.content_type = "Blog Post"
+ return "Project initialized"
+
+ @listen(initialize_project)
+ def create_outline(self, _):
+ researcher = Agent(
+ role="Content Researcher",
+ goal=f"Research {self.state.topic} for {self.state.target_audience}",
+ backstory="You are an expert researcher with deep knowledge of content creation."
+ )
+
+ outliner = Agent(
+ role="Content Strategist",
+ goal=f"Create an engaging outline for a {self.state.content_type}",
+ backstory="You excel at structuring content for maximum engagement."
+ )
+
+ research_task = Task(
+ description=f"Research {self.state.topic} focusing on what would interest {self.state.target_audience}",
+ expected_output="Comprehensive research notes with key points and statistics",
+ agent=researcher
+ )
+
+ outline_task = Task(
+ description=f"Create an outline for a {self.state.content_type} about {self.state.topic}",
+ expected_output="Detailed content outline with sections and key points",
+ agent=outliner,
+ context=[research_task]
+ )
+
+ outline_crew = Crew(
+ agents=[researcher, outliner],
+ tasks=[research_task, outline_task],
+ process=Process.sequential,
+ verbose=True
+ )
+
+ result = outline_crew.kickoff()
+
+ import json
+ try:
+ self.state.outline = json.loads(result.raw)
+ except:
+ self.state.outline = {"sections": result.raw}
+
+ return "Outline created"
+
+ @listen(create_outline)
+ def write_content(self, _):
+ writer = Agent(
+ role="Content Writer",
+ goal=f"Write engaging content for {self.state.target_audience}",
+ backstory="You are a skilled writer who creates compelling content."
+ )
+
+ editor = Agent(
+ role="Content Editor",
+ goal="Ensure content is polished, accurate, and engaging",
+ backstory="You have a keen eye for detail and a talent for improving content."
+ )
+
+ writing_task = Task(
+ description=f"Write a {self.state.content_type} about {self.state.topic} following this outline: {self.state.outline}",
+ expected_output="Complete draft content in markdown format",
+ agent=writer
+ )
+
+ editing_task = Task(
+ description="Edit and improve the draft content for clarity, engagement, and accuracy",
+ expected_output="Polished final content in markdown format",
+ agent=editor,
+ context=[writing_task]
+ )
+
+ writing_crew = Crew(
+ agents=[writer, editor],
+ tasks=[writing_task, editing_task],
+ process=Process.sequential,
+ verbose=True
+ )
+
+ result = writing_crew.kickoff()
+ self.state.final_content = result.raw
+
+ return "Content created"
+
+ @listen(write_content)
+ def optimize_for_seo(self, _):
+ from crewai import LLM
+ llm = LLM(model="openai/gpt-4o-mini")
+
+ prompt = f"""
+ Analyze this content for SEO effectiveness for the keyword "{self.state.topic}".
+ Rate it on a scale of 1-100 and provide 3 specific recommendations for improvement.
+
+ Content: {self.state.final_content[:1000]}... (truncated for brevity)
+
+ Format your response as JSON with the following structure:
+ {{
+ "score": 85,
+ "recommendations": [
+ "Recommendation 1",
+ "Recommendation 2",
+ "Recommendation 3"
+ ]
+ }}
+ """
+
+ seo_analysis = llm.call(prompt)
+
+ import json
+ try:
+ analysis = json.loads(seo_analysis)
+ self.state.seo_score = analysis.get("score", 0)
+ return analysis
+ except:
+ self.state.seo_score = 50
+ return {"score": 50, "recommendations": ["Unable to parse SEO analysis"]}
+
+# Run the flow
+content_flow = ContentProductionFlow()
+result = content_flow.kickoff()
+```
+
+## إطار التقييم العملي
+
+لتحديد النهج الصحيح لحالة استخدامك المحددة، اتبع إطار التقييم التدريجي هذا:
+
+### الخطوة 1: تقييم التعقيد
+
+قيّم تعقيد تطبيقك على مقياس من 1-10 من خلال النظر في:
+
+1. **عدد الخطوات**: كم عدد العمليات المميزة المطلوبة؟
+ - 1-3 خطوات: تعقيد منخفض (1-3)
+ - 4-7 خطوات: تعقيد متوسط (4-7)
+ - 8+ خطوات: تعقيد عالٍ (8-10)
+
+2. **التبعيات المتبادلة**: ما مدى ترابط الأجزاء المختلفة؟
+ - تبعيات قليلة: تعقيد منخفض (1-3)
+ - بعض التبعيات: تعقيد متوسط (4-7)
+ - تبعيات معقدة كثيرة: تعقيد عالٍ (8-10)
+
+3. **المنطق الشرطي**: ما مقدار التفرع وصنع القرار المطلوب؟
+ - عملية خطية: تعقيد منخفض (1-3)
+ - بعض التفرع: تعقيد متوسط (4-7)
+ - أشجار قرار معقدة: تعقيد عالٍ (8-10)
+
+4. **المعرفة التخصصية**: ما مدى تخصص المعرفة المطلوبة؟
+ - معرفة عامة: تعقيد منخفض (1-3)
+ - بعض المعرفة المتخصصة: تعقيد متوسط (4-7)
+ - خبرة عميقة في مجالات متعددة: تعقيد عالٍ (8-10)
+
+احسب متوسط درجتك لتحديد التعقيد الكلي.
+
+### الخطوة 2: تقييم متطلبات الدقة
+
+قيّم متطلبات الدقة على مقياس من 1-10 من خلال النظر في:
+
+1. **هيكل المخرجات**: ما مدى التنظيم المطلوب في المخرجات؟
+ - نص حر: دقة منخفضة (1-3)
+ - شبه منظم: دقة متوسطة (4-7)
+ - منسّق بشكل صارم (JSON، XML): دقة عالية (8-10)
+
+2. **احتياجات الدقة**: ما أهمية الدقة الواقعية؟
+ - محتوى إبداعي: دقة منخفضة (1-3)
+ - محتوى معلوماتي: دقة متوسطة (4-7)
+ - معلومات حرجة: دقة عالية (8-10)
+
+3. **إمكانية التكرار**: ما مدى اتساق النتائج عبر التشغيلات؟
+ - التباين مقبول: دقة منخفضة (1-3)
+ - بعض الاتساق مطلوب: دقة متوسطة (4-7)
+ - تكرار دقيق مطلوب: دقة عالية (8-10)
+
+4. **تحمّل الأخطاء**: ما تأثير الأخطاء؟
+ - تأثير منخفض: دقة منخفضة (1-3)
+ - تأثير معتدل: دقة متوسطة (4-7)
+ - تأثير عالٍ: دقة عالية (8-10)
+
+احسب متوسط درجتك لتحديد متطلبات الدقة الكلية.
+
+### الخطوة 3: التعيين على المصفوفة
+
+ارسم درجات التعقيد والدقة على المصفوفة:
+
+- **تعقيد منخفض (1-4)، دقة منخفضة (1-4)**: Crews بسيطة
+- **تعقيد منخفض (1-4)، دقة عالية (5-10)**: Flows مع استدعاءات LLM مباشرة
+- **تعقيد عالٍ (5-10)، دقة منخفضة (1-4)**: Crews معقدة
+- **تعقيد عالٍ (5-10)، دقة عالية (5-10)**: Flows تنسّق Crews
+
+### الخطوة 4: مراعاة عوامل إضافية
+
+بالإضافة إلى التعقيد والدقة، ضع في اعتبارك:
+
+1. **وقت التطوير**: غالبًا ما تكون Crews أسرع في النماذج الأولية
+2. **احتياجات الصيانة**: توفر Flows قابلية صيانة أفضل على المدى الطويل
+3. **خبرة الفريق**: ضع في اعتبارك ألفة فريقك مع النُهج المختلفة
+4. **متطلبات التوسع**: عادةً ما تتوسع Flows بشكل أفضل للتطبيقات المعقدة
+5. **احتياجات التكامل**: ضع في اعتبارك كيف سيتكامل الحل مع الأنظمة الحالية
+
+## الخلاصة
+
+الاختيار بين Crews وFlows — أو الجمع بينهما — قرار معماري حاسم يؤثر على فعالية وقابلية صيانة وتوسع تطبيق CrewAI. من خلال تقييم حالة الاستخدام على أبعاد التعقيد والدقة، يمكنك اتخاذ قرارات مدروسة تتماشى مع متطلباتك المحددة.
+
+تذكر أن أفضل نهج غالبًا يتطور مع نضج تطبيقك. ابدأ بأبسط حل يلبي احتياجاتك، وكن مستعدًا لصقل بنيتك مع اكتساب الخبرة ووضوح المتطلبات.
+
+
+
+
+## الخطوة 2: فهم هيكل المشروع
+
+يستخدم الـ crew المبدئي المضمّن في مشروع Flow بنية Python/YAML الكلاسيكية. لاستخدام crew بنمط JSON-first داخل Flow، أنشئ `crew.jsonc` و `agents/*.jsonc` داخل مجلد الـ crew وحمّله عبر `crewai.project.load_crew` كما في [Flows](/ar/concepts/flows#building-your-crews).
+
+```
+guide_creator_flow/
+├── .gitignore
+├── pyproject.toml
+├── README.md
+├── .env
+└── src/
+ └── guide_creator_flow/
+ ├── __init__.py
+ ├── main.py
+ ├── crews/
+ │ └── poem_crew/
+ │ ├── config/
+ │ │ ├── agents.yaml
+ │ │ └── tasks.yaml
+ │ └── poem_crew.py
+ └── tools/
+ └── custom_tool.py
+```
+
+يوفر هذا الهيكل فصلاً واضحًا بين مكونات Flow المختلفة. سنعدّل هذا الهيكل لإنشاء Flow منشئ الدليل.
+
+## الخطوة 3: إضافة Crew كتابة المحتوى
+
+```bash
+crewai flow add-crew content-crew
+```
+
+## الخطوة 4: تهيئة Crew كتابة المحتوى
+
+سنهيئ crew كتابة المحتوى باستخدام JSONC. سنعرّف Agent للكتابة وAgent للمراجعة، ثم نحمّل `crew.jsonc` من خطوة Flow.
+
+1. أنشئ `src/guide_creator_flow/crews/content_crew/agents/content_writer.jsonc`:
+
+```jsonc
+{
+ "role": "Educational Content Writer",
+ "goal": "Create engaging, informative content that thoroughly explains the assigned topic and provides valuable insights to the reader.",
+ "backstory": "You are a talented educational writer who explains complex concepts in accessible language and organizes information clearly.",
+ "llm": "provider/model-id",
+ "settings": {
+ "verbose": true
+ }
+}
+```
+
+2. أنشئ `src/guide_creator_flow/crews/content_crew/agents/content_reviewer.jsonc`:
+
+```jsonc
+{
+ "role": "Educational Content Reviewer and Editor",
+ "goal": "Ensure content is accurate, comprehensive, well-structured, and consistent with previously written sections.",
+ "backstory": "You are a meticulous editor with an eye for detail, clarity, and coherence.",
+ "llm": "provider/model-id",
+ "settings": {
+ "verbose": true
+ }
+}
+```
+
+استبدل `provider/model-id` بالنموذج الذي تستخدمه، مثل `openai/gpt-4o` أو `gemini/gemini-2.0-flash-001` أو `anthropic/claude-sonnet-4-6`.
+
+3. أنشئ `src/guide_creator_flow/crews/content_crew/crew.jsonc`:
+
+```jsonc
+{
+ "name": "Content Crew",
+ "agents": ["content_writer", "content_reviewer"],
+ "tasks": [
+ {
+ "name": "write_section_task",
+ "description": "Write a comprehensive section on the topic: \"{section_title}\".\n\nSection description: {section_description}\nTarget audience: {audience_level} level learners\n\nYour content should begin with a brief introduction, explain key concepts clearly with examples, include practical applications where appropriate, end with a summary, and be approximately 500-800 words.\n\nPreviously written sections:\n{previous_sections}",
+ "expected_output": "A well-structured, comprehensive section in Markdown format that thoroughly explains the topic and is appropriate for the target audience.",
+ "agent": "content_writer",
+ "markdown": true
+ },
+ {
+ "name": "review_section_task",
+ "description": "Review and improve this section on \"{section_title}\":\n\n{draft_content}\n\nTarget audience: {audience_level} level learners\nPreviously written sections:\n{previous_sections}\n\nFix errors, improve clarity, verify consistency, enhance structure, and add missing key information.",
+ "expected_output": "An improved, polished version of the section that maintains the original structure but enhances clarity, accuracy, and consistency.",
+ "agent": "content_reviewer",
+ "context": ["write_section_task"],
+ "markdown": true
+ }
+ ],
+ "process": "sequential",
+ "verbose": true
+}
+```
+
+4. استبدل `src/guide_creator_flow/crews/content_crew/content_crew.py` بمحمل صغير:
+
+```python
+from pathlib import Path
+
+from crewai.project import load_crew
+
+
+def kickoff_content_crew(inputs: dict):
+ crew, default_inputs = load_crew(Path(__file__).with_name("crew.jsonc"))
+ return crew.kickoff(inputs={**default_inputs, **inputs})
+```
+
+## الخطوة 5: إنشاء Flow
+
+الآن الجزء المثير - إنشاء Flow الذي سينسّق عملية إنشاء الدليل بالكامل. راجع الملف الإنجليزي الأصلي للكود الكامل لـ `main.py` حيث أن الكود يبقى كما هو.
+
+## الخطوة 6: إعداد متغيرات البيئة
+
+أنشئ ملف `.env` في جذر مشروعك بمفاتيح API. راجع [دليل إعداد LLM](/ar/concepts/llms#setting-up-your-llm) لتفاصيل تهيئة المزود.
+
+```sh .env
+OPENAI_API_KEY=your_openai_api_key
+# or
+GEMINI_API_KEY=your_gemini_api_key
+# or
+ANTHROPIC_API_KEY=your_anthropic_api_key
+```
+
+## الخطوة 7: تثبيت التبعيات
+
+```bash
+crewai install
+```
+
+## الخطوة 8: تشغيل Flow
+
+```bash
+crewai run
+```
+
+عند تشغيل هذا الأمر، ستشاهد Flow يعمل:
+1. سيطلب منك موضوعًا ومستوى الجمهور
+2. سينشئ مخططًا منظمًا لدليلك
+3. سيعالج كل قسم مع تعاون الكاتب والمراجع
+4. أخيرًا سيجمع كل شيء في دليل شامل
+
+## الخطوة 9: تصوير Flow
+
+```bash
+crewai flow plot
+```
+
+سينشئ ملف HTML يوضح هيكل Flow بما في ذلك العلاقات بين الخطوات المختلفة.
+
+## الخطوة 10: مراجعة المخرجات
+
+بمجرد اكتمال Flow، ستجد ملفين في مجلد `output`:
+
+1. `guide_outline.json`: يحتوي على المخطط المنظم للدليل
+2. `complete_guide.md`: الدليل الشامل بجميع الأقسام
+
+## الميزات الرئيسية الموضّحة
+
+يوضح Flow منشئ الدليل عدة ميزات قوية لـ CrewAI:
+
+1. **تفاعل المستخدم**: يجمع Flow مدخلات مباشرة من المستخدم
+2. **استدعاءات LLM المباشرة**: يستخدم فئة LLM لتفاعلات AI فعّالة وأحادية الغرض
+3. **بيانات منظمة مع Pydantic**: يستخدم نماذج Pydantic لضمان سلامة الأنواع
+4. **معالجة تسلسلية مع سياق**: يكتب الأقسام بالترتيب ويوفر الأقسام السابقة كسياق
+5. **Crews متعددة الـ Agents**: يستفيد من Agents متخصصة (كاتب ومراجع) لإنشاء المحتوى
+6. **إدارة الحالة**: يحافظ على الحالة عبر خطوات العملية المختلفة
+7. **بنية قائمة على الأحداث**: يستخدم مزخرف `@listen` للاستجابة للأحداث
+
+## الخطوات التالية
+
+1. جرّب هياكل Flow أكثر تعقيدًا وأنماطًا
+2. جرّب استخدام `@router()` لإنشاء فروع شرطية
+3. استكشف دوال `and_` و`or_` لتنفيذ متوازٍ أكثر تعقيدًا
+4. اربط Flow بواجهات API خارجية وقواعد بيانات وواجهات مستخدم
+5. ادمج عدة Crews متخصصة في Flow واحد
+6. أنشئ تطبيقات دردشة متعددة الجولات مع [تدفقات المحادثة](/ar/guides/flows/conversational-flows) (`kickoff` لكل رسالة، `ChatSession`، تأجيل التتبع)
+
+
+ + صمم Agents، ونسّق Crews، وأتمت Flows مع حواجز حماية وذاكرة ومعرفة ومراقبة مدمجة. +
+
+
+
+توفر Flows:
+- **إدارة الحالة**: حفظ البيانات عبر الخطوات والتنفيذات.
+- **تنفيذ قائم على الأحداث**: تشغيل إجراءات بناءً على أحداث أو مدخلات خارجية.
+- **التحكم في التدفق**: استخدام المنطق الشرطي والحلقات والتفرع.
+
+### 2. Crews: الذكاء
+
+
+
+
+توفر Crews:
+- **Agents بأدوار محددة**: Agents متخصصة بأهداف وأدوات محددة.
+- **تعاون مستقل**: تعمل الـ Agents معًا لحل المهام.
+- **تفويض المهام**: يتم تعيين المهام وتنفيذها بناءً على قدرات الـ Agent.
+
+## كيف يعمل الكل معًا
+
+1. يبدأ **Flow** حدثًا أو يشغّل عملية.
+2. يدير **Flow** الحالة ويقرر ما يجب فعله بعد ذلك.
+3. يفوّض **Flow** مهمة معقدة إلى **Crew**.
+4. تتعاون Agents الـ **Crew** لإكمال المهمة.
+5. يعيد **Crew** النتيجة إلى **Flow**.
+6. يستمر **Flow** في التنفيذ بناءً على النتيجة.
+
+## الميزات الرئيسية
+
+
+
+
+
+
+
+
+
+
+بالإضافة إلى ذلك، يمكنك عرض رسم بياني لتنفيذ التتبع، الذي يوضح تدفق التحكم والبيانات للتتبع.
+
+
+
+
+
+## المراجع
+
+- [Datadog LLM Observability](https://www.datadoghq.com/product/llm-observability/)
+- [التجهيز التلقائي لـ CrewAI من Datadog LLM Observability](https://docs.datadoghq.com/llm_observability/instrumentation/auto_instrumentation?tab=python#crew-ai)
diff --git a/docs/v1.15.13/ar/observability/galileo.mdx b/docs/v1.15.13/ar/observability/galileo.mdx
new file mode 100644
index 0000000000..9c51f2306c
--- /dev/null
+++ b/docs/v1.15.13/ar/observability/galileo.mdx
@@ -0,0 +1,86 @@
+---
+title: Galileo
+description: تكامل Galileo مع CrewAI للتتبع والتقييم
+icon: telescope
+mode: "wide"
+---
+
+## نظرة عامة
+
+يوضح هذا الدليل كيفية دمج **Galileo** مع **CrewAI** للتتبع الشامل وهندسة التقييم. بنهاية هذا الدليل، ستتمكن من تتبع وكلاء CrewAI ومراقبة أدائهم وتقييم سلوكهم باستخدام منصة المراقبة القوية من Galileo.
+
+> **ما هو Galileo؟** [Galileo](https://galileo.ai) هو منصة تقييم ومراقبة للذكاء الاصطناعي توفر تتبعاً شاملاً وتقييماً ومراقبة لتطبيقات الذكاء الاصطناعي. تمكّن الفرق من التقاط البيانات الحقيقية وإنشاء حواجز قوية وتشغيل تجارب منهجية مع تتبع تجارب مدمج وتحليلات أداء.
+
+## البدء
+
+يتبع هذا البرنامج التعليمي [البدء السريع مع CrewAI](/ar/quickstart) ويوضح كيفية إضافة [CrewAIEventListener](https://v2docs.galileo.ai/sdk-api/python/reference/handlers/crewai/handler) من Galileo كمعالج أحداث.
+
+> **ملاحظة** يفترض هذا البرنامج التعليمي أنك أكملت [البدء السريع مع CrewAI](/ar/quickstart).
+
+### الخطوة 1: تثبيت الاعتماديات
+
+ثبّت الاعتماديات المطلوبة لتطبيقك:
+
+```bash
+uv add galileo
+```
+
+### الخطوة 2: أضف إلى ملف .env من [البدء السريع مع CrewAI](/ar/quickstart)
+
+```bash
+# Your Galileo API key
+GALILEO_API_KEY="your-galileo-api-key"
+
+# Your Galileo project name
+GALILEO_PROJECT="your-galileo-project-name"
+
+# The name of the Log stream you want to use for logging
+GALILEO_LOG_STREAM="your-galileo-log-stream "
+```
+
+### الخطوة 3: إضافة مستمع أحداث Galileo
+
+لتفعيل التسجيل مع Galileo، تحتاج إلى إنشاء مثيل من `CrewAIEventListener`. استورد حزمة معالج CrewAI من Galileo بإضافة الكود التالي في أعلى ملف main.py:
+
+```python
+from galileo.handlers.crewai.handler import CrewAIEventListener
+```
+
+في بداية دالة التشغيل، أنشئ مستمع الأحداث:
+
+```python
+def run():
+ # Create the event listener
+ CrewAIEventListener()
+ # The rest of your existing code goes here
+```
+
+عند إنشاء مثيل المستمع، يتم تسجيله تلقائياً مع CrewAI.
+
+### الخطوة 4: شغّل طاقمك
+
+شغّل طاقمك باستخدام CrewAI CLI:
+
+```bash
+crewai run
+```
+
+### الخطوة 5: عرض التتبعات في Galileo
+
+بمجرد انتهاء طاقمك، سيتم تفريغ التتبعات وستظهر في Galileo.
+
+
+
+## فهم تكامل Galileo
+
+يتكامل Galileo مع CrewAI عن طريق تسجيل مستمع أحداث يلتقط أحداث تنفيذ الطاقم (مثل إجراءات الوكلاء واستدعاءات الأدوات واستجابات النماذج) ويعيد توجيهها إلى Galileo للمراقبة والتقييم.
+
+### فهم مستمع الأحداث
+
+إنشاء مثيل `CrewAIEventListener()` هو كل ما يلزم لتفعيل Galileo لتشغيل CrewAI. عند الإنشاء، يقوم المستمع بـ:
+
+- التسجيل تلقائياً مع CrewAI
+- قراءة إعدادات Galileo من متغيرات البيئة
+- تسجيل جميع بيانات التشغيل في مشروع Galileo وتدفق السجل المحدد بواسطة `GALILEO_PROJECT` و `GALILEO_LOG_STREAM`
+
+لا يلزم أي إعداد إضافي أو تغييرات في الكود.
diff --git a/docs/v1.15.13/ar/observability/langdb.mdx b/docs/v1.15.13/ar/observability/langdb.mdx
new file mode 100644
index 0000000000..42726faaaf
--- /dev/null
+++ b/docs/v1.15.13/ar/observability/langdb.mdx
@@ -0,0 +1,167 @@
+---
+title: تكامل LangDB
+description: إدارة وتأمين وتحسين سير عمل CrewAI مع بوابة LangDB AI — الوصول إلى أكثر من 350 نموذجاً وتوجيه تلقائي وتحسين التكاليف ومراقبة كاملة.
+icon: database
+mode: "wide"
+---
+
+# مقدمة
+
+توفر [بوابة LangDB AI](https://langdb.ai) واجهات API متوافقة مع OpenAI للاتصال بنماذج لغة كبيرة متعددة وتعمل كمنصة مراقبة تجعل تتبع سير عمل CrewAI شاملاً وسهلاً مع توفير الوصول إلى أكثر من 350 نموذج لغة. مع استدعاء `init()` واحد، يتم التقاط جميع تفاعلات الوكلاء وتنفيذ المهام واستدعاءات LLM، مما يوفر مراقبة شاملة وبنية تحتية جاهزة للإنتاج لتطبيقاتك.
+
+
+
+
+
+**تحقق من:** [عرض مثال التتبع المباشر](https://app.langdb.ai/sharing/threads/3becbfed-a1be-ae84-ea3c-4942867a3e22)
+
+## الميزات
+
+### قدرات بوابة AI
+- **الوصول إلى أكثر من 350 LLM**: الاتصال بجميع نماذج اللغة الرئيسية من خلال تكامل واحد
+- **النماذج الافتراضية**: إنشاء إعدادات نماذج مخصصة مع معاملات وقواعد توجيه محددة
+- **MCP الافتراضي**: تفعيل التوافق والتكامل مع أنظمة MCP لتعزيز اتصال الوكلاء
+- **حواجز الحماية**: تنفيذ تدابير السلامة وضوابط الامتثال لسلوك الوكلاء
+
+### المراقبة والتتبع
+- **تتبع تلقائي**: استدعاء `init()` واحد يلتقط جميع تفاعلات CrewAI
+- **رؤية شاملة**: مراقبة سير عمل الوكلاء من البداية إلى النهاية
+- **تتبع استخدام الأدوات**: تتبع الأدوات التي يستخدمها الوكلاء ونتائجها
+- **مراقبة استدعاءات النماذج**: رؤى مفصلة لتفاعلات LLM
+- **تحليلات الأداء**: مراقبة زمن الاستجابة واستخدام الرموز والتكاليف
+- **دعم التصحيح**: تنفيذ خطوة بخطوة لاستكشاف الأخطاء
+- **المراقبة في الوقت الفعلي**: لوحة معلومات التتبعات والمقاييس الحية
+
+## تعليمات الإعداد
+
+
+
+
+### ما ستراه
+
+- **تفاعلات الوكلاء**: التدفق الكامل لمحادثات الوكلاء وتسليم المهام
+- **استخدام الأدوات**: الأدوات التي تم استدعاؤها ومدخلاتها ومخرجاتها
+- **استدعاءات النماذج**: تفاعلات LLM المفصلة مع المطالبات والاستجابات
+- **مقاييس الأداء**: تتبع زمن الاستجابة واستخدام الرموز والتكاليف
+- **الجدول الزمني للتنفيذ**: عرض خطوة بخطوة لسير العمل بالكامل
+
+## استكشاف الأخطاء وإصلاحها
+
+### المشاكل الشائعة
+
+- **عدم ظهور تتبعات**: تأكد من استدعاء `init()` قبل أي استيرادات CrewAI
+- **أخطاء المصادقة**: تحقق من مفتاح API ومعرف المشروع في LangDB
+
+## الموارد
+
+
+
+
+
+ + تقييم السجلات الملتقطة تلقائياً من واجهة المستخدم بناءً على المرشحات والعينات +
++ استخدام التقييم البشري أو التصنيف لتقييم جودة سجلاتك +
++ تقييم أي مكون من تتبعك أو سجلك للحصول على رؤى حول سلوك وكيلك +
+
+
+
+
+## استكشاف الأخطاء وإصلاحها
+
+### المشاكل الشائعة
+
+- **عدم ظهور تتبعات**: تأكد من صحة مفتاح API ومعرف المستودع
+- تأكد من استدعاء **`instrument_crewai()`** **_قبل_** تشغيل طاقمك
+- عيّن `debug=True` في استدعاء `instrument_crewai()` لإظهار أي أخطاء داخلية:
+
+ ```python
+ instrument_crewai(logger, debug=True)
+ ```
+- أعدّ وكلاءك مع `verbose=True` لالتقاط سجلات مفصلة
+- تحقق مرة أخرى من أن `instrument_crewai()` يُستدعى **قبل** إنشاء أو تنفيذ الوكلاء
+
+## الموارد
+
+
+
+
+
+
+
+
+### الميزات
+
+- **لوحة معلومات التحليلات**: راقب صحة وأداء وكلائك من خلال لوحات معلومات تفصيلية تتتبع المقاييس والتكاليف وتفاعلات المستخدمين.
+- **SDK مراقبة أصلي لـ OpenTelemetry**: حزم SDK محايدة للمورد لإرسال التتبعات والمقاييس إلى أدوات المراقبة الحالية مثل Grafana وDataDog وغيرها.
+- **تتبع التكاليف للنماذج المخصصة والمعدّلة**: خصّص تقديرات التكلفة لنماذج محددة باستخدام ملفات تسعير مخصصة لوضع ميزانية دقيقة.
+- **لوحة مراقبة الاستثناءات**: اكتشف وحل المشكلات بسرعة من خلال تتبع الاستثناءات والأخطاء الشائعة بلوحة مراقبة.
+- **الامتثال والأمان**: اكتشف التهديدات المحتملة مثل الألفاظ البذيئة وتسريبات المعلومات الشخصية.
+- **كشف حقن الموجهات**: حدد حقن الكود المحتمل وتسريبات الأسرار.
+- **إدارة مفاتيح API والأسرار**: تعامل مع مفاتيح API لنماذج LLM وأسرارك مركزياً بأمان، مع تجنب الممارسات غير الآمنة.
+- **إدارة الموجهات**: أدر وأصدر موجهات الوكلاء باستخدام PromptHub للوصول المتسق والسهل عبر الوكلاء.
+- **ساحة تجربة النماذج**: اختبر وقارن نماذج مختلفة لوكلاء CrewAI قبل النشر.
+
+## تعليمات الإعداد
+
+
+
+
+
+
+
+
+يوفر Opik دعماً شاملاً لكل مرحلة من مراحل تطوير تطبيق CrewAI الخاص بك:
+
+- **تسجيل التتبعات والنطاقات**: تتبع تلقائي لاستدعاءات LLM ومنطق التطبيق لتصحيح الأخطاء وتحليل أنظمة التطوير والإنتاج. أضف التعليقات التوضيحية يدوياً أو برمجياً، واعرض وقارن الاستجابات عبر المشاريع.
+- **تقييم أداء تطبيق LLM**: قيّم وفقاً لمجموعة اختبار مخصصة وشغّل مقاييس تقييم مدمجة أو حدد مقاييسك الخاصة في SDK أو واجهة المستخدم.
+- **الاختبار ضمن خط أنابيب CI/CD**: أنشئ خطوط أساس أداء موثوقة مع اختبارات وحدة LLM من Opik، المبنية على PyTest. شغّل تقييمات عبر الإنترنت للمراقبة المستمرة في الإنتاج.
+- **مراقبة وتحليل بيانات الإنتاج**: افهم أداء نماذجك على بيانات غير مرئية في الإنتاج وأنشئ مجموعات بيانات لتكرارات التطوير الجديدة.
+
+## الإعداد
+يوفر Comet نسخة مستضافة من منصة Opik، أو يمكنك تشغيل المنصة محلياً.
+
+لاستخدام النسخة المستضافة، ما عليك سوى [إنشاء حساب Comet مجاني](https://www.comet.com/signup?utm_medium=github&utm_source=crewai_docs) والحصول على مفتاح API الخاص بك.
+
+لتشغيل منصة Opik محلياً، راجع [دليل التثبيت](https://www.comet.com/docs/opik/self-host/overview/) لمزيد من المعلومات.
+
+في هذا الدليل سنستخدم مثال البدء السريع الخاص بـ CrewAI.
+
+
+
+
+
+## مقدمة
+
+يعزز Portkey إمكانيات CrewAI بميزات جاهزة للإنتاج، محولاً طواقم الوكلاء التجريبية إلى أنظمة متينة من خلال توفير:
+
+- **مراقبة كاملة** لكل خطوة وكيل واستخدام أداة وتفاعل
+- **موثوقية مدمجة** مع آليات الاحتياط وإعادة المحاولة وموازنة الأحمال
+- **تتبع التكاليف وتحسينها** لإدارة إنفاقك على الذكاء الاصطناعي
+- **الوصول إلى أكثر من 200 نموذج LLM** من خلال تكامل واحد
+- **حواجز الحماية** للحفاظ على سلوك الوكلاء آمناً ومتوافقاً
+- **موجهات مُتحكم بإصداراتها** لأداء وكلاء متسق
+
+
+### التثبيت والإعداد
+
+
+
+
+توفر التتبعات عرضاً هرمياً لتنفيذ طاقمك، يظهر تسلسل استدعاءات LLM واستدعاءات الأدوات وانتقالات الحالة.
+
+```python
+# Add trace_id to enable hierarchical tracing in Portkey
+portkey_llm = LLM(
+ model="gpt-4o",
+ base_url=PORTKEY_GATEWAY_URL,
+ api_key="dummy",
+ extra_headers=createHeaders(
+ api_key="YOUR_PORTKEY_API_KEY",
+ virtual_key="YOUR_OPENAI_VIRTUAL_KEY",
+ trace_id="unique-session-id" # Add unique trace ID
+ )
+)
+```
+
+
+
+يسجّل Portkey كل تفاعل مع نماذج LLM، بما في ذلك:
+
+- حمولات الطلب والاستجابة الكاملة
+- مقاييس زمن الاستجابة واستخدام الرموز المميزة
+- حسابات التكلفة
+- استدعاءات الأدوات وتنفيذ الدوال
+
+يمكن تصفية جميع السجلات حسب البيانات الوصفية ومعرّفات التتبع والنماذج والمزيد، مما يسهّل تصحيح أخطاء عمليات تشغيل طاقم محددة.
+
+
+
+يوفر Portkey لوحات معلومات مدمجة تساعدك على:
+
+- تتبع التكلفة واستخدام الرموز المميزة عبر جميع عمليات تشغيل الطاقم
+- تحليل مقاييس الأداء مثل زمن الاستجابة ومعدلات النجاح
+- تحديد الاختناقات في سير عمل الوكلاء
+- مقارنة تكوينات الطاقم ونماذج LLM المختلفة
+
+يمكنك تصفية وتقسيم جميع المقاييس حسب بيانات وصفية مخصصة لتحليل أنواع طواقم أو مجموعات مستخدمين أو حالات استخدام محددة.
+
+
+
+أضف بيانات وصفية مخصصة لتكوين LLM في CrewAI لتمكين تصفية وتقسيم قوية:
+
+```python
+portkey_llm = LLM(
+ model="gpt-4o",
+ base_url=PORTKEY_GATEWAY_URL,
+ api_key="dummy",
+ extra_headers=createHeaders(
+ api_key="YOUR_PORTKEY_API_KEY",
+ virtual_key="YOUR_OPENAI_VIRTUAL_KEY",
+ metadata={
+ "crew_type": "research_crew",
+ "environment": "production",
+ "_user": "user_123", # Special _user field for user analytics
+ "request_source": "mobile_app"
+ }
+ )
+)
+```
+
+يمكن استخدام هذه البيانات الوصفية لتصفية السجلات والتتبعات والمقاييس في لوحة تحكم Portkey، مما يتيح لك تحليل عمليات تشغيل طاقم أو مستخدمين أو بيئات محددة.
+
+
+
+يمكّن هذا:
+- تتبع التكاليف والميزانية لكل مستخدم
+- تحليلات مستخدم مخصصة
+- مقاييس على مستوى الفريق أو المؤسسة
+- مراقبة خاصة بالبيئة (التجريب مقابل الإنتاج)
+
+
+
+
+
+
+
+
+
+
+
+
+ وثائق CrewAI الرسمية
+احصل على إرشادات مخصصة لتنفيذ هذا التكامل
+
+
+
+
+
+ The left panel groups checkpoints by branch; forks nest under their parent. Selecting a checkpoint opens the detail panel with metadata, entity state, and task progress. **Resume** continues the run; **Fork** starts a new branch.
+
+
+
+
+
+ The detail panel exposes two editable areas:
+
+ - **Inputs** — original kickoff inputs, pre-filled and editable.
+
+
+
+
+
+ - **Task outputs** — outputs of completed tasks. Editing an output and hitting **Fork** invalidates downstream tasks so they re-run against the modified context.
+
+
+
+
+
+
+
+
+
+ stop parameter, you can simply omit it from your LLM call:
+
+ ```python
+ from crewai import LLM
+ import os
+
+ os.environ["OPENAI_API_KEY"] = "
+
+
+This matrix helps visualize how different approaches align with varying requirements for complexity and precision. Let's explore what each quadrant means and how it guides your architectural choices.
+
+## The Complexity-Precision Matrix Explained
+
+### What is Complexity?
+
+In the context of CrewAI applications, **complexity** refers to:
+
+- The number of distinct steps or operations required
+- The diversity of tasks that need to be performed
+- The interdependencies between different components
+- The need for conditional logic and branching
+- The sophistication of the overall workflow
+
+### What is Precision?
+
+**Precision** in this context refers to:
+
+- The accuracy required in the final output
+- The need for structured, predictable results
+- The importance of reproducibility
+- The level of control needed over each step
+- The tolerance for variation in outputs
+
+### The Four Quadrants
+
+#### 1. Low Complexity, Low Precision
+
+**Characteristics:**
+- Simple, straightforward tasks
+- Tolerance for some variation in outputs
+- Limited number of steps
+- Creative or exploratory applications
+
+**Recommended Approach:** Simple Crews with minimal agents
+
+**Example Use Cases:**
+- Basic content generation
+- Idea brainstorming
+- Simple summarization tasks
+- Creative writing assistance
+
+#### 2. Low Complexity, High Precision
+
+**Characteristics:**
+- Simple workflows that require exact, structured outputs
+- Need for reproducible results
+- Limited steps but high accuracy requirements
+- Often involves data processing or transformation
+
+**Recommended Approach:** Flows with direct LLM calls or simple Crews with structured outputs
+
+**Example Use Cases:**
+- Data extraction and transformation
+- Form filling and validation
+- Structured content generation (JSON, XML)
+- Simple classification tasks
+
+#### 3. High Complexity, Low Precision
+
+**Characteristics:**
+- Multi-stage processes with many steps
+- Creative or exploratory outputs
+- Complex interactions between components
+- Tolerance for variation in final results
+
+**Recommended Approach:** Complex Crews with multiple specialized agents
+
+**Example Use Cases:**
+- Research and analysis
+- Content creation pipelines
+- Exploratory data analysis
+- Creative problem-solving
+
+#### 4. High Complexity, High Precision
+
+**Characteristics:**
+- Complex workflows requiring structured outputs
+- Multiple interdependent steps with strict accuracy requirements
+- Need for both sophisticated processing and precise results
+- Often mission-critical applications
+
+**Recommended Approach:** Flows orchestrating multiple Crews with validation steps
+
+**Example Use Cases:**
+- Enterprise decision support systems
+- Complex data processing pipelines
+- Multi-stage document processing
+- Regulated industry applications
+
+## Choosing Between Crews and Flows
+
+### When to Choose Crews
+
+Crews are ideal when:
+
+1. **You need collaborative intelligence** - Multiple agents with different specializations need to work together
+2. **The problem requires emergent thinking** - The solution benefits from different perspectives and approaches
+3. **The task is primarily creative or analytical** - The work involves research, content creation, or analysis
+4. **You value adaptability over strict structure** - The workflow can benefit from agent autonomy
+5. **The output format can be somewhat flexible** - Some variation in output structure is acceptable
+
+```python
+# Example: Research Crew for market analysis
+from crewai import Agent, Crew, Process, Task
+
+# Create specialized agents
+researcher = Agent(
+ role="Market Research Specialist",
+ goal="Find comprehensive market data on emerging technologies",
+ backstory="You are an expert at discovering market trends and gathering data."
+)
+
+analyst = Agent(
+ role="Market Analyst",
+ goal="Analyze market data and identify key opportunities",
+ backstory="You excel at interpreting market data and spotting valuable insights."
+)
+
+# Define their tasks
+research_task = Task(
+ description="Research the current market landscape for AI-powered healthcare solutions",
+ expected_output="Comprehensive market data including key players, market size, and growth trends",
+ agent=researcher
+)
+
+analysis_task = Task(
+ description="Analyze the market data and identify the top 3 investment opportunities",
+ expected_output="Analysis report with 3 recommended investment opportunities and rationale",
+ agent=analyst,
+ context=[research_task]
+)
+
+# Create the crew
+market_analysis_crew = Crew(
+ agents=[researcher, analyst],
+ tasks=[research_task, analysis_task],
+ process=Process.sequential,
+ verbose=True
+)
+
+# Run the crew
+result = market_analysis_crew.kickoff()
+```
+
+### When to Choose Flows
+
+Flows are ideal when:
+
+1. **You need precise control over execution** - The workflow requires exact sequencing and state management
+2. **The application has complex state requirements** - You need to maintain and transform state across multiple steps
+3. **You need structured, predictable outputs** - The application requires consistent, formatted results
+4. **The workflow involves conditional logic** - Different paths need to be taken based on intermediate results
+5. **You need to combine AI with procedural code** - The solution requires both AI capabilities and traditional programming
+
+```python
+# Example: Customer Support Flow with structured processing
+from crewai.flow.flow import Flow, listen, or_, router, start
+from pydantic import BaseModel
+from typing import List, Dict
+
+# Define structured state
+class SupportTicketState(BaseModel):
+ ticket_id: str = ""
+ customer_name: str = ""
+ issue_description: str = ""
+ category: str = ""
+ priority: str = "medium"
+ resolution: str = ""
+ satisfaction_score: int = 0
+
+class CustomerSupportFlow(Flow[SupportTicketState]):
+ @start()
+ def receive_ticket(self):
+ # In a real app, this might come from an API
+ self.state.ticket_id = "TKT-12345"
+ self.state.customer_name = "Alex Johnson"
+ self.state.issue_description = "Unable to access premium features after payment"
+ return "Ticket received"
+
+ @listen(receive_ticket)
+ def categorize_ticket(self, _):
+ # Use a direct LLM call for categorization
+ from crewai import LLM
+ llm = LLM(model="openai/gpt-4o-mini")
+
+ prompt = f"""
+ Categorize the following customer support issue into one of these categories:
+ - Billing
+ - Account Access
+ - Technical Issue
+ - Feature Request
+ - Other
+
+ Issue: {self.state.issue_description}
+
+ Return only the category name.
+ """
+
+ self.state.category = llm.call(prompt).strip()
+ return self.state.category
+
+ @router(categorize_ticket)
+ def route_by_category(self, category):
+ # Route to different handlers based on category
+ return category.lower().replace(" ", "_")
+
+ @listen("billing")
+ def handle_billing_issue(self):
+ # Handle billing-specific logic
+ self.state.priority = "high"
+ # More billing-specific processing...
+ return "Billing issue handled"
+
+ @listen("account_access")
+ def handle_access_issue(self):
+ # Handle access-specific logic
+ self.state.priority = "high"
+ # More access-specific processing...
+ return "Access issue handled"
+
+ # Additional category handlers...
+
+ @listen(or_("billing", "account_access", "technical_issue", "feature_request", "other"))
+ def resolve_ticket(self, resolution_info):
+ # Final resolution step
+ self.state.resolution = f"Issue resolved: {resolution_info}"
+ return self.state.resolution
+
+# Run the flow
+support_flow = CustomerSupportFlow()
+result = support_flow.kickoff()
+```
+
+### When to Combine Crews and Flows
+
+The most sophisticated applications often benefit from combining Crews and Flows:
+
+1. **Complex multi-stage processes** - Use Flows to orchestrate the overall process and Crews for complex subtasks
+2. **Applications requiring both creativity and structure** - Use Crews for creative tasks and Flows for structured processing
+3. **Enterprise-grade AI applications** - Use Flows to manage state and process flow while leveraging Crews for specialized work
+
+```python
+# Example: Content Production Pipeline combining Crews and Flows
+from crewai.flow.flow import Flow, listen, start
+from crewai import Agent, Crew, Process, Task
+from pydantic import BaseModel
+from typing import List, Dict
+
+class ContentState(BaseModel):
+ topic: str = ""
+ target_audience: str = ""
+ content_type: str = ""
+ outline: Dict = {}
+ draft_content: str = ""
+ final_content: str = ""
+ seo_score: int = 0
+
+class ContentProductionFlow(Flow[ContentState]):
+ @start()
+ def initialize_project(self):
+ # Set initial parameters
+ self.state.topic = "Sustainable Investing"
+ self.state.target_audience = "Millennial Investors"
+ self.state.content_type = "Blog Post"
+ return "Project initialized"
+
+ @listen(initialize_project)
+ def create_outline(self, _):
+ # Use a research crew to create an outline
+ researcher = Agent(
+ role="Content Researcher",
+ goal=f"Research {self.state.topic} for {self.state.target_audience}",
+ backstory="You are an expert researcher with deep knowledge of content creation."
+ )
+
+ outliner = Agent(
+ role="Content Strategist",
+ goal=f"Create an engaging outline for a {self.state.content_type}",
+ backstory="You excel at structuring content for maximum engagement."
+ )
+
+ research_task = Task(
+ description=f"Research {self.state.topic} focusing on what would interest {self.state.target_audience}",
+ expected_output="Comprehensive research notes with key points and statistics",
+ agent=researcher
+ )
+
+ outline_task = Task(
+ description=f"Create an outline for a {self.state.content_type} about {self.state.topic}",
+ expected_output="Detailed content outline with sections and key points",
+ agent=outliner,
+ context=[research_task]
+ )
+
+ outline_crew = Crew(
+ agents=[researcher, outliner],
+ tasks=[research_task, outline_task],
+ process=Process.sequential,
+ verbose=True
+ )
+
+ # Run the crew and store the result
+ result = outline_crew.kickoff()
+
+ # Parse the outline (in a real app, you might use a more robust parsing approach)
+ import json
+ try:
+ self.state.outline = json.loads(result.raw)
+ except:
+ # Fallback if not valid JSON
+ self.state.outline = {"sections": result.raw}
+
+ return "Outline created"
+
+ @listen(create_outline)
+ def write_content(self, _):
+ # Use a writing crew to create the content
+ writer = Agent(
+ role="Content Writer",
+ goal=f"Write engaging content for {self.state.target_audience}",
+ backstory="You are a skilled writer who creates compelling content."
+ )
+
+ editor = Agent(
+ role="Content Editor",
+ goal="Ensure content is polished, accurate, and engaging",
+ backstory="You have a keen eye for detail and a talent for improving content."
+ )
+
+ writing_task = Task(
+ description=f"Write a {self.state.content_type} about {self.state.topic} following this outline: {self.state.outline}",
+ expected_output="Complete draft content in markdown format",
+ agent=writer
+ )
+
+ editing_task = Task(
+ description="Edit and improve the draft content for clarity, engagement, and accuracy",
+ expected_output="Polished final content in markdown format",
+ agent=editor,
+ context=[writing_task]
+ )
+
+ writing_crew = Crew(
+ agents=[writer, editor],
+ tasks=[writing_task, editing_task],
+ process=Process.sequential,
+ verbose=True
+ )
+
+ # Run the crew and store the result
+ result = writing_crew.kickoff()
+ self.state.final_content = result.raw
+
+ return "Content created"
+
+ @listen(write_content)
+ def optimize_for_seo(self, _):
+ # Use a direct LLM call for SEO optimization
+ from crewai import LLM
+ llm = LLM(model="openai/gpt-4o-mini")
+
+ prompt = f"""
+ Analyze this content for SEO effectiveness for the keyword "{self.state.topic}".
+ Rate it on a scale of 1-100 and provide 3 specific recommendations for improvement.
+
+ Content: {self.state.final_content[:1000]}... (truncated for brevity)
+
+ Format your response as JSON with the following structure:
+ {{
+ "score": 85,
+ "recommendations": [
+ "Recommendation 1",
+ "Recommendation 2",
+ "Recommendation 3"
+ ]
+ }}
+ """
+
+ seo_analysis = llm.call(prompt)
+
+ # Parse the SEO analysis
+ import json
+ try:
+ analysis = json.loads(seo_analysis)
+ self.state.seo_score = analysis.get("score", 0)
+ return analysis
+ except:
+ self.state.seo_score = 50
+ return {"score": 50, "recommendations": ["Unable to parse SEO analysis"]}
+
+# Run the flow
+content_flow = ContentProductionFlow()
+result = content_flow.kickoff()
+```
+
+## Practical Evaluation Framework
+
+To determine the right approach for your specific use case, follow this step-by-step evaluation framework:
+
+### Step 1: Assess Complexity
+
+Rate your application's complexity on a scale of 1-10 by considering:
+
+1. **Number of steps**: How many distinct operations are required?
+ - 1-3 steps: Low complexity (1-3)
+ - 4-7 steps: Medium complexity (4-7)
+ - 8+ steps: High complexity (8-10)
+
+2. **Interdependencies**: How interconnected are the different parts?
+ - Few dependencies: Low complexity (1-3)
+ - Some dependencies: Medium complexity (4-7)
+ - Many complex dependencies: High complexity (8-10)
+
+3. **Conditional logic**: How much branching and decision-making is needed?
+ - Linear process: Low complexity (1-3)
+ - Some branching: Medium complexity (4-7)
+ - Complex decision trees: High complexity (8-10)
+
+4. **Domain knowledge**: How specialized is the knowledge required?
+ - General knowledge: Low complexity (1-3)
+ - Some specialized knowledge: Medium complexity (4-7)
+ - Deep expertise in multiple domains: High complexity (8-10)
+
+Calculate your average score to determine overall complexity.
+
+### Step 2: Assess Precision Requirements
+
+Rate your precision requirements on a scale of 1-10 by considering:
+
+1. **Output structure**: How structured must the output be?
+ - Free-form text: Low precision (1-3)
+ - Semi-structured: Medium precision (4-7)
+ - Strictly formatted (JSON, XML): High precision (8-10)
+
+2. **Accuracy needs**: How important is factual accuracy?
+ - Creative content: Low precision (1-3)
+ - Informational content: Medium precision (4-7)
+ - Critical information: High precision (8-10)
+
+3. **Reproducibility**: How consistent must results be across runs?
+ - Variation acceptable: Low precision (1-3)
+ - Some consistency needed: Medium precision (4-7)
+ - Exact reproducibility required: High precision (8-10)
+
+4. **Error tolerance**: What is the impact of errors?
+ - Low impact: Low precision (1-3)
+ - Moderate impact: Medium precision (4-7)
+ - High impact: High precision (8-10)
+
+Calculate your average score to determine overall precision requirements.
+
+### Step 3: Map to the Matrix
+
+Plot your complexity and precision scores on the matrix:
+
+- **Low Complexity (1-4), Low Precision (1-4)**: Simple Crews
+- **Low Complexity (1-4), High Precision (5-10)**: Flows with direct LLM calls
+- **High Complexity (5-10), Low Precision (1-4)**: Complex Crews
+- **High Complexity (5-10), High Precision (5-10)**: Flows orchestrating Crews
+
+### Step 4: Consider Additional Factors
+
+Beyond complexity and precision, consider:
+
+1. **Development time**: Crews are often faster to prototype
+2. **Maintenance needs**: Flows provide better long-term maintainability
+3. **Team expertise**: Consider your team's familiarity with different approaches
+4. **Scalability requirements**: Flows typically scale better for complex applications
+5. **Integration needs**: Consider how the solution will integrate with existing systems
+
+## Conclusion
+
+Choosing between Crews and Flows—or combining them—is a critical architectural decision that impacts the effectiveness, maintainability, and scalability of your CrewAI application. By evaluating your use case along the dimensions of complexity and precision, you can make informed decisions that align with your specific requirements.
+
+Remember that the best approach often evolves as your application matures. Start with the simplest solution that meets your needs, and be prepared to refine your architecture as you gain experience and your requirements become clearer.
+
+
+
+
+## Step 2: Understanding the Project Structure
+
+The generated project has the following structure. The starter embedded crew uses the classic Python/YAML layout, and in Step 4 we will replace the content crew with a JSONC crew.
+
+```
+guide_creator_flow/
+├── .gitignore
+├── pyproject.toml
+├── README.md
+├── .env
+└── src/
+ └── guide_creator_flow/
+ ├── __init__.py
+ ├── main.py
+ ├── crews/
+ │ └── poem_crew/
+ │ ├── config/
+ │ │ ├── agents.yaml
+ │ │ └── tasks.yaml
+ │ └── poem_crew.py
+ └── tools/
+ └── custom_tool.py
+```
+
+This structure provides a clear separation between different components of your flow:
+- The main flow logic in the `src/guide_creator_flow/main.py` file
+- Specialized crews in the `src/guide_creator_flow/crews` directory
+- Custom tools in the `src/guide_creator_flow/tools` directory
+
+We'll modify this structure to create our guide creator flow, which will orchestrate the process of generating comprehensive learning guides.
+
+## Step 3: Add a Content Writer Crew
+
+Our flow will need a specialized crew to handle the content creation process. Let's use the CrewAI CLI to add a content writer crew:
+
+```bash
+crewai flow add-crew content-crew
+```
+
+This command automatically creates the necessary directories and template files for your crew. The content writer crew will be responsible for writing and reviewing sections of our guide, working within the overall flow orchestrated by our main application.
+
+## Step 4: Configure the Content Writer Crew
+
+Now, let's configure the content writer crew with JSONC. We'll set up two specialized agents - a writer and a reviewer - that collaborate to create high-quality content for our guide.
+
+1. Create `src/guide_creator_flow/crews/content_crew/agents/content_writer.jsonc`:
+
+```jsonc
+{
+ "role": "Educational Content Writer",
+ "goal": "Create engaging, informative content that thoroughly explains the assigned topic and provides valuable insights to the reader.",
+ "backstory": "You are a talented educational writer who explains complex concepts in accessible language and organizes information clearly.",
+ "llm": "provider/model-id",
+ "settings": {
+ "verbose": true
+ }
+}
+```
+
+2. Create `src/guide_creator_flow/crews/content_crew/agents/content_reviewer.jsonc`:
+
+```jsonc
+{
+ "role": "Educational Content Reviewer and Editor",
+ "goal": "Ensure content is accurate, comprehensive, well-structured, and consistent with previously written sections.",
+ "backstory": "You are a meticulous editor with an eye for detail, clarity, and coherence.",
+ "llm": "provider/model-id",
+ "settings": {
+ "verbose": true
+ }
+}
+```
+
+Replace `provider/model-id` with the model you use, for example `openai/gpt-4o`, `gemini/gemini-2.0-flash-001`, or `anthropic/claude-sonnet-4-6`.
+
+3. Create `src/guide_creator_flow/crews/content_crew/crew.jsonc`:
+
+```jsonc
+{
+ "name": "Content Crew",
+ "agents": ["content_writer", "content_reviewer"],
+ "tasks": [
+ {
+ "name": "write_section_task",
+ "description": "Write a comprehensive section on the topic: \"{section_title}\".\n\nSection description: {section_description}\nTarget audience: {audience_level} level learners\n\nYour content should begin with a brief introduction, explain key concepts clearly with examples, include practical applications where appropriate, end with a summary, and be approximately 500-800 words.\n\nPreviously written sections:\n{previous_sections}",
+ "expected_output": "A well-structured, comprehensive section in Markdown format that thoroughly explains the topic and is appropriate for the target audience.",
+ "agent": "content_writer",
+ "markdown": true
+ },
+ {
+ "name": "review_section_task",
+ "description": "Review and improve this section on \"{section_title}\":\n\n{draft_content}\n\nTarget audience: {audience_level} level learners\nPreviously written sections:\n{previous_sections}\n\nFix errors, improve clarity, verify consistency, enhance structure, and add missing key information.",
+ "expected_output": "An improved, polished version of the section that maintains the original structure but enhances clarity, accuracy, and consistency.",
+ "agent": "content_reviewer",
+ "context": ["write_section_task"],
+ "markdown": true
+ }
+ ],
+ "process": "sequential",
+ "verbose": true
+}
+```
+
+The `context` field lets the reviewer use the writer's output.
+
+4. Replace `src/guide_creator_flow/crews/content_crew/content_crew.py` with a small loader:
+
+```python
+from pathlib import Path
+
+from crewai.project import load_crew
+
+
+def kickoff_content_crew(inputs: dict):
+ crew, default_inputs = load_crew(Path(__file__).with_name("crew.jsonc"))
+ return crew.kickoff(inputs={**default_inputs, **inputs})
+```
+
+This loader turns `crew.jsonc` into a `Crew` at runtime. While this crew can function independently, in our flow it will be orchestrated as part of a larger system.
+
+## Step 5: Create the Flow
+
+Now comes the exciting part - creating the flow that will orchestrate the entire guide creation process. This is where we'll combine regular Python code, direct LLM calls, and our content creation crew into a cohesive system.
+
+Our flow will:
+1. Get user input for a topic and audience level
+2. Make a direct LLM call to create a structured guide outline
+3. Process each section sequentially using the content writer crew
+4. Combine everything into a final comprehensive document
+
+Let's create our flow in the `main.py` file:
+
+```python
+#!/usr/bin/env python
+import json
+import os
+from typing import List, Dict
+from pydantic import BaseModel, Field
+from crewai import LLM
+from crewai.flow.flow import Flow, listen, start
+from guide_creator_flow.crews.content_crew.content_crew import kickoff_content_crew
+
+# Define our models for structured data
+class Section(BaseModel):
+ title: str = Field(description="Title of the section")
+ description: str = Field(description="Brief description of what the section should cover")
+
+class GuideOutline(BaseModel):
+ title: str = Field(description="Title of the guide")
+ introduction: str = Field(description="Introduction to the topic")
+ target_audience: str = Field(description="Description of the target audience")
+ sections: List[Section] = Field(description="List of sections in the guide")
+ conclusion: str = Field(description="Conclusion or summary of the guide")
+
+# Define our flow state
+class GuideCreatorState(BaseModel):
+ topic: str = ""
+ audience_level: str = ""
+ guide_outline: GuideOutline = None
+ sections_content: Dict[str, str] = {}
+
+class GuideCreatorFlow(Flow[GuideCreatorState]):
+ """Flow for creating a comprehensive guide on any topic"""
+
+ @start()
+ def get_user_input(self):
+ """Get input from the user about the guide topic and audience"""
+ print("\n=== Create Your Comprehensive Guide ===\n")
+
+ # Get user input
+ self.state.topic = input("What topic would you like to create a guide for? ")
+
+ # Get audience level with validation
+ while True:
+ audience = input("Who is your target audience? (beginner/intermediate/advanced) ").lower()
+ if audience in ["beginner", "intermediate", "advanced"]:
+ self.state.audience_level = audience
+ break
+ print("Please enter 'beginner', 'intermediate', or 'advanced'")
+
+ print(f"\nCreating a guide on {self.state.topic} for {self.state.audience_level} audience...\n")
+ return self.state
+
+ @listen(get_user_input)
+ def create_guide_outline(self, state):
+ """Create a structured outline for the guide using a direct LLM call"""
+ print("Creating guide outline...")
+
+ # Initialize the LLM
+ llm = LLM(model="openai/gpt-4o-mini", response_format=GuideOutline)
+
+ # Create the messages for the outline
+ messages = [
+ {"role": "system", "content": "You are a helpful assistant designed to output JSON."},
+ {"role": "user", "content": f"""
+ Create a detailed outline for a comprehensive guide on "{state.topic}" for {state.audience_level} level learners.
+
+ The outline should include:
+ 1. A compelling title for the guide
+ 2. An introduction to the topic
+ 3. 4-6 main sections that cover the most important aspects of the topic
+ 4. A conclusion or summary
+
+ For each section, provide a clear title and a brief description of what it should cover.
+ """}
+ ]
+
+ # Make the LLM call with JSON response format
+ response = llm.call(messages=messages)
+
+ # Parse the JSON response
+ outline_dict = json.loads(response)
+ self.state.guide_outline = GuideOutline(**outline_dict)
+
+ # Ensure output directory exists before saving
+ os.makedirs("output", exist_ok=True)
+
+ # Save the outline to a file
+ with open("output/guide_outline.json", "w") as f:
+ json.dump(outline_dict, f, indent=2)
+
+ print(f"Guide outline created with {len(self.state.guide_outline.sections)} sections")
+ return self.state.guide_outline
+
+ @listen(create_guide_outline)
+ def write_and_compile_guide(self, outline):
+ """Write all sections and compile the guide"""
+ print("Writing guide sections and compiling...")
+ completed_sections = []
+
+ # Process sections one by one to maintain context flow
+ for section in outline.sections:
+ print(f"Processing section: {section.title}")
+
+ # Build context from previous sections
+ previous_sections_text = ""
+ if completed_sections:
+ previous_sections_text = "# Previously Written Sections\n\n"
+ for title in completed_sections:
+ previous_sections_text += f"## {title}\n\n"
+ previous_sections_text += self.state.sections_content.get(title, "") + "\n\n"
+ else:
+ previous_sections_text = "No previous sections written yet."
+
+ # Run the content crew for this section
+ result = kickoff_content_crew(inputs={
+ "section_title": section.title,
+ "section_description": section.description,
+ "audience_level": self.state.audience_level,
+ "previous_sections": previous_sections_text,
+ "draft_content": ""
+ })
+
+ # Store the content
+ self.state.sections_content[section.title] = result.raw
+ completed_sections.append(section.title)
+ print(f"Section completed: {section.title}")
+
+ # Compile the final guide
+ guide_content = f"# {outline.title}\n\n"
+ guide_content += f"## Introduction\n\n{outline.introduction}\n\n"
+
+ # Add each section in order
+ for section in outline.sections:
+ section_content = self.state.sections_content.get(section.title, "")
+ guide_content += f"\n\n{section_content}\n\n"
+
+ # Add conclusion
+ guide_content += f"## Conclusion\n\n{outline.conclusion}\n\n"
+
+ # Save the guide
+ with open("output/complete_guide.md", "w") as f:
+ f.write(guide_content)
+
+ print("\nComplete guide compiled and saved to output/complete_guide.md")
+ return "Guide creation completed successfully"
+
+def kickoff():
+ """Run the guide creator flow"""
+ GuideCreatorFlow().kickoff()
+ print("\n=== Flow Complete ===")
+ print("Your comprehensive guide is ready in the output directory.")
+ print("Open output/complete_guide.md to view it.")
+
+def plot():
+ """Generate a visualization of the flow"""
+ flow = GuideCreatorFlow()
+ flow.plot("guide_creator_flow")
+ print("Flow visualization saved to guide_creator_flow.html")
+
+if __name__ == "__main__":
+ kickoff()
+```
+
+Let's analyze what's happening in this flow:
+
+1. We define Pydantic models for structured data, ensuring type safety and clear data representation
+2. We create a state class to maintain data across different steps of the flow
+3. We implement three main flow steps:
+ - Getting user input with the `@start()` decorator
+ - Creating a guide outline with a direct LLM call
+ - Processing sections with our content crew
+4. We use the `@listen()` decorator to establish event-driven relationships between steps
+
+This is the power of flows - combining different types of processing (user interaction, direct LLM calls, crew-based tasks) into a coherent, event-driven system.
+
+## Step 6: Set Up Your Environment Variables
+
+Create a `.env` file in your project root with your API keys. See the [LLM setup
+guide](/en/concepts/llms#setting-up-your-llm) for details on configuring a provider.
+
+```sh .env
+OPENAI_API_KEY=your_openai_api_key
+# or
+GEMINI_API_KEY=your_gemini_api_key
+# or
+ANTHROPIC_API_KEY=your_anthropic_api_key
+```
+
+## Step 7: Install Dependencies
+
+Install the required dependencies:
+
+```bash
+crewai install
+```
+
+## Step 8: Run Your Flow
+
+Now it's time to see your flow in action! Run it using the CrewAI CLI:
+
+```bash
+crewai run
+```
+
+When you run this command, you'll see your flow spring to life:
+1. It will prompt you for a topic and audience level
+2. It will create a structured outline for your guide
+3. It will process each section, with the content writer and reviewer collaborating on each
+4. Finally, it will compile everything into a comprehensive guide
+
+This demonstrates the power of flows to orchestrate complex processes involving multiple components, both AI and non-AI.
+
+## Step 9: Visualize Your Flow
+
+One of the powerful features of flows is the ability to visualize their structure:
+
+```bash
+crewai flow plot
+```
+
+This will create an HTML file that shows the structure of your flow, including the relationships between different steps and the data that flows between them. This visualization can be invaluable for understanding and debugging complex flows.
+
+## Step 10: Review the Output
+
+Once the flow completes, you'll find two files in the `output` directory:
+
+1. `guide_outline.json`: Contains the structured outline of the guide
+2. `complete_guide.md`: The comprehensive guide with all sections
+
+Take a moment to review these files and appreciate what you've built - a system that combines user input, direct AI interactions, and collaborative agent work to produce a complex, high-quality output.
+
+## The Art of the Possible: Beyond Your First Flow
+
+What you've learned in this guide provides a foundation for creating much more sophisticated AI systems. Here are some ways you could extend this basic flow:
+
+### Enhancing User Interaction
+
+You could create more interactive flows with:
+- Web interfaces for input and output
+- Real-time progress updates
+- Interactive feedback and refinement loops
+- Multi-stage user interactions
+
+### Adding More Processing Steps
+
+You could expand your flow with additional steps for:
+- Research before outline creation
+- Image generation for illustrations
+- Code snippet generation for technical guides
+- Final quality assurance and fact-checking
+
+### Creating More Complex Flows
+
+You could implement more sophisticated flow patterns:
+- Conditional branching based on user preferences or content type
+- Parallel processing of independent sections
+- Iterative refinement loops with feedback
+- Integration with external APIs and services
+
+### Applying to Different Domains
+
+The same patterns can be applied to create flows for:
+- **Interactive storytelling**: Create personalized stories based on user input
+- **Business intelligence**: Process data, generate insights, and create reports
+- **Product development**: Facilitate ideation, design, and planning
+- **Educational systems**: Create personalized learning experiences
+
+## Key Features Demonstrated
+
+This guide creator flow demonstrates several powerful features of CrewAI:
+
+1. **User interaction**: The flow collects input directly from the user
+2. **Direct LLM calls**: Uses the LLM class for efficient, single-purpose AI interactions
+3. **Structured data with Pydantic**: Uses Pydantic models to ensure type safety
+4. **Sequential processing with context**: Writes sections in order, providing previous sections for context
+5. **Multi-agent crews**: Leverages specialized agents (writer and reviewer) for content creation
+6. **State management**: Maintains state across different steps of the process
+7. **Event-driven architecture**: Uses the `@listen` decorator to respond to events
+
+## Understanding the Flow Structure
+
+Let's break down the key components of flows to help you understand how to build your own:
+
+### 1. Direct LLM Calls
+
+Flows allow you to make direct calls to language models when you need simple, structured responses:
+
+```python
+llm = LLM(
+ model="model-id-here", # gpt-4o, gemini-2.0-flash, anthropic/claude...
+ response_format=GuideOutline
+)
+response = llm.call(messages=messages)
+```
+
+This is more efficient than using a crew when you need a specific, structured output.
+
+### 2. Event-Driven Architecture
+
+Flows use decorators to establish relationships between components:
+
+```python
+@start()
+def get_user_input(self):
+ # First step in the flow
+ # ...
+
+@listen(get_user_input)
+def create_guide_outline(self, state):
+ # This runs when get_user_input completes
+ # ...
+```
+
+This creates a clear, declarative structure for your application.
+
+### 3. State Management
+
+Flows maintain state across steps, making it easy to share data:
+
+```python
+class GuideCreatorState(BaseModel):
+ topic: str = ""
+ audience_level: str = ""
+ guide_outline: GuideOutline = None
+ sections_content: Dict[str, str] = {}
+```
+
+This provides a type-safe way to track and transform data throughout your flow.
+
+### 4. Crew Integration
+
+Flows can seamlessly integrate with crews for complex collaborative tasks:
+
+```python
+result = kickoff_content_crew(inputs={
+ "section_title": section.title,
+ # ...
+})
+```
+
+This allows you to use the right tool for each part of your application - direct LLM calls for simple tasks and crews for complex collaboration.
+
+## Next Steps
+
+Now that you've built your first flow, you can:
+
+1. Experiment with more complex flow structures and patterns
+2. Try using `@router()` to create conditional branches in your flows
+3. Explore the `and_` and `or_` functions for more complex parallel execution
+4. Connect your flow to external APIs, databases, or user interfaces
+5. Combine multiple specialized crews in a single flow
+6. Build multi-turn chat apps with [Conversational Flows](/en/guides/flows/conversational-flows) (`kickoff` per message, `ChatSession`, deferred tracing)
+
+
+ + Design agents, orchestrate crews, and automate flows with guardrails, memory, knowledge, and observability baked in. +
++ Coding agent setup +
++ Copy a ready-to-paste setup prompt for Claude Code, Codex, Cursor, or any coding agent. It installs the official CrewAI skills, checks the CLI, and points the agent at the right docs before it edits code. +
+
+
+
+Flows provide:
+- **State Management**: Persist data across steps and executions.
+- **Event-Driven Execution**: Trigger actions based on events or external inputs.
+- **Control Flow**: Use conditional logic, loops, and branching.
+
+### 2. Crews: The Intelligence
+
+
+
+
+Crews provide:
+- **Role-Playing Agents**: Specialized agents with specific goals and tools.
+- **Autonomous Collaboration**: Agents work together to solve tasks.
+- **Task Delegation**: Tasks are assigned and executed based on agent capabilities.
+
+## How It All Works Together
+
+1. **The Flow** triggers an event or starts a process.
+2. **The Flow** manages the state and decides what to do next.
+3. **The Flow** delegates a complex task to a **Crew**.
+4. **The Crew**'s agents collaborate to complete the task.
+5. **The Crew** returns the result to the **Flow**.
+6. **The Flow** continues execution based on the result.
+
+## Key Features
+
+
+
+
+## Best Practices
+
+1. **Be specific in your image generation prompts** to get the best results.
+2. **Consider generation time** - Image generation can take some time, so factor this into your task planning.
+3. **Follow usage policies** - Always comply with OpenAI's usage policies when generating images.
+
+## Troubleshooting
+
+1. **Check API access** - Ensure your OpenAI API key has access to DALL-E.
+2. **Version compatibility** - Check that you're using the latest version of crewAI and crewai-tools.
+3. **Tool configuration** - Verify that the DALL-E tool is correctly added to the agent's tool list.
\ No newline at end of file
diff --git a/docs/v1.15.13/en/learn/execution-boundary-hooks.mdx b/docs/v1.15.13/en/learn/execution-boundary-hooks.mdx
new file mode 100644
index 0000000000..80e2b382e0
--- /dev/null
+++ b/docs/v1.15.13/en/learn/execution-boundary-hooks.mdx
@@ -0,0 +1,187 @@
+---
+title: Execution Boundary Hooks
+description: Intercept the start, inputs, output, and end of crew and flow executions with the @on decorator
+mode: "wide"
+---
+
+Execution boundary hooks intercept the outermost edges of a run — before any
+work starts, when inputs are resolved, when the final result is ready, and when
+the execution finishes. They fire for both crews and flows and are the right
+place for run-level policy checks, input rewriting, and output sanitization.
+
+## Overview
+
+Four interception points cover the boundaries:
+
+| Point | When | `ctx.payload` |
+|-------|------|---------------|
+| `EXECUTION_START` | A crew or flow is about to begin | inputs `dict` |
+| `INPUT` | Resolved inputs for the execution | inputs `dict` |
+| `OUTPUT` | The final result is ready | the output object |
+| `EXECUTION_END` | The execution has finished (success or failure) | the output object, or `None` on failure |
+
+For a crew, the output payload is a `CrewOutput`. For a flow, it is the final
+flow-method result.
+
+## Hook Signature
+
+```python
+from crewai.hooks import on, HookAborted, InterceptionPoint
+
+@on(InterceptionPoint.EXECUTION_START)
+def boundary_hook(ctx) -> Any | None:
+ # Mutate ctx.payload in place, or
+ # return a non-None value to replace it, or
+ # raise HookAborted(reason, source) to stop the run
+ return None
+```
+
+Boundary hooks follow the standard contract: proceed (`return None`), mutate in
+place, replace by returning, or abort by raising
+[`HookAborted`](/edge/en/learn/execution-hooks#aborting-an-operation). An abort at any
+boundary propagates out of `kickoff()` with its reason.
+
+## Context Schema
+
+Each point receives a typed context. All contexts share the base fields:
+
+```python
+class InterceptionContext:
+ payload: Any # The interceptable value (see table above)
+ agent: Any = None # Not populated at execution boundaries
+ agent_role: str | None # Not populated at execution boundaries
+ task: Any = None # Not populated at execution boundaries
+ crew: Any = None # The Crew instance (crew runs only)
+ flow: Any = None # The Flow instance (flow runs only)
+```
+
+The per-point contexts add a named alias for the payload:
+
+```python
+class ExecutionStartContext(InterceptionContext):
+ inputs: dict # Same dict as payload
+
+class InputContext(InterceptionContext):
+ inputs: dict # Same dict as payload
+
+class OutputContext(InterceptionContext):
+ output: Any # The output object
+
+class ExecutionEndContext(InterceptionContext):
+ output: Any # The output object (None when status == "failed")
+ status: str # "completed" or "failed"
+ error: BaseException | None # The exception when status == "failed"
+```
+
+
+
+
+
+
+ Example with Bearer authentication:
+ ```bash
+ curl -X POST {BASE_URL}/kickoff \
+ -H "Authorization: Bearer YOUR_API_TOKEN" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "inputs": {
+ "topic": "AI Research"
+ },
+ "humanInputWebhook": {
+ "url": "https://your-webhook.com/hitl",
+ "authentication": {
+ "strategy": "bearer",
+ "token": "your-webhook-secret-token"
+ }
+ }
+ }'
+ ```
+
+ Or with Basic authentication:
+ ```bash
+ curl -X POST {BASE_URL}/kickoff \
+ -H "Authorization: Bearer YOUR_API_TOKEN" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "inputs": {
+ "topic": "AI Research"
+ },
+ "humanInputWebhook": {
+ "url": "https://your-webhook.com/hitl",
+ "authentication": {
+ "strategy": "basic",
+ "username": "your-username",
+ "password": "your-password"
+ }
+ }
+ }'
+ ```
+
+
+
+
+
+
+
+
+
+
+
+
+Additionally, you can view the execution graph view of the trace, which shows the control and data flow of the trace, which will scale with larger agents to show handoffs and relationships between LLM calls, tool calls, and agent interactions.
+
+
+
+
+
+## References
+
+- [Datadog LLM Observability](https://www.datadoghq.com/product/llm-observability/)
+- [Datadog LLM Observability CrewAI Auto-Instrumentation](https://docs.datadoghq.com/llm_observability/instrumentation/auto_instrumentation?tab=python#crew-ai)
diff --git a/docs/v1.15.13/en/observability/galileo.mdx b/docs/v1.15.13/en/observability/galileo.mdx
new file mode 100644
index 0000000000..241517ed22
--- /dev/null
+++ b/docs/v1.15.13/en/observability/galileo.mdx
@@ -0,0 +1,115 @@
+---
+title: Galileo
+description: Galileo integration for CrewAI tracing and evaluation
+icon: telescope
+mode: "wide"
+---
+
+## Overview
+
+This guide demonstrates how to integrate **Galileo** with **CrewAI**
+for comprehensive tracing and Evaluation Engineering.
+By the end of this guide, you will be able to trace your CrewAI agents,
+monitor their performance, and evaluate their behaviour with
+Galileo's powerful observability platform.
+
+> **What is Galileo?** [Galileo](https://galileo.ai) is AI evaluation and observability
+platform that delivers end-to-end tracing, evaluation,
+and monitoring for AI applications. It enables teams to capture ground truth,
+create robust guardrails, and run systematic experiments with
+built-in experiment tracking and performance analytics—ensuring reliability,
+transparency, and continuous improvement across the AI lifecycle.
+
+## Getting started
+
+This tutorial follows the [CrewAI quickstart](/en/quickstart) and shows how to add
+Galileo's [CrewAIEventListener](https://v2docs.galileo.ai/sdk-api/python/reference/handlers/crewai/handler),
+an event handler.
+For more information, see Galileo’s
+[Add Galileo to a CrewAI Application](https://v2docs.galileo.ai/how-to-guides/third-party-integrations/add-galileo-to-crewai/add-galileo-to-crewai)
+how-to guide.
+
+> **Note** This tutorial assumes you have completed the [CrewAI quickstart](/en/quickstart).
+If you want a completed comprehensive example, see the Galileo
+[CrewAI sdk-example repo](https://github.com/rungalileo/sdk-examples/tree/main/python/agent/crew-ai).
+
+### Step 1: Install dependencies
+
+Install the required dependencies for your app.
+Create a virtual environment using your preferred method,
+then install dependencies inside that environment using your
+preferred tool:
+
+```bash
+uv add galileo
+```
+
+### Step 2: Add to the .env file from the [CrewAI quickstart](/en/quickstart)
+
+```bash
+# Your Galileo API key
+GALILEO_API_KEY="your-galileo-api-key"
+
+# Your Galileo project name
+GALILEO_PROJECT="your-galileo-project-name"
+
+# The name of the Log stream you want to use for logging
+GALILEO_LOG_STREAM="your-galileo-log-stream "
+```
+
+### Step 3: Add the Galileo event listener
+
+To enable logging with Galileo, you need to create an instance of the `CrewAIEventListener`.
+Import the Galileo CrewAI handler package by
+adding the following code at the top of your main.py file:
+
+```python
+from galileo.handlers.crewai.handler import CrewAIEventListener
+```
+
+At the start of your run function, create the event listener:
+
+```python
+def run():
+ # Create the event listener
+ CrewAIEventListener()
+ # The rest of your existing code goes here
+```
+
+When you create the listener instance, it is automatically
+registered with CrewAI.
+
+### Step 4: Run your crew
+
+Run your crew with the CrewAI CLI:
+
+```bash
+crewai run
+```
+
+### Step 5: View the traces in Galileo
+
+Once your crew has finished, the traces will be flushed and appear in Galileo.
+
+
+
+## Understanding the Galileo Integration
+
+Galileo integrates with CrewAI by registering an event listener
+that captures Crew execution events (e.g., agent actions, tool calls, model responses)
+and forwards them to Galileo for observability and evaluation.
+
+### Understanding the event listener
+
+Creating a `CrewAIEventListener()` instance is all that’s
+required to enable Galileo for a CrewAI run. When instantiated, the listener:
+
+- Automatically registers itself with CrewAI
+- Reads Galileo configuration from environment variables
+- Logs all run data to the Galileo project and log stream specified by
+ `GALILEO_PROJECT` and `GALILEO_LOG_STREAM`
+
+No additional configuration or code changes are required.
+All data from this run is logged to the Galileo project and
+log stream specified by your environment configuration
+(for example, GALILEO_PROJECT and GALILEO_LOG_STREAM).
diff --git a/docs/v1.15.13/en/observability/langdb.mdx b/docs/v1.15.13/en/observability/langdb.mdx
new file mode 100644
index 0000000000..adb2d1908d
--- /dev/null
+++ b/docs/v1.15.13/en/observability/langdb.mdx
@@ -0,0 +1,287 @@
+---
+title: LangDB Integration
+description: Govern, secure, and optimize your CrewAI workflows with LangDB AI Gateway—access 350+ models, automatic routing, cost optimization, and full observability.
+icon: database
+mode: "wide"
+---
+
+# Introduction
+
+[LangDB AI Gateway](https://langdb.ai) provides OpenAI-compatible APIs to connect with multiple Large Language Models and serves as an observability platform that makes it effortless to trace CrewAI workflows end-to-end while providing access to 350+ language models. With a single `init()` call, all agent interactions, task executions, and LLM calls are captured, providing comprehensive observability and production-ready AI infrastructure for your applications.
+
+
+
+
+
+**Checkout:** [View the live trace example](https://app.langdb.ai/sharing/threads/3becbfed-a1be-ae84-ea3c-4942867a3e22)
+
+## Features
+
+### AI Gateway Capabilities
+- **Access to 350+ LLMs**: Connect to all major language models through a single integration
+- **Virtual Models**: Create custom model configurations with specific parameters and routing rules
+- **Virtual MCP**: Enable compatibility and integration with MCP (Model Context Protocol) systems for enhanced agent communication
+- **Guardrails**: Implement safety measures and compliance controls for agent behavior
+
+### Observability & Tracing
+- **Automatic Tracing**: Single `init()` call captures all CrewAI interactions
+- **End-to-End Visibility**: Monitor agent workflows from start to finish
+- **Tool Usage Tracking**: Track which tools agents use and their outcomes
+- **Model Call Monitoring**: Detailed insights into LLM interactions
+- **Performance Analytics**: Monitor latency, token usage, and costs
+- **Debugging Support**: Step-through execution for troubleshooting
+- **Real-time Monitoring**: Live traces and metrics dashboard
+
+## Setup Instructions
+
+
+
+
+### What You'll See
+
+- **Agent Interactions**: Complete flow of agent conversations and task handoffs
+- **Tool Usage**: Which tools were called, their inputs, and outputs
+- **Model Calls**: Detailed LLM interactions with prompts image.pngand responses
+- **Performance Metrics**: Latency, token usage, and cost tracking
+- **Execution Timeline**: Step-by-step view of the entire workflow
+
+
+## Troubleshooting
+
+### Common Issues
+
+- **No traces appearing**: Ensure `init()` is called before any CrewAI imports
+- **Authentication errors**: Verify your LangDB API key and project ID
+
+
+## Resources
+
+
+
+
+
+ + Evaluate captured logs automatically from the UI based on filters and sampling + +
++ Use human evaluation or rating to assess the quality of your logs and evaluate them. + +
++ Evaluate any component of your trace or log to gain insights into your agent’s behavior. + +
+
+
+
+
+## Troubleshooting
+
+### Common Issues
+
+- **No traces appearing**: Ensure your API key and repository ID are correct
+- Ensure you've **`called instrument_crewai()`** **_before_** running your crew. This initializes logging hooks correctly.
+- Set `debug=True` in your `instrument_crewai()` call to surface any internal errors:
+
+ ```python
+ instrument_crewai(logger, debug=True)
+ ```
+- Configure your agents with `verbose=True` to capture detailed logs:
+
+ ```python
+ agent = CrewAgent(..., verbose=True)
+ ```
+- Double-check that `instrument_crewai()` is called **before** creating or executing agents. This might be obvious, but it's a common oversight.
+
+## Resources
+
+
+
+
+
+
+
+
+### Features
+
+- **Analytics Dashboard**: Monitor your Agents health and performance with detailed dashboards that track metrics, costs, and user interactions.
+- **OpenTelemetry-native Observability SDK**: Vendor-neutral SDKs to send traces and metrics to your existing observability tools like Grafana, DataDog and more.
+- **Cost Tracking for Custom and Fine-Tuned Models**: Tailor cost estimations for specific models using custom pricing files for precise budgeting.
+- **Exceptions Monitoring Dashboard**: Quickly spot and resolve issues by tracking common exceptions and errors with a monitoring dashboard.
+- **Compliance and Security**: Detect potential threats such as profanity and PII leaks.
+- **Prompt Injection Detection**: Identify potential code injection and secret leaks.
+- **API Keys and Secrets Management**: Securely handle your LLM API keys and secrets centrally, avoiding insecure practices.
+- **Prompt Management**: Manage and version Agent prompts using PromptHub for consistent and easy access across Agents.
+- **Model Playground** Test and compare different models for your CrewAI agents before deployment.
+
+## Setup Instructions
+
+
+
+
+
+
+
+
+Opik provides comprehensive support for every stage of your CrewAI application development:
+
+- **Log Traces and Spans**: Automatically track LLM calls and application logic to debug and analyze development and production systems. Manually or programmatically annotate, view, and compare responses across projects.
+- **Evaluate Your LLM Application's Performance**: Evaluate against a custom test set and run built-in evaluation metrics or define your own metrics in the SDK or UI.
+- **Test Within Your CI/CD Pipeline**: Establish reliable performance baselines with Opik's LLM unit tests, built on PyTest. Run online evaluations for continuous monitoring in production.
+- **Monitor & Analyze Production Data**: Understand your models' performance on unseen data in production and generate datasets for new dev iterations.
+
+## Setup
+Comet provides a hosted version of the Opik platform, or you can run the platform locally.
+
+To use the hosted version, simply [create a free Comet account](https://www.comet.com/signup?utm_medium=github&utm_source=crewai_docs) and grab you API Key.
+
+To run the Opik platform locally, see our [installation guide](https://www.comet.com/docs/opik/self-host/overview/) for more information.
+
+For this guide we will use CrewAI’s quickstart example.
+
+
+
+
+
+## Introduction
+
+Portkey enhances CrewAI with production-readiness features, turning your experimental agent crews into robust systems by providing:
+
+- **Complete observability** of every agent step, tool use, and interaction
+- **Built-in reliability** with fallbacks, retries, and load balancing
+- **Cost tracking and optimization** to manage your AI spend
+- **Access to 200+ LLMs** through a single integration
+- **Guardrails** to keep agent behavior safe and compliant
+- **Version-controlled prompts** for consistent agent performance
+
+
+### Installation & Setup
+
+
+
+
+Traces provide a hierarchical view of your crew's execution, showing the sequence of LLM calls, tool invocations, and state transitions.
+
+```python
+# Add trace_id to enable hierarchical tracing in Portkey
+portkey_llm = LLM(
+ model="gpt-4o",
+ base_url=PORTKEY_GATEWAY_URL,
+ api_key="dummy",
+ extra_headers=createHeaders(
+ api_key="YOUR_PORTKEY_API_KEY",
+ virtual_key="YOUR_OPENAI_VIRTUAL_KEY",
+ trace_id="unique-session-id" # Add unique trace ID
+ )
+)
+```
+
+
+
+Portkey logs every interaction with LLMs, including:
+
+- Complete request and response payloads
+- Latency and token usage metrics
+- Cost calculations
+- Tool calls and function executions
+
+All logs can be filtered by metadata, trace IDs, models, and more, making it easy to debug specific crew runs.
+
+
+
+Portkey provides built-in dashboards that help you:
+
+- Track cost and token usage across all crew runs
+- Analyze performance metrics like latency and success rates
+- Identify bottlenecks in your agent workflows
+- Compare different crew configurations and LLMs
+
+You can filter and segment all metrics by custom metadata to analyze specific crew types, user groups, or use cases.
+
+
+
+Add custom metadata to your CrewAI LLM configuration to enable powerful filtering and segmentation:
+
+```python
+portkey_llm = LLM(
+ model="gpt-4o",
+ base_url=PORTKEY_GATEWAY_URL,
+ api_key="dummy",
+ extra_headers=createHeaders(
+ api_key="YOUR_PORTKEY_API_KEY",
+ virtual_key="YOUR_OPENAI_VIRTUAL_KEY",
+ metadata={
+ "crew_type": "research_crew",
+ "environment": "production",
+ "_user": "user_123", # Special _user field for user analytics
+ "request_source": "mobile_app"
+ }
+ )
+)
+```
+
+This metadata can be used to filter logs, traces, and metrics on the Portkey dashboard, allowing you to analyze specific crew runs, users, or environments.
+
+
+
+This enables:
+- Per-user cost tracking and budgeting
+- Personalized user analytics
+- Team or organization-level metrics
+- Environment-specific monitoring (staging vs. production)
+
+
+
+
+
+
+
+
+
+
+
+
+ Official CrewAI documentation
+Get personalized guidance on implementing this integration
+
+
+
+
+
+ 왼쪽 패널은 체크포인트를 브랜치별로 그룹화하며, 포크는 부모 아래에 중첩됩니다. 체크포인트를 선택하면 메타데이터, 엔티티 상태, 태스크 진행 상황이 있는 세부 정보 패널이 열립니다. **Resume**은 실행을 계속하고, **Fork**는 새 브랜치를 시작합니다.
+
+
+
+
+
+ 세부 정보 패널에는 두 개의 편집 가능한 영역이 있습니다:
+
+ - **Inputs** — 원래 kickoff의 입력으로, 미리 채워져 있으며 편집 가능합니다.
+
+
+
+
+
+ - **태스크 출력** — 완료된 태스크의 출력. 출력을 편집하고 **Fork**를 누르면 다운스트림 태스크가 무효화되어 수정된 컨텍스트로 다시 실행됩니다.
+
+
+
+
+
+
+
+
+
+ stop 파라미터를 보낼 필요가 없다면 LLM 호출에서 제외할 수 있습니다:
+
+ ```python
+ from crewai import LLM
+ import os
+
+ os.environ["OPENAI_API_KEY"] = "
+
+
+이 매트릭스를 통해 다양한 방식이 복잡성과 정밀성에 대한 요구 사항과 어떻게 일치하는지 시각적으로 확인할 수 있습니다. 각 사분면이 의미하는 바와 그것이 아키텍처 선택에 어떻게 도움이 되는지 함께 살펴보겠습니다.
+
+## 복잡성-정밀도 행렬 설명
+
+### 복잡성이란 무엇인가?
+
+CrewAI 애플리케이션의 맥락에서 **복잡성**은 다음을 의미합니다:
+
+- 요구되는 뚜렷한 단계 또는 작업 수
+- 수행해야 할 작업의 다양성
+- 서로 다른 구성 요소 간의 상호 의존성
+- 조건부 로직과 분기의 필요성
+- 전체 워크플로우의 정교함
+
+### 정밀성이란 무엇인가?
+
+**정밀성**은 이 맥락에서 다음을 의미합니다:
+
+- 최종 결과물에 요구되는 정확성
+- 구조화되고 예측 가능한 결과의 필요성
+- 재현성의 중요성
+- 각 단계에 대한 통제 수준
+- 출력의 변동 허용치
+
+### 네 가지 사분면
+
+#### 1. 낮은 복잡도, 낮은 정밀도
+
+**특징:**
+- 단순하고 직관적인 작업
+- 출력 결과의 일부 변형 허용
+- 제한된 단계 수
+- 창의적이거나 탐색적인 응용
+
+**권장 접근법:** 최소한의 에이전트를 가진 Simple Crews
+
+**예시 사용 사례:**
+- 기본 콘텐츠 생성
+- 아이디어 브레인스토밍
+- 간단한 요약 작업
+- 창의적 글쓰기 보조
+
+#### 2. 낮은 복잡성, 높은 정밀도
+
+**특징:**
+- 정확하고 구조화된 결과물이 요구되는 단순한 워크플로우
+- 재현 가능한 결과가 필요한 경우
+- 단계는 제한적이지만, 높은 정확도가 요구됨
+- 주로 데이터 처리 또는 변환이 포함됨
+
+**권장 방식:** 직접적인 LLM 호출이나 구조화된 출력이 있는 간단한 Crew 사용
+
+**예시 활용 사례:**
+- 데이터 추출 및 변환
+- 양식 작성 및 검증
+- 구조화된 콘텐츠 생성(JSON, XML)
+- 단순 분류 작업
+
+#### 3. 높은 복잡성, 낮은 정밀도
+
+**특징:**
+- 여러 단계로 이루어진 다단계 프로세스
+- 창의적이거나 탐색적인 출력물
+- 구성 요소 간의 복잡한 상호작용
+- 최종 결과의 변동성 허용
+
+**권장 접근 방식:** 여러 전문화된 agent가 포함된 Complex Crew
+
+**예시 사용 사례:**
+- 연구 및 분석
+- 콘텐츠 생성 파이프라인
+- 탐색적 데이터 분석
+- 창의적 문제 해결
+
+#### 4. 높은 복잡성, 높은 정밀도
+
+**특징:**
+- 구조화된 산출물이 요구되는 복잡한 워크플로
+- 엄격한 정확성 요구사항을 가진 여러 상호 의존적인 단계
+- 정교한 처리와 정밀한 결과 모두 필요
+- 종종 임무에 중요한 애플리케이션
+
+**권장 접근 방식:** 검증 단계를 포함한 여러 Crew를 오케스트레이션하는 Flows
+
+**예시 사용 사례:**
+- 엔터프라이즈 의사결정 지원 시스템
+- 복잡한 데이터 처리 파이프라인
+- 다단계 문서 처리
+- 규제 산업 애플리케이션
+
+## 크루와 플로우 중에서 선택하기
+
+### Crews를 선택해야 할 때
+
+Crews는 다음과 같은 경우에 이상적입니다:
+
+1. **협업 지능이 필요할 때** - 서로 다른 전문성을 가진 여러 agent들이 함께 작업해야 할 때
+2. **문제가 창발적 사고를 요구할 때** - 다양한 관점과 접근 방식에서의 해결책이 이득이 될 때
+3. **작업이 주로 창의적이거나 분석적일 때** - 작업이 리서치, 콘텐츠 제작, 분석을 포함할 때
+4. **엄격한 구조보다는 적응력을 중시할 때** - agent의 자율성이 workflow에 도움이 될 때
+5. **출력 형식이 다소 유연할 수 있을 때** - 출력 구조에 약간의 변동이 허용될 때
+
+```python
+# Example: Research Crew for market analysis
+from crewai import Agent, Crew, Process, Task
+
+# Create specialized agents
+researcher = Agent(
+ role="Market Research Specialist",
+ goal="Find comprehensive market data on emerging technologies",
+ backstory="You are an expert at discovering market trends and gathering data."
+)
+
+analyst = Agent(
+ role="Market Analyst",
+ goal="Analyze market data and identify key opportunities",
+ backstory="You excel at interpreting market data and spotting valuable insights."
+)
+
+# Define their tasks
+research_task = Task(
+ description="Research the current market landscape for AI-powered healthcare solutions",
+ expected_output="Comprehensive market data including key players, market size, and growth trends",
+ agent=researcher
+)
+
+analysis_task = Task(
+ description="Analyze the market data and identify the top 3 investment opportunities",
+ expected_output="Analysis report with 3 recommended investment opportunities and rationale",
+ agent=analyst,
+ context=[research_task]
+)
+
+# Create the crew
+market_analysis_crew = Crew(
+ agents=[researcher, analyst],
+ tasks=[research_task, analysis_task],
+ process=Process.sequential,
+ verbose=True
+)
+
+# Run the crew
+result = market_analysis_crew.kickoff()
+```
+
+### 플로우를 선택해야 할 때
+
+플로우는 다음과 같은 경우에 이상적입니다:
+
+1. **실행에 대한 정밀한 제어가 필요할 때** - 워크플로우에 정확한 순서 지정과 상태 관리가 필요한 경우
+2. **애플리케이션에 복잡한 상태 요구사항이 있을 때** - 여러 단계에 걸쳐 상태를 유지하고 변환해야 하는 경우
+3. **구조화되고 예측 가능한 출력이 필요할 때** - 애플리케이션에서 일관되고 포맷된 결과가 필요한 경우
+4. **워크플로우에 조건부 로직이 포함될 때** - 중간 결과에 따라 다른 경로를 선택해야 하는 경우
+5. **AI와 절차적 코드를 결합해야 할 때** - 솔루션에 AI 기능과 전통적인 프로그래밍이 모두 필요한 경우
+
+```python
+# Example: Customer Support Flow with structured processing
+from crewai.flow.flow import Flow, listen, router, start
+from pydantic import BaseModel
+from typing import List, Dict
+
+# Define structured state
+class SupportTicketState(BaseModel):
+ ticket_id: str = ""
+ customer_name: str = ""
+ issue_description: str = ""
+ category: str = ""
+ priority: str = "medium"
+ resolution: str = ""
+ satisfaction_score: int = 0
+
+class CustomerSupportFlow(Flow[SupportTicketState]):
+ @start()
+ def receive_ticket(self):
+ # In a real app, this might come from an API
+ self.state.ticket_id = "TKT-12345"
+ self.state.customer_name = "Alex Johnson"
+ self.state.issue_description = "Unable to access premium features after payment"
+ return "Ticket received"
+
+ @listen(receive_ticket)
+ def categorize_ticket(self, _):
+ # Use a direct LLM call for categorization
+ from crewai import LLM
+ llm = LLM(model="openai/gpt-4o-mini")
+
+ prompt = f"""
+ Categorize the following customer support issue into one of these categories:
+ - Billing
+ - Account Access
+ - Technical Issue
+ - Feature Request
+ - Other
+
+ Issue: {self.state.issue_description}
+
+ Return only the category name.
+ """
+
+ self.state.category = llm.call(prompt).strip()
+ return self.state.category
+
+ @router(categorize_ticket)
+ def route_by_category(self, category):
+ # Route to different handlers based on category
+ return category.lower().replace(" ", "_")
+
+ @listen("billing")
+ def handle_billing_issue(self):
+ # Handle billing-specific logic
+ self.state.priority = "high"
+ # More billing-specific processing...
+ return "Billing issue handled"
+
+ @listen("account_access")
+ def handle_access_issue(self):
+ # Handle access-specific logic
+ self.state.priority = "high"
+ # More access-specific processing...
+ return "Access issue handled"
+
+ # Additional category handlers...
+
+ @listen("billing", "account_access", "technical_issue", "feature_request", "other")
+ def resolve_ticket(self, resolution_info):
+ # Final resolution step
+ self.state.resolution = f"Issue resolved: {resolution_info}"
+ return self.state.resolution
+
+# Run the flow
+support_flow = CustomerSupportFlow()
+result = support_flow.kickoff()
+```
+
+### 크루와 플로우를 결합해야 할 때
+
+가장 정교한 애플리케이션은 종종 크루와 플로우를 결합할 때 이점을 얻습니다:
+
+1. **복잡한 다단계 프로세스** - 플로우를 사용해 전체 프로세스를 오케스트레이션하고, 크루를 통해 복잡한 하위 작업을 처리합니다.
+2. **창의성과 구조가 모두 필요한 애플리케이션** - 창의적인 작업에는 크루를 사용하고, 구조적인 처리는 플로우로 처리합니다.
+3. **엔터프라이즈급 AI 애플리케이션** - 플로우로 상태 및 프로세스 흐름을 관리하면서, 크루를 활용해 특화된 작업을 수행합니다.
+
+```python
+# Example: Content Production Pipeline combining Crews and Flows
+from crewai.flow.flow import Flow, listen, start
+from crewai import Agent, Crew, Process, Task
+from pydantic import BaseModel
+from typing import List, Dict
+
+class ContentState(BaseModel):
+ topic: str = ""
+ target_audience: str = ""
+ content_type: str = ""
+ outline: Dict = {}
+ draft_content: str = ""
+ final_content: str = ""
+ seo_score: int = 0
+
+class ContentProductionFlow(Flow[ContentState]):
+ @start()
+ def initialize_project(self):
+ # Set initial parameters
+ self.state.topic = "Sustainable Investing"
+ self.state.target_audience = "Millennial Investors"
+ self.state.content_type = "Blog Post"
+ return "Project initialized"
+
+ @listen(initialize_project)
+ def create_outline(self, _):
+ # Use a research crew to create an outline
+ researcher = Agent(
+ role="Content Researcher",
+ goal=f"Research {self.state.topic} for {self.state.target_audience}",
+ backstory="You are an expert researcher with deep knowledge of content creation."
+ )
+
+ outliner = Agent(
+ role="Content Strategist",
+ goal=f"Create an engaging outline for a {self.state.content_type}",
+ backstory="You excel at structuring content for maximum engagement."
+ )
+
+ research_task = Task(
+ description=f"Research {self.state.topic} focusing on what would interest {self.state.target_audience}",
+ expected_output="Comprehensive research notes with key points and statistics",
+ agent=researcher
+ )
+
+ outline_task = Task(
+ description=f"Create an outline for a {self.state.content_type} about {self.state.topic}",
+ expected_output="Detailed content outline with sections and key points",
+ agent=outliner,
+ context=[research_task]
+ )
+
+ outline_crew = Crew(
+ agents=[researcher, outliner],
+ tasks=[research_task, outline_task],
+ process=Process.sequential,
+ verbose=True
+ )
+
+ # Run the crew and store the result
+ result = outline_crew.kickoff()
+
+ # Parse the outline (in a real app, you might use a more robust parsing approach)
+ import json
+ try:
+ self.state.outline = json.loads(result.raw)
+ except:
+ # Fallback if not valid JSON
+ self.state.outline = {"sections": result.raw}
+
+ return "Outline created"
+
+ @listen(create_outline)
+ def write_content(self, _):
+ # Use a writing crew to create the content
+ writer = Agent(
+ role="Content Writer",
+ goal=f"Write engaging content for {self.state.target_audience}",
+ backstory="You are a skilled writer who creates compelling content."
+ )
+
+ editor = Agent(
+ role="Content Editor",
+ goal="Ensure content is polished, accurate, and engaging",
+ backstory="You have a keen eye for detail and a talent for improving content."
+ )
+
+ writing_task = Task(
+ description=f"Write a {self.state.content_type} about {self.state.topic} following this outline: {self.state.outline}",
+ expected_output="Complete draft content in markdown format",
+ agent=writer
+ )
+
+ editing_task = Task(
+ description="Edit and improve the draft content for clarity, engagement, and accuracy",
+ expected_output="Polished final content in markdown format",
+ agent=editor,
+ context=[writing_task]
+ )
+
+ writing_crew = Crew(
+ agents=[writer, editor],
+ tasks=[writing_task, editing_task],
+ process=Process.sequential,
+ verbose=True
+ )
+
+ # Run the crew and store the result
+ result = writing_crew.kickoff()
+ self.state.final_content = result.raw
+
+ return "Content created"
+
+ @listen(write_content)
+ def optimize_for_seo(self, _):
+ # Use a direct LLM call for SEO optimization
+ from crewai import LLM
+ llm = LLM(model="openai/gpt-4o-mini")
+
+ prompt = f"""
+ Analyze this content for SEO effectiveness for the keyword "{self.state.topic}".
+ Rate it on a scale of 1-100 and provide 3 specific recommendations for improvement.
+
+ Content: {self.state.final_content[:1000]}... (truncated for brevity)
+
+ Format your response as JSON with the following structure:
+ {{
+ "score": 85,
+ "recommendations": [
+ "Recommendation 1",
+ "Recommendation 2",
+ "Recommendation 3"
+ ]
+ }}
+ """
+
+ seo_analysis = llm.call(prompt)
+
+ # Parse the SEO analysis
+ import json
+ try:
+ analysis = json.loads(seo_analysis)
+ self.state.seo_score = analysis.get("score", 0)
+ return analysis
+ except:
+ self.state.seo_score = 50
+ return {"score": 50, "recommendations": ["Unable to parse SEO analysis"]}
+
+# Run the flow
+content_flow = ContentProductionFlow()
+result = content_flow.kickoff()
+```
+
+## 실용적인 평가 프레임워크
+
+특정 사용 사례에 맞는 올바른 접근 방식을 결정하려면 다음 단계별 평가 프레임워크를 따르세요:
+
+### 1단계: 복잡성 평가
+
+아래와 같은 기준으로 애플리케이션의 복잡성을 1~10점 척도로 평가하세요:
+
+1. **단계 수**: 얼마나 많은 개별 작업이 필요한가요?
+ - 1-3단계: 낮은 복잡성 (1-3)
+ - 4-7단계: 중간 복잡성 (4-7)
+ - 8단계 이상: 높은 복잡성 (8-10)
+
+2. **상호 의존성**: 서로 다른 부분 간의 연결성은 어느 정도인가요?
+ - 의존성이 거의 없음: 낮은 복잡성 (1-3)
+ - 다소 의존성 있음: 중간 복잡성 (4-7)
+ - 복잡한 다중 의존성: 높은 복잡성 (8-10)
+
+3. **조건부 논리**: 얼마나 많은 분기 및 의사결정이 필요한가요?
+ - 선형 프로세스: 낮은 복잡성 (1-3)
+ - 분기가 일부 있음: 중간 복잡성 (4-7)
+ - 복잡한 결정 트리: 높은 복잡성 (8-10)
+
+4. **도메인 지식**: 요구되는 지식의 전문성은 어느 정도인가요?
+ - 일반적인 지식: 낮은 복잡성 (1-3)
+ - 일부 전문 지식 필요: 중간 복잡성 (4-7)
+ - 여러 도메인에 대한 깊은 전문성 필요: 높은 복잡성 (8-10)
+
+평균 점수를 계산하여 전체 복잡성을 결정하세요.
+
+### 2단계: 정밀도 요구사항 평가
+
+정밀도 요구사항을 1-10점 척도로 평가하세요. 다음을 고려합니다:
+
+1. **출력 구조**: 출력이 얼마나 구조화되어야 합니까?
+ - 자유형 텍스트: 낮은 정밀도 (1-3)
+ - 반구조화: 중간 정밀도 (4-7)
+ - 엄격한 포맷(JSON, XML): 높은 정밀도 (8-10)
+
+2. **정확성 필요성**: 사실적 정확성이 얼마나 중요합니까?
+ - 창의적 콘텐츠: 낮은 정밀도 (1-3)
+ - 정보성 콘텐츠: 중간 정밀도 (4-7)
+ - 중요한 정보: 높은 정밀도 (8-10)
+
+3. **재현성**: 실행마다 결과가 얼마나 일관되어야 합니까?
+ - 변동 허용: 낮은 정밀도 (1-3)
+ - 어느 정도 일관성 필요: 중간 정밀도 (4-7)
+ - 정확한 재현성 필요: 높은 정밀도 (8-10)
+
+4. **오류 허용도**: 오류의 영향은 어느 정도입니까?
+ - 영향 적음: 낮은 정밀도 (1-3)
+ - 영향 보통: 중간 정밀도 (4-7)
+ - 영향 큼: 높은 정밀도 (8-10)
+
+평균 점수를 계산하여 전체 정밀도 요구사항을 결정하세요.
+
+### 3단계: 매트릭스에 매핑하기
+
+복잡도와 정밀도 점수를 매트릭스에 표시하세요:
+
+- **낮은 복잡도(1-4), 낮은 정밀도(1-4)**: Simple Crews
+- **낮은 복잡도(1-4), 높은 정밀도(5-10)**: 직접적인 LLM 호출이 있는 Flows
+- **높은 복잡도(5-10), 낮은 정밀도(1-4)**: Complex Crews
+- **높은 복잡도(5-10), 높은 정밀도(5-10)**: Crews를 오케스트레이션하는 Flows
+
+### 4단계: 추가 요소 고려
+
+복잡성과 정밀성 외에도 다음을 고려하세요:
+
+1. **개발 시간**: crew는 프로토타입을 더 빠르게 만들 수 있습니다
+2. **유지보수 필요**: flow는 장기적인 유지보수에 더 적합합니다
+3. **팀 전문성**: 팀이 다양한 접근법에 얼마나 익숙한지 고려하세요
+4. **확장성 요구 사항**: flow는 일반적으로 복잡한 애플리케이션에 더 잘 확장됩니다
+5. **통합 필요**: 솔루션이 기존 시스템과 어떻게 통합될지 고려하세요
+
+## 결론
+
+Crews와 Flows 중에서 선택하거나 결합하는 것은 CrewAI 애플리케이션의 효과성, 유지 관리성, 확장성에 영향을 미치는 중요한 아키텍처적 결정입니다. 복잡성과 정밀성이라는 차원에서 사용 사례를 평가함으로써, 귀하의 특정 요구 사항에 부합하는 정보에 기반한 결정을 내릴 수 있습니다.
+
+가장 좋은 접근방식은 애플리케이션이 성숙해지면서 종종 진화한다는 점을 기억하세요. 귀하의 요구를 충족하는 가장 간단한 해결책으로 시작하고, 경험이 쌓이고 요구 사항이 명확해지면 아키텍처를 개선할 준비를 하세요.
+
+
+
+
+## 2단계: 프로젝트 구조 이해하기
+
+생성된 프로젝트는 다음과 같은 구조를 가지고 있습니다. 시작용 embedded crew는 클래식 Python/YAML 레이아웃을 사용합니다. Flow 안에서 JSON-first crew를 사용하려면 crew 폴더에 `crew.jsonc`와 `agents/*.jsonc`를 만들고 `crewai.project.load_crew`로 로드하세요. 예시는 [Flows](/ko/concepts/flows#building-your-crews)를 참고하세요.
+
+```
+guide_creator_flow/
+├── .gitignore
+├── pyproject.toml
+├── README.md
+├── .env
+└── src/
+ └── guide_creator_flow/
+ ├── __init__.py
+ ├── main.py
+ ├── crews/
+ │ └── poem_crew/
+ │ ├── config/
+ │ │ ├── agents.yaml
+ │ │ └── tasks.yaml
+ │ └── poem_crew.py
+ └── tools/
+ └── custom_tool.py
+```
+
+이 구조는 flow의 다양한 구성 요소를 명확하게 분리해줍니다:
+- `src/guide_creator_flow/main.py` 파일의 main flow 로직
+- `src/guide_creator_flow/crews` 디렉터리의 특화된 crew들
+- `src/guide_creator_flow/tools` 디렉터리의 custom tool들
+
+이제 이 구조를 수정하여 guide creator flow를 만들 것입니다. 이 flow는 포괄적인 학습 가이드 생성을 조직하는 역할을 합니다.
+
+## 3단계: Content Writer Crew 추가
+
+우리 flow에는 콘텐츠 생성 프로세스를 처리할 전문화된 crew가 필요합니다. CrewAI CLI를 사용하여 content writer crew를 추가해봅시다:
+
+```bash
+crewai flow add-crew content-crew
+```
+
+이 명령어는 자동으로 crew에 필요한 디렉터리와 템플릿 파일을 생성합니다. content writer crew는 가이드의 각 섹션을 작성하고 검토하는 역할을 담당하며, 메인 애플리케이션에 의해 조율되는 전체 flow 내에서 작업하게 됩니다.
+
+## 4단계: 콘텐츠 작가 Crew 구성
+
+이제 콘텐츠 작가 crew를 JSONC로 구성합니다. 가이드의 고품질 콘텐츠를 만들기 위해 협업하는 두 명의 전문 에이전트 - 작가와 리뷰어 - 를 설정합니다.
+
+1. `src/guide_creator_flow/crews/content_crew/agents/content_writer.jsonc`를 만듭니다:
+
+```jsonc
+{
+ "role": "Educational Content Writer",
+ "goal": "Create engaging, informative content that thoroughly explains the assigned topic and provides valuable insights to the reader.",
+ "backstory": "You are a talented educational writer who explains complex concepts in accessible language and organizes information clearly.",
+ "llm": "provider/model-id",
+ "settings": {
+ "verbose": true
+ }
+}
+```
+
+2. `src/guide_creator_flow/crews/content_crew/agents/content_reviewer.jsonc`를 만듭니다:
+
+```jsonc
+{
+ "role": "Educational Content Reviewer and Editor",
+ "goal": "Ensure content is accurate, comprehensive, well-structured, and consistent with previously written sections.",
+ "backstory": "You are a meticulous editor with an eye for detail, clarity, and coherence.",
+ "llm": "provider/model-id",
+ "settings": {
+ "verbose": true
+ }
+}
+```
+
+`provider/model-id`를 사용하는 모델로 바꾸세요. 예: `openai/gpt-4o`, `gemini/gemini-2.0-flash-001`, `anthropic/claude-sonnet-4-6`.
+
+3. `src/guide_creator_flow/crews/content_crew/crew.jsonc`를 만듭니다:
+
+```jsonc
+{
+ "name": "Content Crew",
+ "agents": ["content_writer", "content_reviewer"],
+ "tasks": [
+ {
+ "name": "write_section_task",
+ "description": "Write a comprehensive section on the topic: \"{section_title}\".\n\nSection description: {section_description}\nTarget audience: {audience_level} level learners\n\nYour content should begin with a brief introduction, explain key concepts clearly with examples, include practical applications where appropriate, end with a summary, and be approximately 500-800 words.\n\nPreviously written sections:\n{previous_sections}",
+ "expected_output": "A well-structured, comprehensive section in Markdown format that thoroughly explains the topic and is appropriate for the target audience.",
+ "agent": "content_writer",
+ "markdown": true
+ },
+ {
+ "name": "review_section_task",
+ "description": "Review and improve this section on \"{section_title}\":\n\n{draft_content}\n\nTarget audience: {audience_level} level learners\nPreviously written sections:\n{previous_sections}\n\nFix errors, improve clarity, verify consistency, enhance structure, and add missing key information.",
+ "expected_output": "An improved, polished version of the section that maintains the original structure but enhances clarity, accuracy, and consistency.",
+ "agent": "content_reviewer",
+ "context": ["write_section_task"],
+ "markdown": true
+ }
+ ],
+ "process": "sequential",
+ "verbose": true
+}
+```
+
+`context` 필드를 통해 리뷰어가 작가의 출력을 사용할 수 있습니다.
+
+4. `src/guide_creator_flow/crews/content_crew/content_crew.py`를 작은 loader로 교체합니다:
+
+```python
+from pathlib import Path
+
+from crewai.project import load_crew
+
+
+def kickoff_content_crew(inputs: dict):
+ crew, default_inputs = load_crew(Path(__file__).with_name("crew.jsonc"))
+ return crew.kickoff(inputs={**default_inputs, **inputs})
+```
+
+이 loader는 런타임에 `crew.jsonc`를 `Crew`로 바꿉니다. 이 crew는 독립적으로도 작동할 수 있지만, 우리의 플로우에서는 더 큰 시스템의 일부로 오케스트레이션됩니다.
+
+## 5단계: 플로우(Flow) 생성
+
+이제 가장 흥미로운 부분입니다 - 전체 가이드 생성 과정을 오케스트레이션할 플로우를 만드는 단계입니다. 이곳에서 우리는 일반 Python 코드, 직접적인 LLM 호출, 그리고 우리의 컨텐츠 제작 crew를 결합하여 일관된 시스템으로 만듭니다.
+
+우리의 플로우는 다음과 같은 일을 수행합니다:
+1. 주제와 대상 독자 수준에 대한 사용자 입력을 받습니다.
+2. 구조화된 가이드 개요를 만들기 위해 직접 LLM 호출을 합니다.
+3. 컨텐츠 writer crew를 사용하여 각 섹션을 순차적으로 처리합니다.
+4. 모든 내용을 결합하여 최종 종합 문서를 완성합니다.
+
+`main.py` 파일에 우리의 플로우를 생성해봅시다:
+
+```python
+#!/usr/bin/env python
+import json
+import os
+from typing import List, Dict
+from pydantic import BaseModel, Field
+from crewai import LLM
+from crewai.flow.flow import Flow, listen, start
+from guide_creator_flow.crews.content_crew.content_crew import kickoff_content_crew
+
+# Define our models for structured data
+class Section(BaseModel):
+ title: str = Field(description="Title of the section")
+ description: str = Field(description="Brief description of what the section should cover")
+
+class GuideOutline(BaseModel):
+ title: str = Field(description="Title of the guide")
+ introduction: str = Field(description="Introduction to the topic")
+ target_audience: str = Field(description="Description of the target audience")
+ sections: List[Section] = Field(description="List of sections in the guide")
+ conclusion: str = Field(description="Conclusion or summary of the guide")
+
+# Define our flow state
+class GuideCreatorState(BaseModel):
+ topic: str = ""
+ audience_level: str = ""
+ guide_outline: GuideOutline = None
+ sections_content: Dict[str, str] = {}
+
+class GuideCreatorFlow(Flow[GuideCreatorState]):
+ """Flow for creating a comprehensive guide on any topic"""
+
+ @start()
+ def get_user_input(self):
+ """Get input from the user about the guide topic and audience"""
+ print("\n=== Create Your Comprehensive Guide ===\n")
+
+ # Get user input
+ self.state.topic = input("What topic would you like to create a guide for? ")
+
+ # Get audience level with validation
+ while True:
+ audience = input("Who is your target audience? (beginner/intermediate/advanced) ").lower()
+ if audience in ["beginner", "intermediate", "advanced"]:
+ self.state.audience_level = audience
+ break
+ print("Please enter 'beginner', 'intermediate', or 'advanced'")
+
+ print(f"\nCreating a guide on {self.state.topic} for {self.state.audience_level} audience...\n")
+ return self.state
+
+ @listen(get_user_input)
+ def create_guide_outline(self, state):
+ """Create a structured outline for the guide using a direct LLM call"""
+ print("Creating guide outline...")
+
+ # Initialize the LLM
+ llm = LLM(model="openai/gpt-4o-mini", response_format=GuideOutline)
+
+ # Create the messages for the outline
+ messages = [
+ {"role": "system", "content": "You are a helpful assistant designed to output JSON."},
+ {"role": "user", "content": f"""
+ Create a detailed outline for a comprehensive guide on "{state.topic}" for {state.audience_level} level learners.
+
+ The outline should include:
+ 1. A compelling title for the guide
+ 2. An introduction to the topic
+ 3. 4-6 main sections that cover the most important aspects of the topic
+ 4. A conclusion or summary
+
+ For each section, provide a clear title and a brief description of what it should cover.
+ """}
+ ]
+
+ # Make the LLM call with JSON response format
+ response = llm.call(messages=messages)
+
+ # Parse the JSON response
+ outline_dict = json.loads(response)
+ self.state.guide_outline = GuideOutline(**outline_dict)
+
+ # Ensure output directory exists before saving
+ os.makedirs("output", exist_ok=True)
+
+ # Save the outline to a file
+ with open("output/guide_outline.json", "w") as f:
+ json.dump(outline_dict, f, indent=2)
+
+ print(f"Guide outline created with {len(self.state.guide_outline.sections)} sections")
+ return self.state.guide_outline
+
+ @listen(create_guide_outline)
+ def write_and_compile_guide(self, outline):
+ """Write all sections and compile the guide"""
+ print("Writing guide sections and compiling...")
+ completed_sections = []
+
+ # Process sections one by one to maintain context flow
+ for section in outline.sections:
+ print(f"Processing section: {section.title}")
+
+ # Build context from previous sections
+ previous_sections_text = ""
+ if completed_sections:
+ previous_sections_text = "# Previously Written Sections\n\n"
+ for title in completed_sections:
+ previous_sections_text += f"## {title}\n\n"
+ previous_sections_text += self.state.sections_content.get(title, "") + "\n\n"
+ else:
+ previous_sections_text = "No previous sections written yet."
+
+ # Run the content crew for this section
+ result = kickoff_content_crew(inputs={
+ "section_title": section.title,
+ "section_description": section.description,
+ "audience_level": self.state.audience_level,
+ "previous_sections": previous_sections_text,
+ "draft_content": ""
+ })
+
+ # Store the content
+ self.state.sections_content[section.title] = result.raw
+ completed_sections.append(section.title)
+ print(f"Section completed: {section.title}")
+
+ # Compile the final guide
+ guide_content = f"# {outline.title}\n\n"
+ guide_content += f"## Introduction\n\n{outline.introduction}\n\n"
+
+ # Add each section in order
+ for section in outline.sections:
+ section_content = self.state.sections_content.get(section.title, "")
+ guide_content += f"\n\n{section_content}\n\n"
+
+ # Add conclusion
+ guide_content += f"## Conclusion\n\n{outline.conclusion}\n\n"
+
+ # Save the guide
+ with open("output/complete_guide.md", "w") as f:
+ f.write(guide_content)
+
+ print("\nComplete guide compiled and saved to output/complete_guide.md")
+ return "Guide creation completed successfully"
+
+def kickoff():
+ """Run the guide creator flow"""
+ GuideCreatorFlow().kickoff()
+ print("\n=== Flow Complete ===")
+ print("Your comprehensive guide is ready in the output directory.")
+ print("Open output/complete_guide.md to view it.")
+
+def plot():
+ """Generate a visualization of the flow"""
+ flow = GuideCreatorFlow()
+ flow.plot("guide_creator_flow")
+ print("Flow visualization saved to guide_creator_flow.html")
+
+if __name__ == "__main__":
+ kickoff()
+```
+
+이 플로우에서 일어나는 과정을 분석해봅시다:
+
+1. 구조화된 데이터에 대한 Pydantic 모델을 정의하여 타입 안전성과 명확한 데이터 표현을 보장합니다.
+2. 플로우 단계별로 데이터를 유지하기 위한 state 클래스를 생성합니다.
+3. 세 가지 주요 플로우 단계를 구현합니다:
+ - `@start()` 데코레이터로 사용자 입력을 받습니다.
+ - 직접 LLM 호출로 가이드 개요를 생성합니다.
+ - content crew로 각 섹션을 처리합니다.
+4. `@listen()` 데코레이터를 활용해 단계 간 이벤트 기반 관계를 설정합니다.
+
+이것이 바로 flows의 힘입니다 - 다양한 처리 유형(사용자 상호작용, 직접적인 LLM 호출, crew 기반 작업)을 하나의 일관된 이벤트 기반 시스템으로 결합할 수 있습니다.
+
+## 6단계: 환경 변수 설정하기
+
+프로젝트 루트에 `.env` 파일을 생성하고 API 키를 입력하세요. 공급자 구성에 대한 자세한 내용은 [LLM 설정 가이드](/ko/concepts/llms#setting-up-your-llm)를 참고하세요.
+
+```sh .env
+OPENAI_API_KEY=your_openai_api_key
+# or
+GEMINI_API_KEY=your_gemini_api_key
+# or
+ANTHROPIC_API_KEY=your_anthropic_api_key
+```
+
+## 7단계: 의존성 설치
+
+필수 의존성을 설치합니다:
+
+```bash
+crewai install
+```
+
+## 8단계: Flow 실행하기
+
+이제 여러분의 flow가 실제로 작동하는 모습을 볼 차례입니다! CrewAI CLI를 사용하여 flow를 실행하세요:
+
+```bash
+crewai run
+```
+
+이 명령어를 실행하면 flow가 다음과 같이 작동하는 것을 확인할 수 있습니다:
+1. 주제와 대상 수준을 입력하라는 메시지가 표시됩니다.
+2. 가이드의 체계적인 개요를 생성합니다.
+3. 각 섹션을 처리할 때 content writer와 reviewer가 협업합니다.
+4. 마지막으로 모든 내용을 종합하여 완성도 높은 가이드를 만듭니다.
+
+이는 여러 구성요소(인공지능 및 비인공지능 모두)가 포함된 복잡한 프로세스를 flows가 어떻게 조정할 수 있는지 보여줍니다.
+
+## 9단계: Flow 시각화하기
+
+flow의 강력한 기능 중 하나는 구조를 시각화할 수 있다는 점입니다.
+
+```bash
+crewai flow plot
+```
+
+이 명령은 flow의 구조를 보여주는 HTML 파일을 생성하며, 각 단계 간의 관계와 그 사이에 흐르는 데이터를 확인할 수 있습니다. 이러한 시각화는 복잡한 flow를 이해하고 디버깅하는 데 매우 유용합니다.
+
+## 10단계: 출력물 검토하기
+
+flow가 완료되면 `output` 디렉토리에서 두 개의 파일을 찾을 수 있습니다:
+
+1. `guide_outline.json`: 가이드의 구조화된 개요가 포함되어 있습니다
+2. `complete_guide.md`: 모든 섹션이 포함된 종합적인 가이드입니다
+
+이 파일들을 잠시 검토하고 여러분이 구축한 시스템을 되돌아보세요. 이 시스템은 사용자 입력, 직접적인 AI 상호작용, 협업 에이전트 작업을 결합하여 복잡하고 고품질의 결과물을 만들어냅니다.
+
+## 가능한 것의 예술: 첫 번째 Flow 그 이상
+
+이 가이드에서 배운 내용은 훨씬 더 정교한 AI 시스템을 만드는 데 기반이 됩니다. 다음은 이 기본 flow를 확장할 수 있는 몇 가지 방법입니다:
+
+### 사용자 상호작용 향상
+
+더욱 인터랙티브한 플로우를 만들 수 있습니다:
+- 입력 및 출력을 위한 웹 인터페이스
+- 실시간 진행 상황 업데이트
+- 인터랙티브한 피드백 및 개선 루프
+- 다단계 사용자 상호작용
+
+### 추가 처리 단계 추가하기
+
+다음과 같은 추가 단계로 flow를 확장할 수 있습니다:
+- 개요 작성 전 사전 리서치
+- 일러스트를 위한 이미지 생성
+- 기술 가이드용 코드 스니펫 생성
+- 최종 품질 보증 및 사실 확인
+
+### 더 복잡한 Flows 생성하기
+
+더 정교한 flow 패턴을 구현할 수 있습니다:
+- 사용자 선호도나 콘텐츠 유형에 따른 조건 분기
+- 독립적인 섹션의 병렬 처리
+- 피드백과 함께하는 반복적 개선 루프
+- 외부 API 및 서비스와의 통합
+
+### 다양한 도메인에 적용하기
+
+동일한 패턴을 사용하여 다음과 같은 flow를 만들 수 있습니다:
+- **대화형 스토리텔링**: 사용자 입력을 바탕으로 개인화된 이야기를 생성
+- **비즈니스 인텔리전스**: 데이터를 처리하고, 인사이트를 도출하며, 리포트를 생성
+- **제품 개발**: 아이디어 구상, 디자인, 기획을 지원
+- **교육 시스템**: 개인화된 학습 경험을 제공
+
+## 주요 특징 시연
+
+이 guide creator flow에서는 CrewAI의 여러 강력한 기능을 시연합니다:
+
+1. **사용자 상호작용**: flow는 사용자로부터 직접 입력을 수집합니다
+2. **직접적인 LLM 호출**: 효율적이고 단일 목적의 AI 상호작용을 위해 LLM 클래스를 사용합니다
+3. **Pydantic을 통한 구조화된 데이터**: 타입 안정성을 보장하기 위해 Pydantic 모델을 사용합니다
+4. **컨텍스트를 활용한 순차 처리**: 섹션을 순서대로 작성하면서 이전 섹션을 컨텍스트로 제공합니다
+5. **멀티 에이전트 crew**: 콘텐츠 생성을 위해 특화된 에이전트(writer 및 reviewer)를 활용합니다
+6. **상태 관리**: 프로세스의 다양한 단계에 걸쳐 상태를 유지합니다
+7. **이벤트 기반 아키텍처**: 이벤트에 응답하기 위해 `@listen` 데코레이터를 사용합니다
+
+## 플로우 구조 이해하기
+
+플로우의 주요 구성 요소를 분해하여 자신만의 플로우를 만드는 방법을 이해할 수 있도록 도와드리겠습니다:
+
+### 1. 직접 LLM 호출
+
+Flow를 사용하면 간단하고 구조화된 응답이 필요할 때 언어 모델에 직접 호출할 수 있습니다:
+
+```python
+llm = LLM(
+ model="model-id-here", # gpt-4o, gemini-2.0-flash, anthropic/claude...
+ response_format=GuideOutline
+)
+response = llm.call(messages=messages)
+```
+
+특정하고 구조화된 출력이 필요할 때 crew를 사용하는 것보다 더 효율적입니다.
+
+### 2. 이벤트 기반 아키텍처
+
+Flows는 데코레이터를 사용하여 컴포넌트 간의 관계를 설정합니다:
+
+```python
+@start()
+def get_user_input(self):
+ # First step in the flow
+ # ...
+
+@listen(get_user_input)
+def create_guide_outline(self, state):
+ # This runs when get_user_input completes
+ # ...
+```
+
+이렇게 하면 애플리케이션에 명확하고 선언적인 구조가 만들어집니다.
+
+### 3. 상태 관리
+
+flow는 단계 간 상태를 유지하여 데이터를 쉽게 공유할 수 있습니다:
+
+```python
+class GuideCreatorState(BaseModel):
+ topic: str = ""
+ audience_level: str = ""
+ guide_outline: GuideOutline = None
+ sections_content: Dict[str, str] = {}
+```
+
+이 방식은 flow 전반에 걸쳐 데이터를 추적하고 변환하는 타입 안전(type-safe)한 방법을 제공합니다.
+
+### 4. Crew 통합
+
+Flow는 복잡한 협업 작업을 위해 crew와 원활하게 통합될 수 있습니다:
+
+```python
+result = kickoff_content_crew(inputs={
+ "section_title": section.title,
+ # ...
+})
+```
+
+이를 통해 애플리케이션의 각 부분에 적합한 도구를 사용할 수 있습니다. 단순한 작업에는 직접적인 LLM 호출을, 복잡한 협업에는 crew를 사용할 수 있습니다.
+
+## 다음 단계
+
+이제 첫 번째 flow를 구축했으니 다음을 시도해 볼 수 있습니다:
+
+1. 더 복잡한 flow 구조와 패턴을 실험해 보세요.
+2. `@router()`를 사용하여 flow에서 조건부 분기를 만들어 보세요.
+3. 더 복잡한 병렬 실행을 위해 `and_` 및 `or_` 함수를 탐색해 보세요.
+4. flow를 외부 API, 데이터베이스 또는 사용자 인터페이스에 연결해 보세요.
+5. 여러 전문화된 crew를 하나의 flow에서 결합해 보세요.
+6. [대화형 Flow](/ko/guides/flows/conversational-flows)로 멀티턴 채팅 앱 구축 (`kickoff` per message, `ChatSession`, 지연 트레이싱)
+
+
+ + 에이전트를 설계하고 크루를 오케스트레이션하며 guardrails, 메모리, 지식, Observability가 기본 내장된 플로우를 자동화하세요. +
+
+
+
+Flows의 기능:
+- **상태 관리**: 단계 및 실행 전반에 걸쳐 데이터를 유지합니다.
+- **이벤트 기반 실행**: 이벤트 또는 외부 입력을 기반으로 작업을 트리거합니다.
+- **제어 흐름**: 조건부 로직, 반복문, 분기를 사용합니다.
+
+### 2. Crews: 지능 (Intelligence)
+
+
+
+
+Crews의 기능:
+- **역할 수행 Agent**: 특정 목표와 도구를 가진 전문 agent입니다.
+- **자율 협업**: agent들이 협력하여 작업을 해결합니다.
+- **작업 위임**: agent의 능력에 따라 작업이 할당되고 실행됩니다.
+
+## 전체 작동 방식
+
+1. **Flow**가 이벤트를 트리거하거나 프로세스를 시작합니다.
+2. **Flow**가 상태를 관리하고 다음에 무엇을 할지 결정합니다.
+3. **Flow**가 복잡한 작업을 **Crew**에게 위임합니다.
+4. **Crew**의 agent들이 협력하여 작업을 완료합니다.
+5. **Crew**가 결과를 **Flow**에 반환합니다.
+6. **Flow**가 결과를 바탕으로 실행을 계속합니다.
+
+## 주요 기능
+
+
+
+
+## 모범 사례
+
+1. **이미지 생성 프롬프트를 구체적으로 작성하세요**. 그래야 최상의 결과를 얻을 수 있습니다.
+2. **생성 시간을 고려하세요** - 이미지 생성에는 시간이 걸릴 수 있으므로 작업 계획에 이를 반영하세요.
+3. **사용 정책을 준수하세요** - 이미지를 생성할 때 항상 OpenAI의 사용 정책을 준수해야 합니다.
+
+## 문제 해결
+
+1. **API 접근 확인** - OpenAI API 키가 DALL-E에 접근 권한이 있는지 확인하세요.
+2. **버전 호환성** - 최신 버전의 crewAI와 crewai-tools를 사용하고 있는지 확인하세요.
+3. **도구 구성** - DALL-E 도구가 agent의 도구 목록에 올바르게 추가되어 있는지 확인하세요.
\ No newline at end of file
diff --git a/docs/v1.15.13/ko/learn/execution-hooks.mdx b/docs/v1.15.13/ko/learn/execution-hooks.mdx
new file mode 100644
index 0000000000..4254f053c8
--- /dev/null
+++ b/docs/v1.15.13/ko/learn/execution-hooks.mdx
@@ -0,0 +1,379 @@
+---
+title: 실행 훅 개요
+description: 에이전트 작업에 대한 세밀한 제어를 위한 CrewAI 실행 훅 이해 및 사용
+mode: "wide"
+---
+
+실행 훅(Execution Hooks)은 CrewAI 에이전트의 런타임 동작을 세밀하게 제어할 수 있게 해줍니다. 크루 실행 전후에 실행되는 킥오프 훅과 달리, 실행 훅은 에이전트 실행 중 특정 작업을 가로채서 동작을 수정하고, 안전성 검사를 구현하며, 포괄적인 모니터링을 추가할 수 있습니다.
+
+## 실행 훅의 유형
+
+CrewAI는 두 가지 주요 범주의 실행 훅을 제공합니다:
+
+### 1. [LLM 호출 훅](/learn/llm-hooks)
+
+언어 모델 상호작용을 제어하고 모니터링합니다:
+- **LLM 호출 전**: 프롬프트 수정, 입력 검증, 승인 게이트 구현
+- **LLM 호출 후**: 응답 변환, 출력 정제, 대화 기록 업데이트
+
+**사용 사례:**
+- 반복 제한
+- 비용 추적 및 토큰 사용량 모니터링
+- 응답 정제 및 콘텐츠 필터링
+- LLM 호출에 대한 사람의 승인
+- 안전 가이드라인 또는 컨텍스트 추가
+- 디버그 로깅 및 요청/응답 검사
+
+[LLM 훅 문서 보기 →](/learn/llm-hooks)
+
+### 2. [도구 호출 훅](/learn/tool-hooks)
+
+도구 실행을 제어하고 모니터링합니다:
+- **도구 호출 전**: 입력 수정, 매개변수 검증, 위험한 작업 차단
+- **도구 호출 후**: 결과 변환, 출력 정제, 실행 세부사항 로깅
+
+**사용 사례:**
+- 파괴적인 작업에 대한 안전 가드레일
+- 민감한 작업에 대한 사람의 승인
+- 입력 검증 및 정제
+- 결과 캐싱 및 속도 제한
+- 도구 사용 분석
+- 디버그 로깅 및 모니터링
+
+[도구 훅 문서 보기 →](/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):
+ """LLM 응답에서 민감한 데이터를 제거합니다."""
+ if "API_KEY" in context.response:
+ return context.response.replace("API_KEY", "[수정됨]")
+ return None
+
+@before_tool_call
+def block_dangerous_tools(context):
+ """파괴적인 작업을 차단합니다."""
+ if context.tool_name == "delete_database":
+ return False # 실행 차단
+ return None
+
+@after_tool_call
+def log_tool_result(context):
+ """도구 실행을 로깅합니다."""
+ print(f"도구 {context.tool_name} 완료")
+ return None
+```
+
+### 2. 크루 범위 훅
+
+특정 크루 인스턴스에만 훅을 적용합니다:
+
+```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"{self.__class__.__name__}에서 LLM 호출")
+ return None
+
+ @after_tool_call_crew
+ def log_results(self, context):
+ # 크루별 로깅
+ print(f"도구 결과: {context.tool_result[:50]}...")
+ return None
+
+ @crew
+ def crew(self) -> Crew:
+ return Crew(
+ agents=self.agents,
+ tasks=self.tasks,
+ process=Process.sequential
+ )
+```
+
+## 훅 실행 흐름
+
+### LLM 호출 흐름
+
+```
+에이전트가 LLM을 호출해야 함
+ ↓
+[LLM 호출 전 훅 실행]
+ ├→ 훅 1: 반복 횟수 검증
+ ├→ 훅 2: 안전 컨텍스트 추가
+ └→ 훅 3: 요청 로깅
+ ↓
+훅이 False를 반환하는 경우:
+ ├→ LLM 호출 차단
+ └→ ValueError 발생
+ ↓
+모든 훅이 True/None을 반환하는 경우:
+ ├→ LLM 호출 진행
+ └→ 응답 생성
+ ↓
+[LLM 호출 후 훅 실행]
+ ├→ 훅 1: 응답 정제
+ ├→ 훅 2: 응답 로깅
+ └→ 훅 3: 메트릭 업데이트
+ ↓
+최종 응답 반환
+```
+
+### 도구 호출 흐름
+
+```
+에이전트가 도구를 실행해야 함
+ ↓
+[도구 호출 전 훅 실행]
+ ├→ 훅 1: 도구 허용 여부 확인
+ ├→ 훅 2: 입력 검증
+ └→ 훅 3: 필요시 승인 요청
+ ↓
+훅이 False를 반환하는 경우:
+ ├→ 도구 실행 차단
+ └→ 오류 메시지 반환
+ ↓
+모든 훅이 True/None을 반환하는 경우:
+ ├→ 도구 실행 진행
+ └→ 결과 생성
+ ↓
+[도구 호출 후 훅 실행]
+ ├→ 훅 1: 결과 정제
+ ├→ 훅 2: 결과 캐싱
+ └→ 훅 3: 메트릭 로깅
+ ↓
+최종 결과 반환
+```
+
+## 훅 컨텍스트 객체
+
+### LLMCallHookContext
+
+LLM 실행 상태에 대한 액세스를 제공합니다:
+
+```python
+class LLMCallHookContext:
+ executor: CrewAgentExecutor # 전체 실행자 액세스
+ messages: list # 변경 가능한 메시지 목록
+ agent: Agent # 현재 에이전트
+ task: Task # 현재 작업
+ crew: Crew # 크루 인스턴스
+ llm: BaseLLM # LLM 인스턴스
+ iterations: int # 현재 반복 횟수
+ response: str | None # LLM 응답 (후 훅용)
+```
+
+### ToolCallHookContext
+
+도구 실행 상태에 대한 액세스를 제공합니다:
+
+```python
+class ToolCallHookContext:
+ tool_name: str # 호출되는 도구
+ tool_input: dict # 변경 가능한 입력 매개변수
+ tool: CrewStructuredTool # 도구 인스턴스
+ agent: Agent | None # 실행 중인 에이전트
+ task: Task | None # 현재 작업
+ crew: Crew | None # 크루 인스턴스
+ tool_result: str | None # 도구 결과 (후 훅용)
+```
+
+## 일반적인 패턴
+
+### 안전 및 검증
+
+```python
+@before_tool_call
+def safety_check(context):
+ """파괴적인 작업을 차단합니다."""
+ dangerous = ['delete_file', 'drop_table', 'system_shutdown']
+ if context.tool_name in dangerous:
+ print(f"🛑 차단됨: {context.tool_name}")
+ return False
+ return None
+
+@before_llm_call
+def iteration_limit(context):
+ """무한 루프를 방지합니다."""
+ if context.iterations > 15:
+ print("⛔ 최대 반복 횟수 초과")
+ return False
+ return None
+```
+
+### 사람의 개입
+
+```python
+@before_tool_call
+def require_approval(context):
+ """민감한 작업에 대한 승인을 요구합니다."""
+ sensitive = ['send_email', 'make_payment', 'post_message']
+
+ if context.tool_name in sensitive:
+ response = context.request_human_input(
+ prompt=f"{context.tool_name} 승인하시겠습니까?",
+ default_message="승인하려면 'yes'를 입력하세요:"
+ )
+
+ if response.lower() != 'yes':
+ return False
+
+ return None
+```
+
+### 모니터링 및 분석
+
+```python
+from collections import defaultdict
+import time
+
+metrics = defaultdict(lambda: {'count': 0, 'total_time': 0})
+
+@before_tool_call
+def start_timer(context):
+ context.tool_input['_start'] = time.time()
+ return None
+
+@after_tool_call
+def track_metrics(context):
+ start = context.tool_input.get('_start', time.time())
+ duration = time.time() - start
+
+ metrics[context.tool_name]['count'] += 1
+ metrics[context.tool_name]['total_time'] += duration
+
+ return None
+```
+
+## 훅 관리
+
+### 모든 훅 지우기
+
+```python
+from crewai.hooks import clear_all_global_hooks
+
+# 모든 훅을 한 번에 지웁니다
+result = clear_all_global_hooks()
+print(f"{result['total']} 훅이 지워졌습니다")
+```
+
+### 특정 훅 유형 지우기
+
+```python
+from crewai.hooks import (
+ clear_before_llm_call_hooks,
+ clear_after_llm_call_hooks,
+ clear_before_tool_call_hooks,
+ clear_after_tool_call_hooks
+)
+
+# 특정 유형 지우기
+llm_before_count = clear_before_llm_call_hooks()
+tool_after_count = clear_after_tool_call_hooks()
+```
+
+## 모범 사례
+
+### 1. 훅을 집중적으로 유지
+각 훅은 단일하고 명확한 책임을 가져야 합니다.
+
+### 2. 오류를 우아하게 처리
+```python
+@before_llm_call
+def safe_hook(context):
+ try:
+ if some_condition:
+ return False
+ except Exception as e:
+ print(f"훅 오류: {e}")
+ return None # 오류에도 불구하고 실행 허용
+```
+
+### 3. 컨텍스트를 제자리에서 수정
+```python
+# ✅ 올바름 - 제자리에서 수정
+@before_llm_call
+def add_context(context):
+ context.messages.append({"role": "system", "content": "간결하게"})
+
+# ❌ 잘못됨 - 참조를 교체
+@before_llm_call
+def wrong_approach(context):
+ context.messages = [{"role": "system", "content": "간결하게"}]
+```
+
+### 4. 타입 힌트 사용
+```python
+from crewai.hooks import LLMCallHookContext, ToolCallHookContext
+
+def my_llm_hook(context: LLMCallHookContext) -> bool | None:
+ return None
+
+def my_tool_hook(context: ToolCallHookContext) -> str | None:
+ return None
+```
+
+### 5. 테스트에서 정리
+```python
+import pytest
+from crewai.hooks import clear_all_global_hooks
+
+@pytest.fixture(autouse=True)
+def clean_hooks():
+ """각 테스트 전에 훅을 재설정합니다."""
+ yield
+ clear_all_global_hooks()
+```
+
+## 어떤 훅을 사용해야 할까요
+
+### LLM 훅을 사용하는 경우:
+- 반복 제한 구현
+- 프롬프트에 컨텍스트 또는 안전 가이드라인 추가
+- 토큰 사용량 및 비용 추적
+- 응답 정제 또는 변환
+- LLM 호출에 대한 승인 게이트 구현
+- 프롬프트/응답 상호작용 디버깅
+
+### 도구 훅을 사용하는 경우:
+- 위험하거나 파괴적인 작업 차단
+- 실행 전 도구 입력 검증
+- 민감한 작업에 대한 승인 게이트 구현
+- 도구 결과 캐싱
+- 도구 사용 및 성능 추적
+- 도구 출력 정제
+- 도구 호출 속도 제한
+
+### 둘 다 사용하는 경우:
+모든 에이전트 작업을 모니터링해야 하는 포괄적인 관찰성, 안전 또는 승인 시스템을 구축하는 경우.
+
+## 관련 문서
+
+- [LLM 호출 훅 →](/learn/llm-hooks) - 상세한 LLM 훅 문서
+- [도구 호출 훅 →](/learn/tool-hooks) - 상세한 도구 훅 문서
+- [킥오프 전후 훅 →](/learn/before-and-after-kickoff-hooks) - 크루 생명주기 훅
+- [사람의 개입 →](/learn/human-in-the-loop) - 사람 입력 패턴
+
+## 결론
+
+실행 훅은 에이전트 런타임 동작에 대한 강력한 제어를 제공합니다. 이를 사용하여 안전 가드레일, 승인 워크플로우, 포괄적인 모니터링 및 사용자 정의 비즈니스 로직을 구현하세요. 적절한 오류 처리, 타입 안전성 및 성능 고려사항과 결합하면, 훅을 통해 프로덕션 준비가 된 안전하고 관찰 가능한 에이전트 시스템을 구축할 수 있습니다.
diff --git a/docs/v1.15.13/ko/learn/force-tool-output-as-result.mdx b/docs/v1.15.13/ko/learn/force-tool-output-as-result.mdx
new file mode 100644
index 0000000000..1a1da0a5f5
--- /dev/null
+++ b/docs/v1.15.13/ko/learn/force-tool-output-as-result.mdx
@@ -0,0 +1,51 @@
+---
+title: 도구 출력 결과로 강제 지정하기
+description: CrewAI에서 에이전트의 작업에서 도구 출력을 결과로 강제 지정하는 방법을 알아봅니다.
+icon: wrench-simple
+mode: "wide"
+---
+
+## 소개
+
+CrewAI에서는 도구의 출력을 에이전트 작업의 결과로 강제로 사용할 수 있습니다.
+이 기능은 작업 실행 중에 에이전트가 출력을 수정하지 못하도록 하고, 도구의 출력이 반드시 캡처되어 작업 결과로 반환되도록 보장하고 싶을 때 유용합니다.
+
+## 도구 출력을 결과로 강제 지정하기
+
+도구의 출력을 에이전트 작업의 결과로 강제 지정하려면, 에이전트에 도구를 추가할 때 `result_as_answer` 매개변수를 `True`로 설정해야 합니다.
+이 매개변수는 도구의 출력이 에이전트에 의해 수정되지 않고 작업 결과로 캡처되어 반환되도록 보장합니다.
+
+다음은 에이전트 작업의 결과로 도구 출력을 강제 지정하는 방법의 예시입니다:
+
+```python Code
+from crewai.agent import Agent
+from my_tool import MyCustomTool
+
+# Create a coding agent with the custom tool
+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)],
+ )
+
+# Assuming the tool's execution and result population occurs within the system
+task_result = coding_agent.execute_task(task)
+```
+
+## 워크플로우 실행
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+또한, 트레이스의 제어 및 데이터 흐름을 보여주는 트레이스의 실행 그래프 보기를 볼 수 있으며, 이는 더 큰 에이전트로 확장하여 LLM 호출, 도구 호출 및 에이전트 상호 작용 간의 핸드오프와 관계를 보여줍니다.
+
+
+
+
+
+## 참조
+
+- [Datadog LLM Observability](https://www.datadoghq.com/product/llm-observability/)
+- [Datadog LLM 옵저버빌리티 크루AI 자동 계측](https://docs.datadoghq.com/llm_observability/instrumentation/auto_instrumentation?tab=python#crew-ai)
diff --git a/docs/v1.15.13/ko/observability/galileo.mdx b/docs/v1.15.13/ko/observability/galileo.mdx
new file mode 100644
index 0000000000..f82b825740
--- /dev/null
+++ b/docs/v1.15.13/ko/observability/galileo.mdx
@@ -0,0 +1,115 @@
+---
+title: Galileo 갈릴레오
+description: CrewAI 추적 및 평가를 위한 Galileo 통합
+icon: telescope
+mode: "wide"
+---
+
+## 개요
+
+이 가이드는 **Galileo**를 **CrewAI**와 통합하는 방법을 보여줍니다.
+포괄적인 추적 및 평가 엔지니어링을 위한 것입니다.
+이 가이드가 끝나면 CrewAI 에이전트를 추적할 수 있게 됩니다.
+성과를 모니터링하고 행동을 평가합니다.
+Galileo의 강력한 관측 플랫폼.
+
+> **갈릴레오(Galileo)란 무엇인가요?**[Galileo](https://galileo.ai/)는 AI 평가 및 관찰 가능성입니다.
+엔드투엔드 추적, 평가,
+AI 애플리케이션 모니터링. 이를 통해 팀은 실제 사실을 포착할 수 있습니다.
+견고한 가드레일을 만들고 체계적인 실험을 실행하세요.
+내장된 실험 추적 및 성능 분석으로 신뢰성 보장
+AI 수명주기 전반에 걸쳐 투명성과 지속적인 개선을 제공합니다.
+
+## 시작하기
+
+이 튜토리얼은 [CrewAI 빠른 시작](/ko/quickstart.mdx)을 따르며 추가하는 방법을 보여줍니다.
+갈릴레오의 [CrewAIEventListener](https://v2docs.galileo.ai/sdk-api/python/reference/handlers/crewai/handler),
+이벤트 핸들러.
+자세한 내용은 갈릴레오 문서를 참고하세요.
+[CrewAI 애플리케이션에 Galileo 추가](https://v2docs.galileo.ai/how-to-guides/third-party-integrations/add-galileo-to-crewai/add-galileo-to-crewai)
+방법 안내.
+
+> **참고**이 튜토리얼에서는 [CrewAI 빠른 시작](/ko/quickstart.mdx)을 완료했다고 가정합니다.
+완전한 포괄적인 예제를 원한다면 Galileo
+[CrewAI SDK 예제 저장소](https://github.com/rungalileo/sdk-examples/tree/main/python/agent/crew-ai).
+
+### 1단계: 종속성 설치
+
+앱에 필요한 종속성을 설치합니다.
+원하는 방법으로 가상 환경을 생성하고,
+그런 다음 다음을 사용하여 해당 환경 내에 종속성을 설치하십시오.
+선호하는 도구:
+
+```bash
+uv add galileo
+```
+
+### 2단계: [CrewAI 빠른 시작](/ko/quickstart.mdx)에서 .env 파일에 추가
+
+```bash
+# Your Galileo API key
+GALILEO_API_KEY="your-galileo-api-key"
+
+# Your Galileo project name
+GALILEO_PROJECT="your-galileo-project-name"
+
+# The name of the Log stream you want to use for logging
+GALILEO_LOG_STREAM="your-galileo-log-stream "
+```
+
+### 3단계: Galileo 이벤트 리스너 추가
+
+Galileo로 로깅을 활성화하려면 `CrewAIEventListener`의 인스턴스를 생성해야 합니다.
+다음을 통해 Galileo CrewAI 핸들러 패키지를 가져옵니다.
+main.py 파일 상단에 다음 코드를 추가하세요.
+
+```python
+from galileo.handlers.crewai.handler import CrewAIEventListener
+```
+
+실행 함수 시작 시 이벤트 리스너를 생성합니다.
+
+```python
+def run():
+ # Create the event listener
+ CrewAIEventListener()
+ # The rest of your existing code goes here
+```
+
+리스너 인스턴스를 생성하면 자동으로
+CrewAI에 등록되었습니다.
+
+### 4단계: Crew Agent 실행
+
+CrewAI CLI를 사용하여 Crew Agent를 실행하세요.
+
+```bash
+crewai run
+```
+
+### 5단계: Galileo에서 추적 보기
+
+승무원 에이전트가 완료되면 흔적이 플러시되어 Galileo에 나타납니다.
+
+
+
+## 갈릴레오 통합 이해
+
+Galileo는 이벤트 리스너를 등록하여 CrewAI와 통합됩니다.
+승무원 실행 이벤트(예: 에이전트 작업, 도구 호출, 모델 응답)를 캡처합니다.
+관찰 가능성과 평가를 위해 이를 갈릴레오에 전달합니다.
+
+### 이벤트 리스너 이해
+
+`CrewAIEventListener()` 인스턴스를 생성하는 것이 전부입니다.
+CrewAI 실행을 위해 Galileo를 활성화하는 데 필요합니다. 인스턴스화되면 리스너는 다음을 수행합니다.
+
+-CrewAI에 자동으로 등록됩니다.
+-환경 변수에서 Galileo 구성을 읽습니다.
+-모든 실행 데이터를 Galileo 프로젝트 및 다음에서 지정한 로그 스트림에 기록합니다.
+ `GALILEO_PROJECT` 및 `GALILEO_LOG_STREAM`
+
+추가 구성이나 코드 변경이 필요하지 않습니다.
+이 실행의 모든 데이터는 Galileo 프로젝트에 기록되며
+환경 구성에 따라 지정된 로그 스트림
+(예: GALILEO_PROJECT 및 GALILEO_LOG_STREAM)
diff --git a/docs/v1.15.13/ko/observability/langdb.mdx b/docs/v1.15.13/ko/observability/langdb.mdx
new file mode 100644
index 0000000000..6a5442f494
--- /dev/null
+++ b/docs/v1.15.13/ko/observability/langdb.mdx
@@ -0,0 +1,285 @@
+---
+title: LangDB 통합
+description: LangDB AI Gateway로 CrewAI 워크플로우를 관리, 보안, 최적화하세요—350개 이상의 모델 액세스, 자동 라우팅, 비용 최적화, 완전한 가시성을 제공합니다.
+icon: database
+mode: "wide"
+---
+
+# 소개
+
+[LangDB AI Gateway](https://langdb.ai)는 여러 대형 언어 모델과의 연결을 지원하는 OpenAI 호환 API를 제공하며, 350개 이상의 언어 모델에 접근할 수 있도록 해주는 관측 플랫폼입니다. 단 한 번의 `init()` 호출로 모든 에이전트 상호작용, 작업 실행 및 LLM 호출이 캡처되어, 애플리케이션을 위한 종합적인 관측성과 프로덕션 수준의 AI 인프라를 제공합니다.
+
+
+
+
+
+**확인:** [실시간 추적 예시 보기](https://app.langdb.ai/sharing/threads/3becbfed-a1be-ae84-ea3c-4942867a3e22)
+
+## 기능
+
+### AI 게이트웨이 기능
+- **350개 이상의 LLM 접근**: 단일 통합을 통해 모든 주요 언어 모델에 연결
+- **가상 모델**: 특정 매개변수와 라우팅 규칙으로 맞춤형 모델 구성 생성
+- **가상 MCP**: 에이전트 간 향상된 통신을 위해 MCP(Model Context Protocol) 시스템과의 호환성 및 통합 지원
+- **가드레일**: 에이전트 행동에 대한 안전 조치 및 컴플라이언스 제어 구현
+
+### 가시성 및 추적
+- **자동 추적**: 단일 `init()` 호출로 모든 CrewAI 상호작용을 캡처
+- **엔드-투-엔드 가시성**: 에이전트 워크플로우를 시작부터 끝까지 모니터링
+- **도구 사용 추적**: 에이전트가 사용하는 도구와 그 결과를 추적
+- **모델 호출 모니터링**: LLM 상호작용에 대한 상세한 인사이트 제공
+- **성능 분석**: 지연 시간, 토큰 사용량 및 비용 모니터링
+- **디버깅 지원**: 문제 해결을 위한 단계별 실행
+- **실시간 모니터링**: 라이브 트레이스 및 메트릭 대시보드
+
+## 설치 안내
+
+
+
+
+### 볼 수 있는 내용
+
+- **에이전트 상호작용**: 에이전트 대화 및 작업 인계의 전체 흐름
+- **도구 사용**: 호출된 도구, 입력값 및 출력값
+- **모델 호출**: 프롬프트 및 응답과 함께하는 상세 LLM 상호작용
+- **성능 지표**: 지연 시간, 토큰 사용량, 비용 추적
+- **실행 타임라인**: 전체 워크플로우의 단계별 보기
+
+## 문제 해결
+
+### 일반적인 문제
+
+- **추적이 나타나지 않음**: `init()`이 CrewAI 임포트 이전에 호출되었는지 확인하세요
+- **인증 오류**: LangDB API 키와 프로젝트 ID를 확인하세요
+
+## 리소스
+
+
+
+
+
+ + 필터 및 샘플링을 기준으로 UI에서 캡처된 로그를 자동으로 평가할 수 있습니다. +
++ 로그의 품질을 평가하고, 사람의 평가 또는 등급을 이용해 로그를 검토할 수 있습니다. +
++ 트레이스 또는 로그의 모든 컴포넌트를 평가하여 에이전트의 행동에 대한 통찰을 얻을 수 있습니다. +
+
+
+
+
+## 문제 해결
+
+### 흔한 문제
+
+- **추적(trace)가 나타나지 않음**: API 키와 저장소 ID가 올바른지 확인하세요.
+- crew를 실행하기 **_전에_** 반드시 **`instrument_crewai()`를 호출**했는지 확인하세요. 이 함수가 로깅 훅(logging hook)을 올바르게 초기화합니다.
+- 내부 오류를 드러내기 위해 `instrument_crewai()` 호출 시 `debug=True`로 설정하세요:
+
+ ```python
+ instrument_crewai(logger, debug=True)
+ ```
+- 에이전트에서 상세 로그를 캡처하기 위해 `verbose=True`로 설정하세요:
+
+ ```python
+ agent = CrewAgent(..., verbose=True)
+ ```
+- `instrument_crewai()`가 에이전트를 생성하거나 실행하기 **전에** 호출되는지 다시 한 번 확인하세요. 너무 당연해 보일 수 있지만, 자주 발생하는 실수입니다.
+
+## 리소스
+
+
+
+
+
+
+
+
+### 기능
+
+- **분석 대시보드**: 에이전트의 상태와 성능을 모니터링할 수 있는 대시보드를 통해 지표, 비용, 사용자 상호작용을 자세히 추적할 수 있습니다.
+- **OpenTelemetry-네이티브 가시성 SDK**: Grafana, DataDog 등 기존 가시성 도구로 추적 및 지표를 전송할 수 있는 벤더 중립적 SDK를 제공합니다.
+- **커스텀 및 파인튜닝 모델 비용 추적**: 정확한 예산 책정을 위해 커스텀 가격 파일을 사용하여 특정 모델의 비용 추정치를 맞춤화할 수 있습니다.
+- **예외 모니터링 대시보드**: 모니터링 대시보드를 통해 일반적인 예외 및 오류를 추적하여 문제를 신속하게 찾아내고 해결할 수 있습니다.
+- **컴플라이언스 및 보안**: 욕설 및 PII 유출과 같은 잠재적인 위협을 탐지합니다.
+- **프롬프트 인젝션 탐지**: 잠재적인 코드 인젝션 및 비밀 유출을 식별합니다.
+- **API 키 및 비밀 관리**: LLM API 키와 비밀을 중앙에서 안전하게 관리하여 안전하지 않은 관행을 방지합니다.
+- **프롬프트 관리**: PromptHub을 사용하여 에이전트 프롬프트를 관리 및 버전 관리하고, 모든 에이전트에서 일관되고 쉽게 접근할 수 있습니다.
+- **모델 플레이그라운드**: 배포 전에 CrewAI 에이전트에 사용할 다양한 모델을 테스트하고 비교할 수 있습니다.
+
+## 설치 안내
+
+
+
+
+
+
+
+
+Opik은 CrewAI 애플리케이션 개발의 모든 단계에서 포괄적인 지원을 제공합니다:
+
+- **로그 트레이스 및 스팬**: 개발 및 프로덕션 시스템에서 LLM 호출과 애플리케이션 로직을 자동으로 추적하여 디버깅 및 분석이 가능합니다. 프로젝트 간 응답을 수동 또는 프로그램적으로 주석 달고, 조회하고, 비교할 수 있습니다.
+- **LLM 애플리케이션 성능 평가**: 사용자 지정 테스트 세트로 평가하고, 내장된 평가 지표를 실행하거나 SDK 또는 UI에서 사용자만의 지표를 정의할 수 있습니다.
+- **CI/CD 파이프라인 내 테스트**: PyTest 기반의 Opik LLM 단위 테스트로 신뢰할 수 있는 성능 기준선을 설정하세요. 프로덕션에서 연속 모니터링을 위한 온라인 평가도 실행할 수 있습니다.
+- **프로덕션 데이터 모니터링 및 분석**: 프로덕션에서 보지 못한 데이터에 대한 모델의 성능을 이해하고, 새로운 개발 반복을 위한 데이터 세트를 생성할 수 있습니다.
+
+## 설치
+
+Comet은 호스팅된 Opik 플랫폼을 제공하거나, 로컬에서 플랫폼을 실행할 수도 있습니다.
+
+호스팅 버전을 사용하려면 [무료 Comet 계정 만들기](https://www.comet.com/signup?utm_medium=github&utm_source=crewai_docs) 후 API 키를 발급받으세요.
+
+Opik 플랫폼을 로컬에서 실행하려면, [설치 가이드](https://www.comet.com/docs/opik/self-host/overview/)에서 자세한 정보를 확인하세요.
+
+이 가이드에서는 CrewAI의 빠른 시작 예제를 사용합니다.
+
+
+
+## 소개
+
+Portkey는 CrewAI에 프로덕션 적합성을 위한 기능을 추가하여 실험적인 agent crew를 다음과 같이 견고한 시스템으로 전환합니다.
+
+- **모든 agent 단계, 도구 사용, 상호작용에 대한 완전한 관찰 가능성**
+- **내장된 신뢰성**: 폴백, 재시도, 로드 밸런싱 기능 제공
+- **AI 비용 관리**를 위한 비용 추적 및 최적화
+- **단일 통합을 통한 200개 이상의 LLM 접근**
+- **agent의 행동을 안전하고 규정 준수로 유지하는 가드레일**
+- **일관된 agent 성능을 위한 버전 관리되는 prompt**
+
+### 설치 및 설정
+
+
+
+
+Traces는 crew의 실행을 계층적으로 보여주며, LLM 호출, 도구 호출, 상태 전환의 순서를 확인할 수 있습니다.
+
+```python
+# Portkey에서 계층적 추적을 활성화하려면 trace_id를 추가하세요
+portkey_llm = LLM(
+ model="gpt-4o",
+ base_url=PORTKEY_GATEWAY_URL,
+ api_key="dummy",
+ extra_headers=createHeaders(
+ api_key="YOUR_PORTKEY_API_KEY",
+ virtual_key="YOUR_OPENAI_VIRTUAL_KEY",
+ trace_id="unique-session-id" # 고유한 trace ID 추가
+ )
+)
+```
+
+
+
+Portkey는 LLM과의 모든 상호작용을 로그로 남깁니다. 여기에는 다음이 포함됩니다:
+
+- 전체 요청 및 응답 페이로드
+- 지연 시간 및 토큰 사용량 지표
+- 비용 계산
+- 도구 호출 및 함수 실행
+
+모든 로그는 메타데이터, trace ID, 모델 등으로 필터링할 수 있어 특정 crew 실행을 쉽게 디버깅할 수 있습니다.
+
+
+
+Portkey는 사용자가 다음을 할 수 있도록 지원하는 내장 대시보드를 제공합니다:
+
+- 모든 crew 실행에서 비용 및 토큰 사용량 추적
+- 지연 시간, 성공률과 같은 성능 지표 분석
+- agent workflow의 병목 지점 식별
+- 서로 다른 crew 구성 및 LLM 비교
+
+사용자는 모든 지표를 사용자 정의 메타데이터별로 필터링 및 세분화하여 특정 crew 유형, 사용자 그룹 또는 사용 사례를 분석할 수 있습니다.
+
+
+
+CrewAI LLM 구성에 사용자 정의 메타데이터를 추가하여 강력한 필터링 및 세분화를 활성화할 수 있습니다:
+
+```python
+portkey_llm = LLM(
+ model="gpt-4o",
+ base_url=PORTKEY_GATEWAY_URL,
+ api_key="dummy",
+ extra_headers=createHeaders(
+ api_key="YOUR_PORTKEY_API_KEY",
+ virtual_key="YOUR_OPENAI_VIRTUAL_KEY",
+ metadata={
+ "crew_type": "research_crew",
+ "environment": "production",
+ "_user": "user_123", # 사용자 분석을 위한 특수 _user 필드
+ "request_source": "mobile_app"
+ }
+ )
+)
+```
+
+이 메타데이터는 Portkey 대시보드에서 로그, trace, 지표를 필터링하는 데 사용될 수 있으며, 특정 crew 실행, 사용자 또는 환경을 분석할 수 있습니다.
+
+
+
+이를 통해 다음이 가능합니다:
+- 사용자별 비용 추적 및 예산 관리
+- 개인화된 사용자 분석
+- 팀 또는 조직 단위의 지표
+- 환경별 모니터링(스테이징 vs. 프로덕션)
+
+
+
+
+
+
+
+
+
+
+공식 CrewAI 문서
+이 통합 구현에 대한 맞춤형 안내를 받아보세요
+
+
+
+
+
+ O painel esquerdo agrupa checkpoints por branch; forks aninham sob seu pai. Selecionar um checkpoint abre o painel de detalhes com metadados, estado da entidade e progresso das tarefas. **Resume** continua a execução; **Fork** inicia uma nova branch.
+
+
+
+
+
+ O painel de detalhes expõe duas áreas editáveis:
+
+ - **Inputs** — os inputs originais do kickoff, preenchidos e editáveis.
+
+
+
+
+
+ - **Saídas das tarefas** — saídas das tarefas concluídas. Editar uma saída e pressionar **Fork** invalida tarefas downstream para que sejam reexecutadas com o contexto modificado.
+
+
+
+
+
+
+
+
+
+ stop, basta omiti-lo na chamada do LLM:
+
+ ```python
+ from crewai import LLM
+ import os
+
+ os.environ["OPENAI_API_KEY"] = "
+
+
+Essa matriz ajuda a visualizar como diferentes abordagens se alinham com os requisitos variados de complexidade e precisão. Vamos explorar o significado de cada quadrante e como isso orienta suas escolhas arquiteturais.
+
+## Explicando a Matriz Complexidade-Precisão
+
+### O que é Complexidade?
+
+No contexto das aplicações CrewAI, **complexidade** refere-se a:
+
+- O número de etapas ou operações distintas necessárias
+- A diversidade de tarefas que precisam ser realizadas
+- As interdependências entre diferentes componentes
+- A necessidade de lógica condicional e ramificações
+- A sofisticação do fluxo de trabalho como um todo
+
+### O que é Precisão?
+
+**Precisão** nesse contexto refere-se a:
+
+- O grau de exatidão exigido no resultado final
+- A necessidade de resultados estruturados e previsíveis
+- A importância da reprodutibilidade
+- O nível de controle necessário sobre cada etapa
+- A tolerância à variação nos resultados
+
+### Os Quatro Quadrantes
+
+#### 1. Baixa Complexidade, Baixa Precisão
+
+**Características:**
+- Tarefas simples e diretas
+- Tolerância a alguma variação nos resultados
+- Número limitado de etapas
+- Aplicações criativas ou exploratórias
+
+**Abordagem Recomendada:** Crews simples com poucos agentes
+
+**Exemplos de Casos de Uso:**
+- Geração básica de conteúdo
+- Brainstorming de ideias
+- Tarefas simples de sumarização
+- Assistência à escrita criativa
+
+#### 2. Baixa Complexidade, Alta Precisão
+
+**Características:**
+- Fluxos de trabalho simples que exigem resultados exatos e estruturados
+- Necessidade de resultados reproduzíveis
+- Poucas etapas, mas alto requisito de precisão
+- Frequentemente envolve processamento ou transformação de dados
+
+**Abordagem Recomendada:** Flows com chamadas diretas a LLM ou Crews simples com saídas estruturadas
+
+**Exemplos de Casos de Uso:**
+- Extração e transformação de dados
+- Preenchimento e validação de formulários
+- Geração estruturada de conteúdo (JSON, XML)
+- Tarefas simples de classificação
+
+#### 3. Alta Complexidade, Baixa Precisão
+
+**Características:**
+- Processos multiestágio com muitas etapas
+- Saídas criativas ou exploratórias
+- Interações complexas entre componentes
+- Tolerância à variação nos resultados finais
+
+**Abordagem Recomendada:** Crews complexas com múltiplos agentes especializados
+
+**Exemplos de Casos de Uso:**
+- Pesquisa e análise
+- Pipelines de criação de conteúdo
+- Análise exploratória de dados
+- Solução criativa de problemas
+
+#### 4. Alta Complexidade, Alta Precisão
+
+**Características:**
+- Fluxos de trabalho complexos que requerem saídas estruturadas
+- Múltiplas etapas interdependentes com rígida exigência de precisão
+- Necessidade tanto de processamento sofisticado quanto de resultados precisos
+- Frequentemente aplicações críticas
+
+**Abordagem Recomendada:** Flows orquestrando múltiplas Crews com etapas de validação
+
+**Exemplos de Casos de Uso:**
+- Sistemas corporativos de suporte à decisão
+- Pipelines complexos de processamento de dados
+- Processamento de documentos em múltiplos estágios
+- Aplicações em indústrias reguladas
+
+## Escolhendo Entre Crews e Flows
+
+### Quando Escolher Crews
+
+Crews são ideais quando:
+
+1. **Você precisa de inteligência colaborativa** - Múltiplos agentes com especializações diferentes precisam trabalhar juntos
+2. **O problema requer pensamento emergente** - A solução se beneficia de diferentes perspectivas e abordagens
+3. **A tarefa é principalmente criativa ou analítica** - O trabalho envolve pesquisa, criação de conteúdo ou análise
+4. **Você valoriza adaptabilidade mais do que estrutura rígida** - O fluxo de trabalho pode se beneficiar da autonomia dos agentes
+5. **O formato da saída pode ser um pouco flexível** - Alguma variação na estrutura do resultado é aceitável
+
+```python
+# Example: Research Crew for market analysis
+from crewai import Agent, Crew, Process, Task
+
+# Create specialized agents
+researcher = Agent(
+ role="Market Research Specialist",
+ goal="Find comprehensive market data on emerging technologies",
+ backstory="You are an expert at discovering market trends and gathering data."
+)
+
+analyst = Agent(
+ role="Market Analyst",
+ goal="Analyze market data and identify key opportunities",
+ backstory="You excel at interpreting market data and spotting valuable insights."
+)
+
+# Define their tasks
+research_task = Task(
+ description="Research the current market landscape for AI-powered healthcare solutions",
+ expected_output="Comprehensive market data including key players, market size, and growth trends",
+ agent=researcher
+)
+
+analysis_task = Task(
+ description="Analyze the market data and identify the top 3 investment opportunities",
+ expected_output="Analysis report with 3 recommended investment opportunities and rationale",
+ agent=analyst,
+ context=[research_task]
+)
+
+# Create the crew
+market_analysis_crew = Crew(
+ agents=[researcher, analyst],
+ tasks=[research_task, analysis_task],
+ process=Process.sequential,
+ verbose=True
+)
+
+# Run the crew
+result = market_analysis_crew.kickoff()
+```
+
+### Quando Escolher Flows
+
+Flows são ideais quando:
+
+1. **Você precisa de controle preciso da execução** - O fluxo de trabalho exige sequenciamento exato e gerenciamento de estado
+2. **A aplicação tem requisitos complexos de estado** - Você precisa manter e transformar estado ao longo de múltiplas etapas
+3. **Você precisa de saídas estruturadas e previsíveis** - A aplicação exige resultados consistentes e formatados
+4. **O fluxo de trabalho envolve lógica condicional** - Caminhos diferentes precisam ser seguidos com base em resultados intermediários
+5. **Você precisa combinar IA com código procedural** - A solução demanda tanto capacidades de IA quanto programação tradicional
+
+```python
+# Example: Customer Support Flow with structured processing
+from crewai.flow.flow import Flow, listen, router, start
+from pydantic import BaseModel
+from typing import List, Dict
+
+# Define structured state
+class SupportTicketState(BaseModel):
+ ticket_id: str = ""
+ customer_name: str = ""
+ issue_description: str = ""
+ category: str = ""
+ priority: str = "medium"
+ resolution: str = ""
+ satisfaction_score: int = 0
+
+class CustomerSupportFlow(Flow[SupportTicketState]):
+ @start()
+ def receive_ticket(self):
+ # In a real app, this might come from an API
+ self.state.ticket_id = "TKT-12345"
+ self.state.customer_name = "Alex Johnson"
+ self.state.issue_description = "Unable to access premium features after payment"
+ return "Ticket received"
+
+ @listen(receive_ticket)
+ def categorize_ticket(self, _):
+ # Use a direct LLM call for categorization
+ from crewai import LLM
+ llm = LLM(model="openai/gpt-4o-mini")
+
+ prompt = f"""
+ Categorize the following customer support issue into one of these categories:
+ - Billing
+ - Account Access
+ - Technical Issue
+ - Feature Request
+ - Other
+
+ Issue: {self.state.issue_description}
+
+ Return only the category name.
+ """
+
+ self.state.category = llm.call(prompt).strip()
+ return self.state.category
+
+ @router(categorize_ticket)
+ def route_by_category(self, category):
+ # Route to different handlers based on category
+ return category.lower().replace(" ", "_")
+
+ @listen("billing")
+ def handle_billing_issue(self):
+ # Handle billing-specific logic
+ self.state.priority = "high"
+ # More billing-specific processing...
+ return "Billing issue handled"
+
+ @listen("account_access")
+ def handle_access_issue(self):
+ # Handle access-specific logic
+ self.state.priority = "high"
+ # More access-specific processing...
+ return "Access issue handled"
+
+ # Additional category handlers...
+
+ @listen("billing", "account_access", "technical_issue", "feature_request", "other")
+ def resolve_ticket(self, resolution_info):
+ # Final resolution step
+ self.state.resolution = f"Issue resolved: {resolution_info}"
+ return self.state.resolution
+
+# Run the flow
+support_flow = CustomerSupportFlow()
+result = support_flow.kickoff()
+```
+
+### Quando Combinar Crews e Flows
+
+As aplicações mais sofisticadas frequentemente se beneficiam da combinação de Crews e Flows:
+
+1. **Processos complexos em múltiplos estágios** - Use Flows para orquestrar o processo geral e Crews para sub-tarefas complexas
+2. **Aplicações que exigem criatividade e estrutura** - Use Crews para tarefas criativas e Flows para processamento estruturado
+3. **Aplicações corporativas de IA** - Use Flows para gerenciar estado e fluxo de processo enquanto aproveita Crews para tarefas especializadas
+
+```python
+# Example: Content Production Pipeline combining Crews and Flows
+from crewai.flow.flow import Flow, listen, start
+from crewai import Agent, Crew, Process, Task
+from pydantic import BaseModel
+from typing import List, Dict
+
+class ContentState(BaseModel):
+ topic: str = ""
+ target_audience: str = ""
+ content_type: str = ""
+ outline: Dict = {}
+ draft_content: str = ""
+ final_content: str = ""
+ seo_score: int = 0
+
+class ContentProductionFlow(Flow[ContentState]):
+ @start()
+ def initialize_project(self):
+ # Set initial parameters
+ self.state.topic = "Sustainable Investing"
+ self.state.target_audience = "Millennial Investors"
+ self.state.content_type = "Blog Post"
+ return "Project initialized"
+
+ @listen(initialize_project)
+ def create_outline(self, _):
+ # Use a research crew to create an outline
+ researcher = Agent(
+ role="Content Researcher",
+ goal=f"Research {self.state.topic} for {self.state.target_audience}",
+ backstory="You are an expert researcher with deep knowledge of content creation."
+ )
+
+ outliner = Agent(
+ role="Content Strategist",
+ goal=f"Create an engaging outline for a {self.state.content_type}",
+ backstory="You excel at structuring content for maximum engagement."
+ )
+
+ research_task = Task(
+ description=f"Research {self.state.topic} focusing on what would interest {self.state.target_audience}",
+ expected_output="Comprehensive research notes with key points and statistics",
+ agent=researcher
+ )
+
+ outline_task = Task(
+ description=f"Create an outline for a {self.state.content_type} about {self.state.topic}",
+ expected_output="Detailed content outline with sections and key points",
+ agent=outliner,
+ context=[research_task]
+ )
+
+ outline_crew = Crew(
+ agents=[researcher, outliner],
+ tasks=[research_task, outline_task],
+ process=Process.sequential,
+ verbose=True
+ )
+
+ # Run the crew and store the result
+ result = outline_crew.kickoff()
+
+ # Parse the outline (in a real app, you might use a more robust parsing approach)
+ import json
+ try:
+ self.state.outline = json.loads(result.raw)
+ except:
+ # Fallback if not valid JSON
+ self.state.outline = {"sections": result.raw}
+
+ return "Outline created"
+
+ @listen(create_outline)
+ def write_content(self, _):
+ # Use a writing crew to create the content
+ writer = Agent(
+ role="Content Writer",
+ goal=f"Write engaging content for {self.state.target_audience}",
+ backstory="You are a skilled writer who creates compelling content."
+ )
+
+ editor = Agent(
+ role="Content Editor",
+ goal="Ensure content is polished, accurate, and engaging",
+ backstory="You have a keen eye for detail and a talent for improving content."
+ )
+
+ writing_task = Task(
+ description=f"Write a {self.state.content_type} about {self.state.topic} following this outline: {self.state.outline}",
+ expected_output="Complete draft content in markdown format",
+ agent=writer
+ )
+
+ editing_task = Task(
+ description="Edit and improve the draft content for clarity, engagement, and accuracy",
+ expected_output="Polished final content in markdown format",
+ agent=editor,
+ context=[writing_task]
+ )
+
+ writing_crew = Crew(
+ agents=[writer, editor],
+ tasks=[writing_task, editing_task],
+ process=Process.sequential,
+ verbose=True
+ )
+
+ # Run the crew and store the result
+ result = writing_crew.kickoff()
+ self.state.final_content = result.raw
+
+ return "Content created"
+
+ @listen(write_content)
+ def optimize_for_seo(self, _):
+ # Use a direct LLM call for SEO optimization
+ from crewai import LLM
+ llm = LLM(model="openai/gpt-4o-mini")
+
+ prompt = f"""
+ Analyze this content for SEO effectiveness for the keyword "{self.state.topic}".
+ Rate it on a scale of 1-100 and provide 3 specific recommendations for improvement.
+
+ Content: {self.state.final_content[:1000]}... (truncated for brevity)
+
+ Format your response as JSON with the following structure:
+ {{
+ "score": 85,
+ "recommendations": [
+ "Recommendation 1",
+ "Recommendation 2",
+ "Recommendation 3"
+ ]
+ }}
+ """
+
+ seo_analysis = llm.call(prompt)
+
+ # Parse the SEO analysis
+ import json
+ try:
+ analysis = json.loads(seo_analysis)
+ self.state.seo_score = analysis.get("score", 0)
+ return analysis
+ except:
+ self.state.seo_score = 50
+ return {"score": 50, "recommendations": ["Unable to parse SEO analysis"]}
+
+# Run the flow
+content_flow = ContentProductionFlow()
+result = content_flow.kickoff()
+```
+
+## Framework Prático de Avaliação
+
+Para determinar a abordagem certa para seu caso de uso específico, siga este framework passo a passo:
+
+### Passo 1: Avalie a Complexidade
+
+Classifique a complexidade do seu aplicativo numa escala de 1-10 considerando:
+
+1. **Número de etapas**: Quantas operações distintas são necessárias?
+ - 1-3 etapas: Baixa complexidade (1-3)
+ - 4-7 etapas: Média complexidade (4-7)
+ - 8+ etapas: Alta complexidade (8-10)
+
+2. **Interdependências**: Quão interligadas estão as partes diferentes?
+ - Poucas dependências: Baixa complexidade (1-3)
+ - Algumas dependências: Média complexidade (4-7)
+ - Muitas dependências complexas: Alta complexidade (8-10)
+
+3. **Lógica condicional**: Quanto de ramificação e tomada de decisão é necessário?
+ - Processo linear: Baixa complexidade (1-3)
+ - Alguma ramificação: Média complexidade (4-7)
+ - Árvores de decisão complexas: Alta complexidade (8-10)
+
+4. **Conhecimento de domínio**: Quão especializado deve ser o conhecimento requerido?
+ - Conhecimento geral: Baixa complexidade (1-3)
+ - Algum conhecimento especializado: Média complexidade (4-7)
+ - Grande especialização em múltiplos domínios: Alta complexidade (8-10)
+
+Calcule a média das pontuações para determinar sua complexidade geral.
+
+### Passo 2: Avalie os Requisitos de Precisão
+
+Classifique seus requisitos de precisão numa escala de 1-10 considerando:
+
+1. **Estrutura da saída**: Quão estruturado o resultado deve ser?
+ - Texto livre: Baixa precisão (1-3)
+ - Semi-estruturado: Média precisão (4-7)
+ - Estritamente formatado (JSON, XML): Alta precisão (8-10)
+
+2. **Necessidade de exatidão**: Qual a importância da precisão factual?
+ - Conteúdo criativo: Baixa precisão (1-3)
+ - Conteúdo informacional: Média precisão (4-7)
+ - Informação crítica: Alta precisão (8-10)
+
+3. **Reprodutibilidade**: Quão consistentes devem ser os resultados entre execuções?
+ - Variação aceitável: Baixa precisão (1-3)
+ - Alguma consistência necessária: Média precisão (4-7)
+ - Exata reprodutibilidade: Alta precisão (8-10)
+
+4. **Tolerância a erros**: Qual o impacto de erros?
+ - Baixo impacto: Baixa precisão (1-3)
+ - Impacto moderado: Média precisão (4-7)
+ - Alto impacto: Alta precisão (8-10)
+
+Calcule a média das pontuações para determinar seu requisito geral de precisão.
+
+### Passo 3: Mapeie na Matriz
+
+Plote as pontuações de complexidade e precisão na matriz:
+
+- **Baixa Complexidade (1-4), Baixa Precisão (1-4)**: Crews simples
+- **Baixa Complexidade (1-4), Alta Precisão (5-10)**: Flows com chamadas diretas a LLM
+- **Alta Complexidade (5-10), Baixa Precisão (1-4)**: Crews complexas
+- **Alta Complexidade (5-10), Alta Precisão (5-10)**: Flows orquestrando Crews
+
+### Passo 4: Considere Fatores Adicionais
+
+Além de complexidade e precisão, considere:
+
+1. **Tempo de desenvolvimento**: Crews costumam ser mais rápidas para prototipar
+2. **Necessidades de manutenção**: Flows proporcionam melhor manutenção a longo prazo
+3. **Expertise do time**: Considere a familiaridade de sua equipe com as abordagens
+4. **Requisitos de escalabilidade**: Flows normalmente escalam melhor para aplicações complexas
+5. **Necessidades de integração**: Considere como a solução se integrará aos sistemas existentes
+
+## Conclusão
+
+Escolher entre Crews e Flows — ou combiná-los — é uma decisão arquitetônica crítica que impacta a efetividade, manutenibilidade e escalabilidade da sua aplicação CrewAI. Ao avaliar seu caso de uso nas dimensões de complexidade e precisão, você toma decisões inteligentes que alinham-se aos seus requisitos.
+
+Lembre-se de que a melhor abordagem geralmente evolui na medida em que sua aplicação amadurece. Comece com a solução mais simples que atenda às suas necessidades e esteja preparado para refinar sua arquitetura conforme for ganhando experiência e seus requisitos se tornarem mais claros.
+
+
+
+
+## Passo 2: Entendendo a Estrutura do Projeto
+
+O projeto gerado possui a seguinte estrutura. A crew inicial embutida usa o layout clássico Python/YAML. Para usar uma crew JSON-first dentro de um Flow, crie `crew.jsonc` e `agents/*.jsonc` na pasta da crew e carregue com `crewai.project.load_crew`, como mostrado em [Flows](/pt-BR/concepts/flows#building-your-crews).
+
+```
+guide_creator_flow/
+├── .gitignore
+├── pyproject.toml
+├── README.md
+├── .env
+└── src/
+ └── guide_creator_flow/
+ ├── __init__.py
+ ├── main.py
+ ├── crews/
+ │ └── poem_crew/
+ │ ├── config/
+ │ │ ├── agents.yaml
+ │ │ └── tasks.yaml
+ │ └── poem_crew.py
+ └── tools/
+ └── custom_tool.py
+```
+
+Esta estrutura oferece uma separação clara entre os diferentes componentes do seu flow:
+- A lógica principal do flow no arquivo `src/guide_creator_flow/main.py`
+- Crews especializados no diretório `src/guide_creator_flow/crews`
+- Ferramentas customizadas no diretório `src/guide_creator_flow/tools`
+
+Vamos modificar esta estrutura para criar nosso flow de criação de guias, que irá orquestrar o processo de geração de guias de aprendizagem abrangentes.
+
+## Passo 3: Adicione um Crew de Redator de Conteúdo
+
+Nosso flow precisará de um crew especializado para lidar com o processo de criação de conteúdo. Vamos usar a CLI do CrewAI para adicionar um crew de redatores de conteúdo:
+
+```bash
+crewai flow add-crew content-crew
+```
+
+Este comando cria automaticamente os diretórios e arquivos de template necessários para seu crew. O crew de redatores será responsável por escrever e revisar seções do nosso guia, trabalhando dentro do flow orquestrado pela aplicação principal.
+
+## Passo 4: Configure o Crew de Redator de Conteúdo
+
+Agora, vamos configurar o crew de redatores com JSONC. Vamos definir dois agentes especializados - um escritor e um revisor - que colaboram para criar conteúdo de alta qualidade para o guia.
+
+1. Crie `src/guide_creator_flow/crews/content_crew/agents/content_writer.jsonc`:
+
+```jsonc
+{
+ "role": "Educational Content Writer",
+ "goal": "Create engaging, informative content that thoroughly explains the assigned topic and provides valuable insights to the reader.",
+ "backstory": "You are a talented educational writer who explains complex concepts in accessible language and organizes information clearly.",
+ "llm": "provider/model-id",
+ "settings": {
+ "verbose": true
+ }
+}
+```
+
+2. Crie `src/guide_creator_flow/crews/content_crew/agents/content_reviewer.jsonc`:
+
+```jsonc
+{
+ "role": "Educational Content Reviewer and Editor",
+ "goal": "Ensure content is accurate, comprehensive, well-structured, and consistent with previously written sections.",
+ "backstory": "You are a meticulous editor with an eye for detail, clarity, and coherence.",
+ "llm": "provider/model-id",
+ "settings": {
+ "verbose": true
+ }
+}
+```
+
+Substitua `provider/model-id` pelo modelo que você usa, como `openai/gpt-4o`, `gemini/gemini-2.0-flash-001` ou `anthropic/claude-sonnet-4-6`.
+
+3. Crie `src/guide_creator_flow/crews/content_crew/crew.jsonc`:
+
+```jsonc
+{
+ "name": "Content Crew",
+ "agents": ["content_writer", "content_reviewer"],
+ "tasks": [
+ {
+ "name": "write_section_task",
+ "description": "Write a comprehensive section on the topic: \"{section_title}\".\n\nSection description: {section_description}\nTarget audience: {audience_level} level learners\n\nYour content should begin with a brief introduction, explain key concepts clearly with examples, include practical applications where appropriate, end with a summary, and be approximately 500-800 words.\n\nPreviously written sections:\n{previous_sections}",
+ "expected_output": "A well-structured, comprehensive section in Markdown format that thoroughly explains the topic and is appropriate for the target audience.",
+ "agent": "content_writer",
+ "markdown": true
+ },
+ {
+ "name": "review_section_task",
+ "description": "Review and improve this section on \"{section_title}\":\n\n{draft_content}\n\nTarget audience: {audience_level} level learners\nPreviously written sections:\n{previous_sections}\n\nFix errors, improve clarity, verify consistency, enhance structure, and add missing key information.",
+ "expected_output": "An improved, polished version of the section that maintains the original structure but enhances clarity, accuracy, and consistency.",
+ "agent": "content_reviewer",
+ "context": ["write_section_task"],
+ "markdown": true
+ }
+ ],
+ "process": "sequential",
+ "verbose": true
+}
+```
+
+O campo `context` permite que o revisor use a saída do escritor.
+
+4. Substitua `src/guide_creator_flow/crews/content_crew/content_crew.py` por um pequeno loader:
+
+```python
+from pathlib import Path
+
+from crewai.project import load_crew
+
+
+def kickoff_content_crew(inputs: dict):
+ crew, default_inputs = load_crew(Path(__file__).with_name("crew.jsonc"))
+ return crew.kickoff(inputs={**default_inputs, **inputs})
+```
+
+Esse loader transforma `crew.jsonc` em uma `Crew` em runtime. Embora essa crew possa funcionar de forma independente, no nosso flow ela será orquestrada como parte de um sistema maior.
+
+## Passo 5: Crie o Flow
+
+Agora vem a parte emocionante – criar o flow que irá orquestrar todo o processo de criação do guia. Aqui iremos combinar código Python regular, chamadas diretas a LLM e nosso crew de criação de conteúdo em um sistema coeso.
+
+Nosso flow irá:
+1. Obter a entrada do usuário sobre o tema e nível do público
+2. Fazer uma chamada direta à LLM para criar um roteiro estruturado do guia
+3. Processar cada seção sequencialmente usando o crew de redatores
+4. Combinar tudo em um documento final abrangente
+
+Vamos criar nosso flow no arquivo `main.py`:
+
+```python
+#!/usr/bin/env python
+import json
+import os
+from typing import List, Dict
+from pydantic import BaseModel, Field
+from crewai import LLM
+from crewai.flow.flow import Flow, listen, start
+from guide_creator_flow.crews.content_crew.content_crew import kickoff_content_crew
+
+# Definir nossos modelos para dados estruturados
+class Section(BaseModel):
+ title: str = Field(description="Title of the section")
+ description: str = Field(description="Brief description of what the section should cover")
+
+class GuideOutline(BaseModel):
+ title: str = Field(description="Title of the guide")
+ introduction: str = Field(description="Introduction to the topic")
+ target_audience: str = Field(description="Description of the target audience")
+ sections: List[Section] = Field(description="List of sections in the guide")
+ conclusion: str = Field(description="Conclusion or summary of the guide")
+
+# Definir o estado do nosso flow
+class GuideCreatorState(BaseModel):
+ topic: str = ""
+ audience_level: str = ""
+ guide_outline: GuideOutline = None
+ sections_content: Dict[str, str] = {}
+
+class GuideCreatorFlow(Flow[GuideCreatorState]):
+ """Flow para criar um guia abrangente sobre qualquer tópico"""
+
+ @start()
+ def get_user_input(self):
+ """Obter entrada do usuário sobre o tópico e público do guia"""
+ print("\n=== Create Your Comprehensive Guide ===\n")
+
+ # Obter entrada do usuário
+ self.state.topic = input("What topic would you like to create a guide for? ")
+
+ # Obter nível do público com validação
+ while True:
+ audience = input("Who is your target audience? (beginner/intermediate/advanced) ").lower()
+ if audience in ["beginner", "intermediate", "advanced"]:
+ self.state.audience_level = audience
+ break
+ print("Please enter 'beginner', 'intermediate', or 'advanced'")
+
+ print(f"\nCreating a guide on {self.state.topic} for {self.state.audience_level} audience...\n")
+ return self.state
+
+ @listen(get_user_input)
+ def create_guide_outline(self, state):
+ """Criar um esboço estruturado para o guia usando uma chamada direta ao LLM"""
+ print("Creating guide outline...")
+
+ # Inicializar o LLM
+ llm = LLM(model="openai/gpt-4o-mini", response_format=GuideOutline)
+
+ # Criar as mensagens para o esboço
+ messages = [
+ {"role": "system", "content": "You are a helpful assistant designed to output JSON."},
+ {"role": "user", "content": f"""
+ Create a detailed outline for a comprehensive guide on "{state.topic}" for {state.audience_level} level learners.
+
+ The outline should include:
+ 1. A compelling title for the guide
+ 2. An introduction to the topic
+ 3. 4-6 main sections that cover the most important aspects of the topic
+ 4. A conclusion or summary
+
+ For each section, provide a clear title and a brief description of what it should cover.
+ """}
+ ]
+
+ # Fazer a chamada ao LLM com formato de resposta JSON
+ response = llm.call(messages=messages)
+
+ # Analisar a resposta JSON
+ outline_dict = json.loads(response)
+ self.state.guide_outline = GuideOutline(**outline_dict)
+
+ # Garantir que o diretório de saída exista antes de salvar
+ os.makedirs("output", exist_ok=True)
+
+ # Salvar o esboço em um arquivo
+ with open("output/guide_outline.json", "w") as f:
+ json.dump(outline_dict, f, indent=2)
+
+ print(f"Guide outline created with {len(self.state.guide_outline.sections)} sections")
+ return self.state.guide_outline
+
+ @listen(create_guide_outline)
+ def write_and_compile_guide(self, outline):
+ """Escrever todas as seções e compilar o guia"""
+ print("Writing guide sections and compiling...")
+ completed_sections = []
+
+ # Processar seções uma por uma para manter o fluxo de contexto
+ for section in outline.sections:
+ print(f"Processing section: {section.title}")
+
+ # Construir contexto a partir das seções anteriores
+ previous_sections_text = ""
+ if completed_sections:
+ previous_sections_text = "# Previously Written Sections\n\n"
+ for title in completed_sections:
+ previous_sections_text += f"## {title}\n\n"
+ previous_sections_text += self.state.sections_content.get(title, "") + "\n\n"
+ else:
+ previous_sections_text = "No previous sections written yet."
+
+ # Executar a crew de conteúdo para esta seção
+ result = kickoff_content_crew(inputs={
+ "section_title": section.title,
+ "section_description": section.description,
+ "audience_level": self.state.audience_level,
+ "previous_sections": previous_sections_text,
+ "draft_content": ""
+ })
+
+ # Armazenar o conteúdo
+ self.state.sections_content[section.title] = result.raw
+ completed_sections.append(section.title)
+ print(f"Section completed: {section.title}")
+
+ # Compilar o guia final
+ guide_content = f"# {outline.title}\n\n"
+ guide_content += f"## Introduction\n\n{outline.introduction}\n\n"
+
+ # Adicionar cada seção em ordem
+ for section in outline.sections:
+ section_content = self.state.sections_content.get(section.title, "")
+ guide_content += f"\n\n{section_content}\n\n"
+
+ # Adicionar conclusão
+ guide_content += f"## Conclusion\n\n{outline.conclusion}\n\n"
+
+ # Salvar o guia
+ with open("output/complete_guide.md", "w") as f:
+ f.write(guide_content)
+
+ print("\nComplete guide compiled and saved to output/complete_guide.md")
+ return "Guide creation completed successfully"
+
+def kickoff():
+ """Executar o flow criador de guias"""
+ GuideCreatorFlow().kickoff()
+ print("\n=== Flow Complete ===")
+ print("Your comprehensive guide is ready in the output directory.")
+ print("Open output/complete_guide.md to view it.")
+
+def plot():
+ """Gerar uma visualização do flow"""
+ flow = GuideCreatorFlow()
+ flow.plot("guide_creator_flow")
+ print("Flow visualization saved to guide_creator_flow.html")
+
+if __name__ == "__main__":
+ kickoff()
+```
+
+Vamos analisar o que está acontecendo neste flow:
+
+1. Definimos modelos Pydantic para dados estruturados, garantindo segurança de tipos e representação clara dos dados.
+2. Criamos uma classe de estado para manter dados entre os diferentes passos do flow.
+3. Implementamos três etapas principais para o flow:
+ - Obtenção da entrada do usuário com o decorator `@start()`
+ - Criação do roteiro do guia com uma chamada direta à LLM
+ - Processamento das seções com nosso crew de conteúdo
+4. Usamos o decorator `@listen()` para estabelecer relações orientadas a eventos entre as etapas
+
+Este é o poder dos flows – combinar diferentes tipos de processamento (interação com usuário, chamadas diretas a IA, tarefas colaborativas com crews) em um sistema orientado a eventos e coeso.
+
+## Passo 6: Configure suas Variáveis de Ambiente
+
+Crie um arquivo `.env` na raiz do projeto com suas chaves de API. Veja o [guia de configuração do LLM](/pt-BR/concepts/llms#setting-up-your-llm) para detalhes sobre como configurar o provedor.
+
+```sh .env
+OPENAI_API_KEY=sua_chave_openai
+# ou
+GEMINI_API_KEY=sua_chave_gemini
+# ou
+ANTHROPIC_API_KEY=sua_chave_anthropic
+```
+
+## Passo 7: Instale as Dependências
+
+Instale as dependências necessárias:
+
+```bash
+crewai install
+```
+
+## Passo 8: Execute Seu Flow
+
+Agora é hora de ver seu flow em ação! Execute-o usando a CLI do CrewAI:
+
+```bash
+crewai run
+```
+
+Quando você rodar esse comando, verá seu flow ganhando vida:
+1. Ele solicitará um tema e o nível do público para você
+2. Criará um roteiro estruturado para o seu guia
+3. Processará cada seção, com o redator e o revisor colaborando em cada uma
+4. Por fim, irá compilar tudo em um guia abrangente
+
+Isso demonstra o poder dos flows para orquestrar processos complexos envolvendo múltiplos componentes, tanto de IA quanto não-IA.
+
+## Passo 9: Visualize Seu Flow
+
+Uma das funcionalidades mais poderosas dos flows é a possibilidade de visualizar sua estrutura:
+
+```bash
+crewai flow plot
+```
+
+Isso irá criar um arquivo HTML que mostra a estrutura do seu flow, incluindo os relacionamentos entre etapas e o fluxo de dados. Essa visualização pode ser inestimável para entender e depurar flows complexos.
+
+## Passo 10: Revise o Resultado
+
+Depois que o flow finalizar, você encontrará dois arquivos no diretório `output`:
+
+1. `guide_outline.json`: Contém o roteiro estruturado do guia
+2. `complete_guide.md`: O guia abrangente com todas as seções
+
+Reserve um momento para revisar esses arquivos e apreciar o que você construiu – um sistema que combina entrada do usuário, interações diretas com IA e trabalho colaborativo de agents para produzir um output complexo e de alta qualidade.
+
+## A Arte do Possível: Além do Seu Primeiro Flow
+
+O que você aprendeu neste guia é uma base para criar sistemas de IA muito mais sofisticados. Veja algumas formas de expandir este flow básico:
+
+### Aprimorando a Interação com o Usuário
+
+Você pode criar flows mais interativos com:
+- Interfaces web para entrada e saída de dados
+- Atualizações em tempo real de progresso
+- Loops de feedback e refinamento interativos
+- Interações multi-stage com o usuário
+
+### Adicionando Mais Etapas de Processamento
+
+Você pode expandir seu flow com etapas adicionais para:
+- Pesquisa antes da criação do roteiro
+- Geração de imagens para ilustrações
+- Geração de snippets de código para guias técnicos
+- Garantia de qualidade e checagem final de fatos
+
+### Criando Flows Mais Complexos
+
+Você pode implementar padrões de flow mais sofisticados:
+- Ramificações condicionais com base na preferência do usuário ou tipo de conteúdo
+- Processamento paralelo de seções independentes
+- Loops de refinamento iterativo com feedback
+- Integração a APIs e serviços externos
+
+### Aplicando a Diferentes Domínios
+
+Os mesmos padrões podem ser usados para criar flows de:
+- **Narrativas interativas**: criação de histórias personalizadas com base na entrada do usuário
+- **Inteligência de negócios**: processamento de dados, geração de insights e criação de relatórios
+- **Desenvolvimento de produtos**: facilitação de ideação, design e planejamento
+- **Sistemas educacionais**: criação de experiências de aprendizagem personalizadas
+
+## Principais Funcionalidades Demonstradas
+
+Este flow de criação de guia demonstra diversos recursos poderosos do CrewAI:
+
+1. **Interação com o usuário**: O flow coleta input diretamente do usuário
+2. **Chamadas diretas à LLM**: Usa a classe LLM para interações eficientes e direcionadas com IA
+3. **Dados estruturados com Pydantic**: Usa Pydantic para garantir segurança de tipos
+4. **Processamento sequencial com contexto**: Escreve seções em ordem, fornecendo as anteriores como contexto
+5. **Crews multiagentes**: Utiliza agents especializados (redator e revisor) para criação de conteúdo
+6. **Gerenciamento de estado**: Mantém estado entre diferentes etapas do processo
+7. **Arquitetura orientada a eventos**: Usa o decorator `@listen` para responder a eventos
+
+## Entendendo a Estrutura do Flow
+
+Vamos decompor os principais componentes dos flows para ajudá-lo a entender como construir o seu:
+
+### 1. Chamadas Diretas à LLM
+
+Flows permitem que você faça chamadas diretas a modelos de linguagem quando precisa de respostas simples e estruturadas:
+
+```python
+llm = LLM(
+ model="model-id-here", # gpt-4o, gemini-2.0-flash, anthropic/claude...
+ response_format=GuideOutline
+)
+response = llm.call(messages=messages)
+```
+
+Isso é mais eficiente do que usar um crew quando você precisa de um output específico e estruturado.
+
+### 2. Arquitetura Orientada a Eventos
+
+Flows usam decorators para estabelecer relações entre componentes:
+
+```python
+@start()
+def get_user_input(self):
+ # Primeira etapa no flow
+ # ...
+
+@listen(get_user_input)
+def create_guide_outline(self, state):
+ # Esta roda quando get_user_input é concluída
+ # ...
+```
+
+Isso cria uma estrutura clara e declarativa para sua aplicação.
+
+### 3. Gerenciamento de Estado
+
+Flows mantêm o estado entre as etapas, facilitando o compartilhamento de dados:
+
+```python
+class GuideCreatorState(BaseModel):
+ topic: str = ""
+ audience_level: str = ""
+ guide_outline: GuideOutline = None
+ sections_content: Dict[str, str] = {}
+```
+
+Isso fornece uma maneira segura e tipada de rastrear e transformar dados ao longo do flow.
+
+### 4. Integração com Crews
+
+Flows podem integrar crews para tarefas colaborativas complexas:
+
+```python
+result = kickoff_content_crew(inputs={
+ "section_title": section.title,
+ # ...
+})
+```
+
+Assim, você usa a ferramenta certa para cada parte da aplicação – chamadas diretas para tarefas simples e crews para colaboração avançada.
+
+## Próximos Passos
+
+Agora que você construiu seu primeiro flow, pode:
+
+1. Experimentar estruturas e padrões mais complexos de flow
+2. Testar o uso do `@router()` para criar ramificações condicionais em seus flows
+3. Explorar as funções `and_` e `or_` para execuções paralelas e mais complexas
+4. Conectar seu flow a APIs externas, bancos de dados ou interfaces de usuário
+5. Combinar múltiplos crews especializados em um único flow
+6. Criar apps de chat multi-turn com [Flows conversacionais](/pt-BR/guides/flows/conversational-flows) (`kickoff` por mensagem, `ChatSession`, tracing adiado)
+
+
+ + Crie agentes, orquestre crews e automatize flows com guardrails, memória, conhecimento e observabilidade integrados. +
+
+
+
+Flows fornecem:
+- **Gerenciamento de Estado**: Persistem dados através de etapas e execuções.
+- **Execução Orientada a Eventos**: Acionam ações com base em eventos ou entradas externas.
+- **Controle de Fluxo**: Usam lógica condicional, loops e ramificações.
+
+### 2. Crews: A Inteligência
+
+
+
+
+Crews fornecem:
+- **Agentes com Funções**: Agentes especializados com objetivos e ferramentas específicas.
+- **Colaboração Autônoma**: Agentes trabalham juntos para resolver tarefas.
+- **Delegação de Tarefas**: Tarefas são atribuídas e executadas com base nas capacidades dos agentes.
+
+## Como Tudo Funciona Junto
+
+1. **O Flow** aciona um evento ou inicia um processo.
+2. **O Flow** gerencia o estado e decide o que fazer a seguir.
+3. **O Flow** delega uma tarefa complexa para um **Crew**.
+4. Os agentes do **Crew** colaboram para completar a tarefa.
+5. **O Crew** retorna o resultado para o **Flow**.
+6. **O Flow** continua a execução com base no resultado.
+
+## Principais Funcionalidades
+
+
+
+
+## Boas Práticas
+
+1. **Seja específico nos prompts de geração de imagem** para obter melhores resultados.
+2. **Considere o tempo de geração** - A geração de imagens pode levar algum tempo, então inclua isso no seu planejamento de tarefas.
+3. **Siga as políticas de uso** - Sempre cumpra as políticas de uso da OpenAI ao gerar imagens.
+
+## Solução de Problemas
+
+1. **Verifique o acesso à API** - Certifique-se de que sua chave de API OpenAI possui acesso ao DALL-E.
+2. **Compatibilidade de versões** - Verifique se você está utilizando a versão mais recente do crewAI e crewai-tools.
+3. **Configuração da ferramenta** - Confirme que a ferramenta DALL-E foi corretamente adicionada à lista de ferramentas do agente.
\ No newline at end of file
diff --git a/docs/v1.15.13/pt-BR/learn/execution-hooks.mdx b/docs/v1.15.13/pt-BR/learn/execution-hooks.mdx
new file mode 100644
index 0000000000..0e70edfbd7
--- /dev/null
+++ b/docs/v1.15.13/pt-BR/learn/execution-hooks.mdx
@@ -0,0 +1,379 @@
+---
+title: Visão Geral dos Hooks de Execução
+description: Entendendo e usando hooks de execução no CrewAI para controle fino sobre operações de agentes
+mode: "wide"
+---
+
+Os Hooks de Execução fornecem controle fino sobre o comportamento em tempo de execução dos seus agentes CrewAI. Diferentemente dos hooks de kickoff que são executados antes e depois da execução da crew, os hooks de execução interceptam operações específicas durante a execução do agente, permitindo que você modifique comportamentos, implemente verificações de segurança e adicione monitoramento abrangente.
+
+## Tipos de Hooks de Execução
+
+O CrewAI fornece duas categorias principais de hooks de execução:
+
+### 1. [Hooks de Chamada LLM](/learn/llm-hooks)
+
+Controle e monitore interações com o modelo de linguagem:
+- **Antes da Chamada LLM**: Modifique prompts, valide entradas, implemente gates de aprovação
+- **Depois da Chamada LLM**: Transforme respostas, sanitize saídas, atualize histórico de conversação
+
+**Casos de Uso:**
+- Limitação de iterações
+- Rastreamento de custos e monitoramento de uso de tokens
+- Sanitização de respostas e filtragem de conteúdo
+- Aprovação humana para chamadas LLM
+- Adição de diretrizes de segurança ou contexto
+- Logging de debug e inspeção de requisição/resposta
+
+[Ver Documentação de Hooks LLM →](/learn/llm-hooks)
+
+### 2. [Hooks de Chamada de Ferramenta](/learn/tool-hooks)
+
+Controle e monitore execução de ferramentas:
+- **Antes da Chamada de Ferramenta**: Modifique entradas, valide parâmetros, bloqueie operações perigosas
+- **Depois da Chamada de Ferramenta**: Transforme resultados, sanitize saídas, registre detalhes de execução
+
+**Casos de Uso:**
+- Guardrails de segurança para operações destrutivas
+- Aprovação humana para ações sensíveis
+- Validação e sanitização de entrada
+- Cache de resultados e limitação de taxa
+- Análise de uso de ferramentas
+- Logging de debug e monitoramento
+
+[Ver Documentação de Hooks de Ferramenta →](/learn/tool-hooks)
+
+## Métodos de Registro
+
+### 1. Hooks Baseados em Decoradores (Recomendado)
+
+A maneira mais limpa e pythônica de registrar hooks:
+
+```python
+from crewai.hooks import before_llm_call, after_llm_call, before_tool_call, after_tool_call
+
+@before_llm_call
+def limit_iterations(context):
+ """Previne loops infinitos limitando iterações."""
+ if context.iterations > 10:
+ return False # Bloquear execução
+ return None
+
+@after_llm_call
+def sanitize_response(context):
+ """Remove dados sensíveis das respostas do LLM."""
+ if "API_KEY" in context.response:
+ return context.response.replace("API_KEY", "[CENSURADO]")
+ return None
+
+@before_tool_call
+def block_dangerous_tools(context):
+ """Bloqueia operações destrutivas."""
+ if context.tool_name == "delete_database":
+ return False # Bloquear execução
+ return None
+
+@after_tool_call
+def log_tool_result(context):
+ """Registra execução de ferramenta."""
+ print(f"Ferramenta {context.tool_name} concluída")
+ return None
+```
+
+### 2. Hooks com Escopo de Crew
+
+Aplica hooks apenas a instâncias específicas de 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):
+ # Aplica-se apenas a esta crew
+ print(f"Chamada LLM em {self.__class__.__name__}")
+ return None
+
+ @after_tool_call_crew
+ def log_results(self, context):
+ # Logging específico da crew
+ print(f"Resultado da ferramenta: {context.tool_result[:50]}...")
+ return None
+
+ @crew
+ def crew(self) -> Crew:
+ return Crew(
+ agents=self.agents,
+ tasks=self.tasks,
+ process=Process.sequential
+ )
+```
+
+## Fluxo de Execução de Hooks
+
+### Fluxo de Chamada LLM
+
+```
+Agente precisa chamar LLM
+ ↓
+[Hooks Antes da Chamada LLM Executam]
+ ├→ Hook 1: Validar contagem de iterações
+ ├→ Hook 2: Adicionar contexto de segurança
+ └→ Hook 3: Registrar requisição
+ ↓
+Se algum hook retornar False:
+ ├→ Bloquear chamada LLM
+ └→ Lançar ValueError
+ ↓
+Se todos os hooks retornarem True/None:
+ ├→ Chamada LLM prossegue
+ └→ Resposta gerada
+ ↓
+[Hooks Depois da Chamada LLM Executam]
+ ├→ Hook 1: Sanitizar resposta
+ ├→ Hook 2: Registrar resposta
+ └→ Hook 3: Atualizar métricas
+ ↓
+Resposta final retornada
+```
+
+### Fluxo de Chamada de Ferramenta
+
+```
+Agente precisa executar ferramenta
+ ↓
+[Hooks Antes da Chamada de Ferramenta Executam]
+ ├→ Hook 1: Verificar se ferramenta é permitida
+ ├→ Hook 2: Validar entradas
+ └→ Hook 3: Solicitar aprovação se necessário
+ ↓
+Se algum hook retornar False:
+ ├→ Bloquear execução da ferramenta
+ └→ Retornar mensagem de erro
+ ↓
+Se todos os hooks retornarem True/None:
+ ├→ Execução da ferramenta prossegue
+ └→ Resultado gerado
+ ↓
+[Hooks Depois da Chamada de Ferramenta Executam]
+ ├→ Hook 1: Sanitizar resultado
+ ├→ Hook 2: Fazer cache do resultado
+ └→ Hook 3: Registrar métricas
+ ↓
+Resultado final retornado
+```
+
+## Objetos de Contexto de Hook
+
+### LLMCallHookContext
+
+Fornece acesso ao estado de execução do LLM:
+
+```python
+class LLMCallHookContext:
+ executor: CrewAgentExecutor # Acesso completo ao executor
+ messages: list # Lista de mensagens mutável
+ agent: Agent # Agente atual
+ task: Task # Tarefa atual
+ crew: Crew # Instância da crew
+ llm: BaseLLM # Instância do LLM
+ iterations: int # Iteração atual
+ response: str | None # Resposta do LLM (hooks posteriores)
+```
+
+### ToolCallHookContext
+
+Fornece acesso ao estado de execução da ferramenta:
+
+```python
+class ToolCallHookContext:
+ tool_name: str # Ferramenta sendo chamada
+ tool_input: dict # Parâmetros de entrada mutáveis
+ tool: CrewStructuredTool # Instância da ferramenta
+ agent: Agent | None # Agente executando
+ task: Task | None # Tarefa atual
+ crew: Crew | None # Instância da crew
+ tool_result: str | None # Resultado da ferramenta (hooks posteriores)
+```
+
+## Padrões Comuns
+
+### Segurança e Validação
+
+```python
+@before_tool_call
+def safety_check(context):
+ """Bloqueia operações destrutivas."""
+ dangerous = ['delete_file', 'drop_table', 'system_shutdown']
+ if context.tool_name in dangerous:
+ print(f"🛑 Bloqueado: {context.tool_name}")
+ return False
+ return None
+
+@before_llm_call
+def iteration_limit(context):
+ """Previne loops infinitos."""
+ if context.iterations > 15:
+ print("⛔ Máximo de iterações excedido")
+ return False
+ return None
+```
+
+### Humano no Loop
+
+```python
+@before_tool_call
+def require_approval(context):
+ """Requer aprovação para operações sensíveis."""
+ sensitive = ['send_email', 'make_payment', 'post_message']
+
+ if context.tool_name in sensitive:
+ response = context.request_human_input(
+ prompt=f"Aprovar {context.tool_name}?",
+ default_message="Digite 'sim' para aprovar:"
+ )
+
+ if response.lower() != 'sim':
+ return False
+
+ return None
+```
+
+### Monitoramento e Análise
+
+```python
+from collections import defaultdict
+import time
+
+metrics = defaultdict(lambda: {'count': 0, 'total_time': 0})
+
+@before_tool_call
+def start_timer(context):
+ context.tool_input['_start'] = time.time()
+ return None
+
+@after_tool_call
+def track_metrics(context):
+ start = context.tool_input.get('_start', time.time())
+ duration = time.time() - start
+
+ metrics[context.tool_name]['count'] += 1
+ metrics[context.tool_name]['total_time'] += duration
+
+ return None
+```
+
+## Gerenciamento de Hooks
+
+### Limpar Todos os Hooks
+
+```python
+from crewai.hooks import clear_all_global_hooks
+
+# Limpa todos os hooks de uma vez
+result = clear_all_global_hooks()
+print(f"Limpou {result['total']} hooks")
+```
+
+### Limpar Tipos Específicos de Hooks
+
+```python
+from crewai.hooks import (
+ clear_before_llm_call_hooks,
+ clear_after_llm_call_hooks,
+ clear_before_tool_call_hooks,
+ clear_after_tool_call_hooks
+)
+
+# Limpar tipos específicos
+llm_before_count = clear_before_llm_call_hooks()
+tool_after_count = clear_after_tool_call_hooks()
+```
+
+## Melhores Práticas
+
+### 1. Mantenha os Hooks Focados
+Cada hook deve ter uma responsabilidade única e clara.
+
+### 2. Trate Erros Graciosamente
+```python
+@before_llm_call
+def safe_hook(context):
+ try:
+ if some_condition:
+ return False
+ except Exception as e:
+ print(f"Erro no hook: {e}")
+ return None # Permitir execução apesar do erro
+```
+
+### 3. Modifique o Contexto In-Place
+```python
+# ✅ Correto - modificar in-place
+@before_llm_call
+def add_context(context):
+ context.messages.append({"role": "system", "content": "Seja conciso"})
+
+# ❌ Errado - substitui referência
+@before_llm_call
+def wrong_approach(context):
+ context.messages = [{"role": "system", "content": "Seja conciso"}]
+```
+
+### 4. Use Type Hints
+```python
+from crewai.hooks import LLMCallHookContext, ToolCallHookContext
+
+def my_llm_hook(context: LLMCallHookContext) -> bool | None:
+ return None
+
+def my_tool_hook(context: ToolCallHookContext) -> str | None:
+ return None
+```
+
+### 5. Limpe em Testes
+```python
+import pytest
+from crewai.hooks import clear_all_global_hooks
+
+@pytest.fixture(autouse=True)
+def clean_hooks():
+ """Reseta hooks antes de cada teste."""
+ yield
+ clear_all_global_hooks()
+```
+
+## Quando Usar Qual Hook
+
+### Use Hooks LLM Quando:
+- Implementar limites de iteração
+- Adicionar contexto ou diretrizes de segurança aos prompts
+- Rastrear uso de tokens e custos
+- Sanitizar ou transformar respostas
+- Implementar gates de aprovação para chamadas LLM
+- Fazer debug de interações de prompt/resposta
+
+### Use Hooks de Ferramenta Quando:
+- Bloquear operações perigosas ou destrutivas
+- Validar entradas de ferramenta antes da execução
+- Implementar gates de aprovação para ações sensíveis
+- Fazer cache de resultados de ferramenta
+- Rastrear uso e performance de ferramentas
+- Sanitizar saídas de ferramenta
+- Limitar taxa de chamadas de ferramenta
+
+### Use Ambos Quando:
+Construir sistemas abrangentes de observabilidade, segurança ou aprovação que precisam monitorar todas as operações do agente.
+
+## Documentação Relacionada
+
+- [Hooks de Chamada LLM →](/learn/llm-hooks) - Documentação detalhada de hooks LLM
+- [Hooks de Chamada de Ferramenta →](/learn/tool-hooks) - Documentação detalhada de hooks de ferramenta
+- [Hooks Antes e Depois do Kickoff →](/learn/before-and-after-kickoff-hooks) - Hooks do ciclo de vida da crew
+- [Humano no Loop →](/learn/human-in-the-loop) - Padrões de entrada humana
+
+## Conclusão
+
+Os Hooks de Execução fornecem controle poderoso sobre o comportamento em tempo de execução do agente. Use-os para implementar guardrails de segurança, fluxos de trabalho de aprovação, monitoramento abrangente e lógica de negócio personalizada. Combinados com tratamento adequado de erros, segurança de tipos e considerações de performance, os hooks permitem sistemas de agentes seguros, prontos para produção e observáveis.
diff --git a/docs/v1.15.13/pt-BR/learn/force-tool-output-as-result.mdx b/docs/v1.15.13/pt-BR/learn/force-tool-output-as-result.mdx
new file mode 100644
index 0000000000..c053c34488
--- /dev/null
+++ b/docs/v1.15.13/pt-BR/learn/force-tool-output-as-result.mdx
@@ -0,0 +1,51 @@
+---
+title: Forçar a Saída da Ferramenta como Resultado
+description: Aprenda como forçar a saída de uma ferramenta como resultado em uma tarefa de Agent no CrewAI.
+icon: wrench-simple
+mode: "wide"
+---
+
+## Introdução
+
+No CrewAI, você pode forçar a saída de uma ferramenta como o resultado de uma tarefa de um agent.
+Esse recurso é útil quando você deseja garantir que a saída da ferramenta seja capturada e retornada como resultado da tarefa, evitando quaisquer modificações pelo agent durante a execução da tarefa.
+
+## Forçando a Saída da Ferramenta como Resultado
+
+Para forçar a saída da ferramenta como resultado da tarefa de um agent, você precisa definir o parâmetro `result_as_answer` como `True` ao adicionar uma ferramenta ao agent.
+Esse parâmetro garante que a saída da ferramenta seja capturada e retornada como resultado da tarefa, sem qualquer modificação pelo agent.
+
+Veja um exemplo de como forçar a saída da ferramenta como resultado da tarefa de um agent:
+
+```python Code
+from crewai.agent import Agent
+from my_tool import MyCustomTool
+
+# Create a coding agent with the custom tool
+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)],
+ )
+
+# Assuming the tool's execution and result population occurs within the system
+task_result = coding_agent.execute_task(task)
+```
+
+## Fluxo de Trabalho em Ação
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+Além disso, você pode visualizar a visualização do gráfico de execução do rastreamento, que mostra o controle e o fluxo de dados do rastreamento, que será dimensionado com agentes maiores para mostrar transferências e relacionamentos entre chamadas LLM, chamadas de ferramentas e interações de agentes.
+
+
+
+
+
+## Referências
+
+- [Datadog LLM Observability](https://www.datadoghq.com/product/llm-observability/)
+- [Datadog LLM Observability CrewAI Auto-Instrumentation](https://docs.datadoghq.com/llm_observability/instrumentation/auto_instrumentation?tab=python#crew-ai)
diff --git a/docs/v1.15.13/pt-BR/observability/galileo.mdx b/docs/v1.15.13/pt-BR/observability/galileo.mdx
new file mode 100644
index 0000000000..4296e35fb9
--- /dev/null
+++ b/docs/v1.15.13/pt-BR/observability/galileo.mdx
@@ -0,0 +1,115 @@
+---
+title: Galileo Galileu
+description: Integração Galileo para rastreamento e avaliação CrewAI
+icon: telescope
+mode: "wide"
+---
+
+## Visão geral
+
+Este guia demonstra como integrar o **Galileo**com o **CrewAI**
+para rastreamento abrangente e engenharia de avaliação.
+Ao final deste guia, você será capaz de rastrear seus agentes CrewAI,
+monitorar seu desempenho e avaliar seu comportamento com
+A poderosa plataforma de observabilidade do Galileo.
+
+> **O que é Galileo?**[Galileo](https://galileo.ai/) é avaliação e observabilidade de IA
+plataforma que oferece rastreamento, avaliação e
+e monitoramento de aplicações de IA. Ele permite que as equipes capturem a verdade,
+criar grades de proteção robustas e realizar experimentos sistemáticos com
+rastreamento de experimentos integrado e análise de desempenho -garantindo confiabilidade,
+transparência e melhoria contínua em todo o ciclo de vida da IA.
+
+## Primeiros passos
+
+Este tutorial segue o [CrewAI Quickstart](pt-BR/quickstart) e mostra como adicionar
+[CrewAIEventListener] do Galileo(https://v2docs.galileo.ai/sdk-api/python/reference/handlers/crewai/handler),
+um manipulador de eventos.
+Para mais informações, consulte Galileu
+[Adicionar Galileo a um aplicativo CrewAI](https://v2docs.galileo.ai/how-to-guides/third-party-integrations/add-galileo-to-crewai/add-galileo-to-crewai)
+guia prático.
+
+> **Observação**Este tutorial pressupõe que você concluiu o [CrewAI Quickstart](pt-BR/quickstart).
+Se você quiser um exemplo completo e abrangente, consulte o Galileo
+[Repositório de exemplo SDK da CrewAI](https://github.com/rungalileo/sdk-examples/tree/main/python/agent/crew-ai).
+
+### Etapa 1: instalar dependências
+
+Instale as dependências necessárias para seu aplicativo.
+Crie um ambiente virtual usando seu método preferido,
+em seguida, instale dependências dentro desse ambiente usando seu
+ferramenta preferida:
+
+```bash
+uv add galileo
+```
+
+### Etapa 2: adicione ao arquivo .env do [CrewAI Quickstart](/pt-BR/quickstart)
+
+```bash
+# Your Galileo API key
+GALILEO_API_KEY="your-galileo-api-key"
+
+# Your Galileo project name
+GALILEO_PROJECT="your-galileo-project-name"
+
+# The name of the Log stream you want to use for logging
+GALILEO_LOG_STREAM="your-galileo-log-stream "
+```
+
+### Etapa 3: adicionar o ouvinte de eventos Galileo
+
+Para habilitar o registro com Galileo, você precisa criar uma instância do `CrewAIEventListener`.
+Importe o pacote manipulador Galileo CrewAI por
+adicionando o seguinte código no topo do seu arquivo main.py:
+
+```python
+from galileo.handlers.crewai.handler import CrewAIEventListener
+```
+
+No início da sua função run, crie o ouvinte de evento:
+
+```python
+def run():
+ # Create the event listener
+ CrewAIEventListener()
+ # The rest of your existing code goes here
+```
+
+Quando você cria a instância do listener, ela é automaticamente
+registrado na CrewAI.
+
+### Etapa 4: administre sua Crew
+
+Administre sua Crew com o CrewAI CLI:
+
+```bash
+crewai run
+```
+
+### Passo 5: Visualize os traços no Galileo
+
+Assim que sua tripulação terminar, os rastros serão eliminados e aparecerão no Galileo.
+
+
+
+## Compreendendo a integração do Galileo
+
+Galileo se integra ao CrewAI registrando um ouvinte de evento
+que captura eventos de execução da tripulação (por exemplo, ações do agente, chamadas de ferramentas, respostas do modelo)
+e os encaminha ao Galileo para observabilidade e avaliação.
+
+### Compreendendo o ouvinte de eventos
+
+Criar uma instância `CrewAIEventListener()` é tudo o que você precisa
+necessário para habilitar o Galileo para uma execução do CrewAI. Quando instanciado, o ouvinte:
+
+-Registra-se automaticamente no CrewAI
+-Lê a configuração do Galileo a partir de variáveis de ambiente
+-Registra todos os dados de execução no projeto Galileo e fluxo de log especificado por
+ `GALILEO_PROJECT` e `GALILEO_LOG_STREAM`
+
+Nenhuma configuração adicional ou alterações de código são necessárias.
+Todos os dados desta execução são registados no projecto Galileo e
+fluxo de log especificado pela configuração do seu ambiente
+(por exemplo, GALILEO_PROJECT e GALILEO_LOG_STREAM).
diff --git a/docs/v1.15.13/pt-BR/observability/langdb.mdx b/docs/v1.15.13/pt-BR/observability/langdb.mdx
new file mode 100644
index 0000000000..86b2aea826
--- /dev/null
+++ b/docs/v1.15.13/pt-BR/observability/langdb.mdx
@@ -0,0 +1,287 @@
+---
+title: Integração LangDB
+description: Governe, proteja e otimize seus fluxos de trabalho CrewAI com LangDB AI Gateway—acesse mais de 350 modelos, roteamento automático, otimização de custos e observabilidade completa.
+icon: database
+mode: "wide"
+---
+
+# Introdução
+
+[LangDB AI Gateway](https://langdb.ai) fornece APIs compatíveis com OpenAI para conectar com múltiplos Modelos de Linguagem Grandes e serve como uma plataforma de observabilidade que torna effortless rastrear fluxos de trabalho CrewAI de ponta a ponta, proporcionando acesso a mais de 350 modelos de linguagem. Com uma única chamada `init()`, todas as interações de agentes, execuções de tarefas e chamadas LLM são capturadas, fornecendo observabilidade abrangente e infraestrutura de IA pronta para produção para suas aplicações.
+
+
+
+
+
+**Confira:** [Ver o exemplo de trace ao vivo](https://app.langdb.ai/sharing/threads/3becbfed-a1be-ae84-ea3c-4942867a3e22)
+
+## Recursos
+
+### Capacidades do AI Gateway
+- **Acesso a mais de 350 LLMs**: Conecte-se a todos os principais modelos de linguagem através de uma única integração
+- **Modelos Virtuais**: Crie configurações de modelo personalizadas com parâmetros específicos e regras de roteamento
+- **MCP Virtual**: Habilite compatibilidade e integração com sistemas MCP (Model Context Protocol) para comunicação aprimorada de agentes
+- **Guardrails**: Implemente medidas de segurança e controles de conformidade para comportamento de agentes
+
+### Observabilidade e Rastreamento
+- **Rastreamento Automático**: Uma única chamada `init()` captura todas as interações CrewAI
+- **Visibilidade Ponta a Ponta**: Monitore fluxos de trabalho de agentes do início ao fim
+- **Rastreamento de Uso de Ferramentas**: Rastreie quais ferramentas os agentes usam e seus resultados
+- **Monitoramento de Chamadas de Modelo**: Insights detalhados sobre interações LLM
+- **Análise de Performance**: Monitore latência, uso de tokens e custos
+- **Suporte a Depuração**: Execução passo a passo para solução de problemas
+- **Monitoramento em Tempo Real**: Dashboard de traces e métricas ao vivo
+
+## Instruções de Configuração
+
+
+
+
+### O Que Você Verá
+
+- **Interações de Agentes**: Fluxo completo de conversas de agentes e transferências de tarefas
+- **Uso de Ferramentas**: Quais ferramentas foram chamadas, suas entradas e saídas
+- **Chamadas de Modelo**: Interações LLM detalhadas com prompts e respostas
+- **Métricas de Performance**: Rastreamento de latência, uso de tokens e custos
+- **Linha do Tempo de Execução**: Visualização passo a passo de todo o fluxo de trabalho
+
+
+## Solução de Problemas
+
+### Problemas Comuns
+
+- **Nenhum trace aparecendo**: Certifique-se de que `init()` seja chamado antes de qualquer importação CrewAI
+- **Erros de autenticação**: Verifique sua chave API LangDB e ID do projeto
+
+
+## Recursos
+
+
+
+
+
+
+
+
+### Funcionalidades
+
+- **Painel Analítico**: Monitore a saúde e desempenho dos seus Agentes com dashboards detalhados que acompanham métricas, custos e interações dos usuários.
+- **SDK de Observabilidade Nativo OpenTelemetry**: SDKs neutros de fornecedor para enviar rastreamentos e métricas para suas ferramentas de observabilidade existentes como Grafana, DataDog e outros.
+- **Rastreamento de Custos para Modelos Customizados e Ajustados**: Adapte estimativas de custo para modelos específicos usando arquivos de precificação customizados para orçamentos precisos.
+- **Painel de Monitoramento de Exceções**: Identifique e solucione rapidamente problemas ao rastrear exceções comuns e erros por meio de um painel de monitoramento.
+- **Conformidade e Segurança**: Detecte ameaças potenciais como profanidade e vazamento de dados sensíveis (PII).
+- **Detecção de Prompt Injection**: Identifique possíveis injeções de código e vazamentos de segredos.
+- **Gerenciamento de Chaves de API e Segredos**: Gerencie suas chaves de API e segredos do LLM de forma centralizada e segura, evitando práticas inseguras.
+- **Gerenciamento de Prompt**: Gerencie e versiona prompts de Agente usando o PromptHub para acesso consistente e fácil entre os agentes.
+- **Model Playground** Teste e compare diferentes modelos para seus agentes CrewAI antes da implantação.
+
+## Instruções de Configuração
+
+
+
+
+
+
+
+
+O Opik oferece suporte abrangente para cada etapa do desenvolvimento da sua aplicação CrewAI:
+
+- **Registrar Traces e Spans**: Acompanhe automaticamente chamadas LLM e lógica da aplicação para depurar e analisar sistemas em desenvolvimento e em produção. Anote manualmente ou programaticamente, visualize e compare respostas entre projetos.
+- **Avalie a Performance da sua Aplicação LLM**: Avalie contra um conjunto de testes personalizado e execute métricas de avaliação nativas ou defina suas próprias métricas via SDK ou UI.
+- **Teste no Pipeline CI/CD**: Estabeleça bases de performance confiáveis com os testes unitários LLM do Opik, baseados em PyTest. Execute avaliações online para monitoramento contínuo em produção.
+- **Monitore & Analise Dados de Produção**: Entenda a performance dos seus modelos em dados inéditos em produção e gere conjuntos de dados para novas iterações de desenvolvimento.
+
+## Configuração
+A Comet oferece uma versão hospedada da plataforma Opik, ou você pode rodar a plataforma localmente.
+
+Para usar a versão hospedada, basta [criar uma conta gratuita na Comet](https://www.comet.com/signup?utm_medium=github&utm_source=crewai_docs) e obter sua chave de API.
+
+Para rodar a plataforma Opik localmente, veja nosso [guia de instalação](https://www.comet.com/docs/opik/self-host/overview/) para mais informações.
+
+Neste guia, utilizaremos o exemplo de início rápido da CrewAI.
+
+
+
+
+
+## Introdução
+
+Portkey aprimora o CrewAI com recursos prontos para produção, transformando seus crews de agentes experimentais em sistemas robustos ao fornecer:
+
+- **Observabilidade completa** de cada etapa do agente, uso de ferramentas e interações
+- **Confiabilidade incorporada** com fallbacks, tentativas automáticas e balanceamento de carga
+- **Rastreamento e otimização de custos** para gerenciar seus gastos com IA
+- **Acesso a mais de 200 LLMs** por meio de uma única integração
+- **Guardrails** para manter o comportamento dos agentes seguro e em conformidade
+- **Prompts versionados** para desempenho consistente dos agentes
+
+
+### Instalação & Configuração
+
+
+
+
+Os traces fornecem uma visão hierárquica da execução do seu crew, mostrando a sequência de chamadas LLM, ativações de ferramentas e transições de estado.
+
+```python
+# Adicione trace_id para habilitar o tracing hierárquico no Portkey
+portkey_llm = LLM(
+ model="gpt-4o",
+ base_url=PORTKEY_GATEWAY_URL,
+ api_key="dummy",
+ extra_headers=createHeaders(
+ api_key="YOUR_PORTKEY_API_KEY",
+ virtual_key="YOUR_OPENAI_VIRTUAL_KEY",
+ trace_id="unique-session-id" # Adicione um trace ID único
+ )
+)
+```
+
+
+
+Portkey registra cada interação com LLMs, incluindo:
+
+- Payloads completos das requisições e respostas
+- Métricas de latência e uso de tokens
+- Cálculos de custo
+- Chamadas de ferramentas e execuções de funções
+
+Todos os logs podem ser filtrados por metadados, trace IDs, modelos e mais, tornando mais fácil depurar execuções específicas do crew.
+
+
+
+Portkey oferece dashboards integrados que ajudam você a:
+
+- Rastrear custos e uso de tokens em todas as execuções do crew
+- Analisar métricas de desempenho, como latência e taxas de sucesso
+- Identificar gargalos nos fluxos de trabalho dos agentes
+- Comparar diferentes configurações de crew e LLMs
+
+Você pode filtrar e segmentar todas as métricas por metadados personalizados para analisar tipos de crew, grupos de usuários ou casos de uso específicos.
+
+
+
+Adicione metadados personalizados à configuração LLM do seu CrewAI para permitir filtragem e segmentação poderosas:
+
+```python
+portkey_llm = LLM(
+ model="gpt-4o",
+ base_url=PORTKEY_GATEWAY_URL,
+ api_key="dummy",
+ extra_headers=createHeaders(
+ api_key="YOUR_PORTKEY_API_KEY",
+ virtual_key="YOUR_OPENAI_VIRTUAL_KEY",
+ metadata={
+ "crew_type": "research_crew",
+ "environment": "production",
+ "_user": "user_123", # Campo especial _user para analytics de usuários
+ "request_source": "mobile_app"
+ }
+ )
+)
+```
+
+Esses metadados podem ser usados para filtrar logs, traces e métricas no painel do Portkey, permitindo analisar execuções específicas do crew, usuários ou ambientes.
+
+
+
+Isso permite:
+- Rastreamento de custos e orçamento por usuário
+- Analytics personalizados por usuário
+- Métricas por equipe ou organização
+- Monitoramento específico por ambiente (homologação x produção)
+
+
+
+
+
+
+
+
+
+
+
+
+ Documentação oficial do CrewAI
+Receba orientação personalizada sobre como implementar essa integração
+
+
+