{"id":"crewai","kind":"sdk","name":"CrewAI","slug":"crewai","description":"Python framework for orchestrating role-playing AI agent crews.","vendor":"CrewAI","languages":["python"],"categories":["ai"],"homepage":"https://www.crewai.com","docsUrl":"https://docs.crewai.com","githubUrl":"https://github.com/crewAIInc/crewAI","packages":[{"registry":"pypi","name":"crewai","url":"https://pypi.org/project/crewai/"}],"tags":["agents"],"skills":[{"name":"getting-started","url":"https://skills.sh/crewaiinc/skills/getting-started","install":"npx skills add crewaiinc/skills","sdk":"crewai","key":"crewai/getting-started","description":"CrewAI architecture decisions and project scaffolding. Use when starting a new crewAI project, choosing between LLM.call() vs Agent.kickoff() vs Crew.kickoff() vs Flow, scaffolding with 'crewai create flow', setting up YAML config (agents.yaml, tasks.yaml), wiring @CrewBase crew.py, writing Flow main.py with @start/@listen, building experimental conversational Flows with handle_turn()/chat(), or using {variable} interpolation.","hasContent":true,"content":"---\nname: getting-started\ndescription: \"CrewAI architecture decisions and project scaffolding. Use when starting a new crewAI project, choosing between LLM.call() vs Agent.kickoff() vs Crew.kickoff() vs Flow, scaffolding with 'crewai create flow', setting up YAML config (agents.yaml, tasks.yaml), wiring @CrewBase crew.py, writing Flow main.py with @start/@listen, building experimental conversational Flows with handle_turn()/chat(), or using {variable} interpolation.\"\n---\n\n# CrewAI Getting Started & Architecture\n\nHow to choose the right abstraction, scaffold a project, and wire everything together.\n\n---\n\n## MANDATORY WORKFLOW — Read This First\n\n**NEVER manually create crewAI project files.** Always scaffold with the CLI:\n\n```bash\ncrewai create flow <project_name>\n```\n\nThis is **not optional**. Even if you only need one crew, even if you know the file structure by heart — run the CLI first, then modify the generated files. Do NOT write `main.py`, `crew.py`, `agents.yaml`, `tasks.yaml`, or `pyproject.toml` by hand from scratch.\n\n> **Why:** The CLI sets up correct imports, directory structure, pyproject.toml config, and boilerplate that is easy to get subtly wrong when done manually. The reference material below teaches you how the pieces work so you can *modify* scaffolded code, not so you can *replace* the scaffolding step.\n\n**Workflow:**\n1. Run `crewai create flow <name>` (use **underscores**, not hyphens)\n2. Edit the generated YAML and Python files to match your use case\n3. Run `crewai install` then `crewai run`\n\n---\n\n## 1. Choosing the Right Abstraction\n\ncrewAI has five common abstraction choices. Pick the simplest one that fits your need:\n\n| Level | When to Use | Overhead | Example |\n|---|---|---|---|\n| `LLM.call()` | Single prompt, no tools, structured extraction | Lowest | Parse an email into fields |\n| `Agent.kickoff()` | One agent with tools and reasoning, no multi-agent coordination | Low | Research a topic with web search |\n| `Crew.kickoff()` | Multiple agents collaborating on related tasks | Medium | Research + write + review pipeline |\n| `Flow` wrapping crews/agents/LLM calls | Production app with state, routing, conditionals, error handling | Full | Multi-step workflow with branching logic |\n| Conversational `Flow` | Multi-turn chat where each user line re-runs a Flow with the same session id | Full + experimental | Support assistant with routed chat, research, and escalation turns |\n\n### Decision Flowchart\n\n```\nDo you need tools or multi-step reasoning?\n├── No  → LLM.call()\n└── Yes\n    └── Do you need multiple agents collaborating?\n        ├── No  → Agent.kickoff()\n        └── Yes\n            └── Do you need state management, routing, or multiple crews?\n                ├── No  → Crew (but still scaffold as a Flow for future-proofing)\n                └── Yes → Flow + Crew(s)\n\nDo users send multiple chat messages in one session?\n└── Yes → Conversational Flow with handle_turn(message, session_id=...)\n```\n\n**Rule of thumb:** For any production application, **always start with a Flow**. You can embed `LLM.call()`, `Agent.kickoff()`, or `Crew.kickoff()` inside Flow steps. This gives you state management, error handling, and room to grow.\n\nFor chat applications, start with a conversational `Flow` rather than trying to make `Crew.kickoff()` or `Flow.kickoff()` act like a chat loop. The conversational surface is experimental, but it is the intended API for multi-turn sessions: call `flow.handle_turn(message, session_id=...)` for every user line, or `flow.chat()` for a local terminal REPL. Official guide: <https://docs.crewai.com/en/guides/flows/conversational-flows>.\n\n---\n\n## 2. LLM.call() — Direct LLM Invocation\n\nUse for simple, single-turn tasks where you don't need tools or agent reasoning.\n\n```python\nfrom crewai import LLM\nfrom pydantic import BaseModel\n\nclass EmailFields(BaseModel):\n    sender: str\n    subject: str\n    urgency: str\n\nllm = LLM(model=\"openai/gpt-4o\")\n\n# Without response_format — returns a string\nraw = llm.call(messages=[{\"role\": \"user\", \"content\": \"Summarize this text...\"}])\nprint(raw)  # str\n\n# With response_format — returns the Pydantic object directly\nresult = llm.call(\n    messages=[{\"role\": \"user\", \"content\": f\"Extract fields from this email: {email_text}\"}],\n    response_format=EmailFields\n)\nprint(result.sender)   # str — access Pydantic fields directly\nprint(result.urgency)  # str\n```\n\n**When NOT to use:** If you need tools, multi-step reasoning, or retries — use an Agent instead.\n\n---\n\n## 3. Agent.kickoff() — Single Agent Execution\n\nUse when you need one agent with tools and reasoning, but don't need multi-agent coordination.\n\n```python\nfrom crewai import Agent\nfrom crewai_tools import SerperDevTool\nfrom pydantic import BaseModel\n\nclass ResearchFindings(BaseModel):\n    main_points: list[str]\n    key_technologies: list[str]\n\nresearcher = Agent(\n    role=\"AI Researcher\",\n    goal=\"Research the latest AI developments\",\n    backstory=\"Expert AI researcher with deep technical knowledge.\",\n    llm=\"openai/gpt-4o\",       # Optional: defaults to OPENAI_MODEL_NAME env var or \"gpt-4\"\n    tools=[SerperDevTool()],\n)\n\n# Unstructured output\nresult = researcher.kickoff(\"What are the latest LLM developments?\")\nprint(result.raw)            # str\nprint(result.usage_metrics)  # token usage\n\n# Structured output with response_format\nresult = researcher.kickoff(\n    \"Summarize latest AI developments\",\n    response_format=ResearchFindings,\n)\nprint(result.pydantic.main_points)\n```\n\n> **Note:** `Agent.kickoff()` wraps results — access structured output via `result.pydantic`. This differs from `LLM.call()`, which returns the Pydantic object directly.\n\n**When NOT to use:** If you need multiple agents passing context to each other — use a Crew.\n\n---\n\n## 4. CLI Scaffold Reference\n\nAs stated above: **NEVER skip `crewai create flow`.** This section documents what the CLI generates so you know what to modify — not so you can recreate it by hand.\n\n```bash\ncrewai create flow my_project\n```\n\n> **Warning:** Always use **underscores** in project names, not hyphens. `crewai create flow my-project` creates a directory that is not a valid Python identifier, causing `ModuleNotFoundError` on import. Use `my_project` instead.\n\nThis generates:\n\n```\nmy_project/\n├── src/my_project/\n│   ├── crews/\n│   │   └── my_crew/\n│   │       ├── config/\n│   │       │   ├── agents.yaml    # Agent definitions (role, goal, backstory)\n│   │       │   └── tasks.yaml     # Task definitions (description, expected_output)\n│   │       └── my_crew.py         # Crew class with @CrewBase\n│   ├── tools/\n│   │   └── custom_tool.py\n│   ├── main.py                    # Flow class with @start/@listen\n│   └── ...\n├── .env                           # API keys (OPENAI_API_KEY, etc.)\n└── pyproject.toml\n```\n\n> **Do not** use `crewai create crew` unless you are certain you will never need routing, state, or multiple crews. Prefer `crewai create flow` as the default.\n\n---\n\n## 5. YAML Configuration (agents.yaml & tasks.yaml)\n\nThe scaffold uses YAML files for agent and task definitions. This separates configuration from code and supports `{variable}` interpolation.\n\n### agents.yaml\n\n```yaml\nresearcher:\n  role: >\n    {topic} Senior Data Researcher\n  goal: >\n    Uncover cutting-edge developments in {topic}\n  backstory: >\n    You're a seasoned researcher with a knack for uncovering\n    the latest developments in {topic}.\n  # Optional overrides:\n  # llm: openai/gpt-4o\n  # max_iter: 20\n  # max_rpm: 10\n\nreporting_analyst:\n  role: >\n    {topic} Reporting Analyst\n  goal: >\n    Create detailed reports based on {topic} research findings\n  backstory: >\n    You're a meticulous analyst known for turning complex data\n    into clear, actionable reports.\n```\n\n### tasks.yaml\n\n```yaml\nresearch_task:\n  description: >\n    Conduct thorough research about {topic}.\n    Identify key trends, breakthrough technologies,\n    and potential industry impacts.\n  expected_output: >\n    A detailed report with analysis of the top 5\n    developments in {topic}, with sources and implications.\n  agent: researcher\n\nreporting_task:\n  description: >\n    Review the research and create a comprehensive report about {topic}.\n  expected_output: >\n    A polished report formatted in markdown with sections\n    for each key finding.\n  agent: reporting_analyst\n  output_file: output/report.md\n```\n\n**Key rules:**\n- `{variable}` placeholders are replaced at runtime via `crew.kickoff(inputs={...})`\n- `expected_output` is always a **string** (never a Pydantic class name)\n- `agent` value must match an agent key in `agents.yaml`\n- In `Process.sequential`, each task auto-receives all prior task outputs as context\n- For non-sequential deps, use `context=[other_task]` to explicitly pass output\n\n---\n\n## 6. Wiring It Together — crew.py\n\nThe `@CrewBase` decorator auto-loads YAML config files and collects `@agent` and `@task` methods.\n\n```python\nfrom crewai import Agent, Crew, Process, Task\nfrom crewai.project import CrewBase, agent, crew, task\nfrom crewai_tools import SerperDevTool\n\n@CrewBase\nclass ResearchCrew:\n    \"\"\"Research and reporting crew.\"\"\"\n\n    agents_config = \"config/agents.yaml\"\n    tasks_config = \"config/tasks.yaml\"\n\n    @agent\n    def researcher(self) -> Agent:\n        return Agent(\n            config=self.agents_config[\"researcher\"],\n            tools=[SerperDevTool()],\n        )\n\n    @agent\n    def reporting_analyst(self) -> Agent:\n        return Agent(\n            config=self.agents_config[\"reporting_analyst\"],\n        )\n\n    @task\n    def research_task(self) -> Task:\n        return Task(config=self.tasks_config[\"research_task\"])\n\n    @task\n    def reporting_task(self) -> Task:\n        return Task(\n            config=self.tasks_config[\"reporting_task\"],\n            context=[self.research_task()],  # Explicit dependency (optional in sequential)\n            output_file=\"output/report.md\",\n        )\n\n    @crew\n    def crew(self) -> Crew:\n        return Crew(\n            agents=self.agents,  # auto-collected by @agent\n            tasks=self.tasks,    # auto-collected by @task\n            process=Process.sequential,\n            verbose=True,\n        )\n```\n\n**Important:** Method names must match YAML keys. `def researcher(self)` maps to the `researcher:` key in `agents.yaml`.\n\n---\n\n## 7. Flows — The Production Foundation\n\nFlows are the recommended way to build production crewAI applications. They provide state management, conditional routing, human-in-the-loop, and persistence — wrapping crews, agents, and LLM calls into a coherent workflow.\n\n### Basic Flow — main.py\n\n```python\nfrom crewai.flow.flow import Flow, listen, start\nfrom pydantic import BaseModel\nfrom .crews.research_crew.research_crew import ResearchCrew\n\nclass ResearchState(BaseModel):\n    topic: str = \"\"\n    report: str = \"\"\n\nclass ResearchFlow(Flow[ResearchState]):\n\n    @start()\n    def begin(self):\n        print(f\"Starting research on: {self.state.topic}\")\n\n    @listen(begin)\n    def run_research(self):\n        result = ResearchCrew().crew().kickoff(\n            inputs={\"topic\": self.state.topic}\n        )\n        self.state.report = result.raw\n\ndef kickoff():\n    flow = ResearchFlow()\n    flow.kickoff(inputs={\"topic\": \"AI Agents\"})\n\nif __name__ == \"__main__\":\n    kickoff()\n```\n\n**Key points:**\n- `flow.kickoff(inputs={\"topic\": \"AI Agents\"})` populates `self.state.topic` (keys must match Pydantic field names). The YAML `{variable}` substitution happens later, when you call `crew.kickoff(inputs={\"topic\": self.state.topic})` inside a Flow step. The chain is: **flow inputs → state → crew inputs → YAML substitution**.\n- Each `@listen` method runs after its dependency completes\n- State persists across all Flow steps — use it to pass data between crews\n\n### State Management — Structured vs Unstructured\n\n**Structured (recommended for production):**\n```python\nfrom pydantic import BaseModel\n\nclass MyState(BaseModel):\n    topic: str = \"\"\n    research: str = \"\"\n    draft: str = \"\"\n    approved: bool = False\n\nclass MyFlow(Flow[MyState]):\n    ...\n```\n\n**Unstructured (quick prototyping):**\n```python\nclass MyFlow(Flow):  # No type parameter — state is a dict\n    @start()\n    def begin(self):\n        self.state[\"topic\"] = \"AI\"  # dict-style access\n```\n\nUse structured state for type safety, IDE autocompletion, and validation. Use unstructured only for throwaway prototypes.\n\n### Using Agent.kickoff() Inside Flows (Common Pattern)\n\nMany production Flows skip Crews entirely and orchestrate individual agents via `Agent.kickoff()`. This gives you fine-grained control — each Flow step calls a specific agent, passes state, and stores the result. The Flow handles orchestration; agents handle reasoning.\n\n```python\nfrom crewai import Agent, LLM\nfrom crewai.flow.flow import Flow, listen, start\nfrom crewai_tools import SerperDevTool, ScrapeWebsiteTool\nfrom pydantic import BaseModel\n\nclass ResearchState(BaseModel):\n    query: str = \"\"\n    raw_research: str = \"\"\n    analysis: str = \"\"\n    report: str = \"\"\n\nclass DeepResearchFlow(Flow[ResearchState]):\n\n    @start()\n    def gather_research(self):\n        \"\"\"Agent with tools does the actual searching.\"\"\"\n        researcher = Agent(\n            role=\"Senior Research Analyst\",\n            goal=\"Find comprehensive, factual information about the given topic\",\n            backstory=\"You're an expert researcher who always cites sources and flags uncertainty.\",\n            tools=[SerperDevTool(), ScrapeWebsiteTool()],\n            llm=\"openai/gpt-4o\",\n        )\n        result = researcher.kickoff(\n            f\"Research this topic thoroughly: {self.state.query}\"\n        )\n        self.state.raw_research = result.raw\n\n    @listen(gather_research)\n    def analyze_findings(self):\n        \"\"\"A different agent analyzes the raw research — no tools needed.\"\"\"\n        analyst = Agent(\n            role=\"Data Analyst\",\n            goal=\"Extract key insights, patterns, and actionable recommendations\",\n            backstory=\"You turn raw data into clear, structured analysis.\",\n            llm=\"openai/gpt-4o\",\n        )\n        result = analyst.kickoff(\n            f\"Analyze these research findings and extract key insights:\\n\\n{self.state.raw_research}\"\n        )\n        self.state.analysis = result.raw\n\n    @listen(analyze_findings)\n    def write_report(self):\n        \"\"\"A writer agent produces the final deliverable.\"\"\"\n        writer = Agent(\n            role=\"Technical Writer\",\n            goal=\"Produce clear, actionable reports for non-technical readers\",\n            backstory=\"You specialize in making complex information accessible.\",\n            llm=\"openai/gpt-4o\",\n        )\n        result = writer.kickoff(\n            f\"Write a comprehensive report based on this analysis:\\n\\n{self.state.analysis}\"\n        )\n        self.state.report = result.raw\n```\n\n**Why this pattern works well:**\n- Each agent is purpose-built for its step — narrow role, specific tools\n- The Flow manages state and sequencing — no crew overhead\n- Easy to add routing, human review, or retry logic between steps\n- You can mix `Agent.kickoff()`, `LLM.call()`, and `Crew.kickoff()` freely\n\n**When to use Agent.kickoff() vs Crew.kickoff() in a Flow:**\n\n| Use `Agent.kickoff()` when | Use `Crew.kickoff()` when |\n|---|---|\n| Each step is a distinct agent with different tools | Multiple agents need to collaborate on ONE task |\n| You want the Flow to control sequencing | Agents need to pass context to each other within a step |\n| Steps are independent and don't need inter-agent delegation | You need hierarchical process with a manager |\n| You want maximum control over what data flows between steps | The sub-workflow is self-contained and reusable |\n\n### Agent.kickoff() with Structured Output in Flows\n\nCombine `response_format` with state for typed data flow between agents:\n\n```python\nclass Insights(BaseModel):\n    key_points: list[str]\n    recommendations: list[str]\n    confidence: float\n\nclass AnalysisFlow(Flow[AnalysisState]):\n\n    @start()\n    def research(self):\n        researcher = Agent(role=\"Researcher\", goal=\"...\", backstory=\"...\", tools=[SerperDevTool()])\n        result = researcher.kickoff(\n            f\"Research {self.state.topic}\",\n            response_format=Insights,\n        )\n        # result.pydantic gives you the typed Insights object\n        self.state.key_points = result.pydantic.key_points\n        self.state.recommendations = result.pydantic.recommendations\n```\n\n### Mixing Abstractions in a Flow\n\nA Flow can combine all crewAI abstractions in a single workflow:\n\n```python\nclass ProductFlow(Flow[ProductState]):\n\n    @start()\n    def classify_request(self):\n        # LLM.call() for simple classification\n        llm = LLM(model=\"openai/gpt-4o\")\n        self.state.category = llm.call(\n            messages=[{\"role\": \"user\", \"content\": f\"Classify: {self.state.request}\"}],\n            response_format=Category\n        ).category\n\n    @router(classify_request)\n    def route_by_category(self):\n        if self.state.category == \"simple\":\n            return \"quick_answer\"\n        return \"deep_research\"\n\n    @listen(\"quick_answer\")\n    def handle_simple(self):\n        # Agent.kickoff() for single-agent work\n        agent = Agent(role=\"Helper\", goal=\"Answer quickly\", backstory=\"...\")\n        result = agent.kickoff(self.state.request)\n        self.state.answer = result.raw\n\n    @listen(\"deep_research\")\n    def handle_complex(self):\n        # Crew.kickoff() for multi-agent collaboration\n        result = ResearchCrew().crew().kickoff(\n            inputs={\"topic\": self.state.request}\n        )\n        self.state.answer = result.raw\n```\n\n### Flow Routing with `@router`\n\nUse `@router` for conditional branching — return a string label, and `@listen(\"label\")` binds to branches:\n\n```python\nfrom crewai.flow.flow import Flow, listen, router, start, or_\n\nclass QualityFlow(Flow[QAState]):\n\n    @start()\n    def generate_content(self):\n        result = WriterCrew().crew().kickoff(inputs={\"topic\": self.state.topic})\n        self.state.draft = result.raw\n\n    @router(generate_content)\n    def check_quality(self):\n        llm = LLM(model=\"openai/gpt-4o\")\n        score = llm.call(\n            messages=[{\"role\": \"user\", \"content\": f\"Rate 1-10: {self.state.draft}\"}],\n            response_format=QualityScore\n        )\n        if score.rating >= 7:\n            return \"approved\"\n        return \"needs_revision\"\n\n    @listen(\"approved\")\n    def publish(self):\n        self.state.published = True\n\n    @listen(\"needs_revision\")\n    def revise(self):\n        result = EditorCrew().crew().kickoff(\n            inputs={\"draft\": self.state.draft}\n        )\n        self.state.draft = result.raw\n```\n\n### Converging Branches with `or_()` and `and_()`\n\n```python\nfrom crewai.flow.flow import Flow, listen, start, or_, and_\n\nclass ParallelFlow(Flow[MyState]):\n\n    @start()\n    def fetch_data_a(self):\n        ...\n\n    @start()\n    def fetch_data_b(self):\n        ...\n\n    # Runs when BOTH fetches complete\n    @listen(and_(fetch_data_a, fetch_data_b))\n    def merge_results(self):\n        ...\n\n    # Runs when EITHER source provides data\n    @listen(or_(fetch_data_a, fetch_data_b))\n    def process_first_available(self):\n        ...\n```\n\n### Flow Persistence with `@persist`\n\nFor long-running workflows that need to survive restarts:\n\n```python\nfrom crewai.flow.flow import Flow, start, listen, persist\nfrom crewai.flow.persistence import SQLiteFlowPersistence\n\n@persist(SQLiteFlowPersistence())  # Class-level: persists all methods\nclass LongRunningFlow(Flow[MyState]):\n\n    @start()\n    def step_one(self):\n        self.state.data = \"processed\"\n\n    @listen(step_one)\n    def step_two(self):\n        # If the process crashes here, restarting with the same\n        # state ID will resume from after step_one\n        ...\n```\n\n### Conversational Flows with `handle_turn()` (Experimental)\n\nUse a conversational `Flow` when the product is a chat session: support assistants, routed research helpers, onboarding wizards, or any UI where the same user sends multiple turns.\n\nCore model:\n- Each user message is a **new Flow run** with the **same session id**\n- `handle_turn(message, session_id=...)` appends the user line to `state.messages`, resets per-turn execution tracking, and calls `kickoff(inputs={\"id\": session_id})` internally\n- `Flow.kickoff()` does **not** accept `user_message=` or `session_id=` keyword args\n- Route chat turns with `route_turn()` plus `@listen(\"ROUTE\")` handlers\n- Call `append_assistant_message(reply)` in handlers so the next turn sees assistant history\n- Wrap owned loops in `try/finally` and call `finalize_session_traces()`; `flow.chat()` does this for local REPLs\n\n```python\nfrom uuid import uuid4\n\nfrom crewai import Agent, Flow\nfrom crewai.flow import listen\nfrom crewai.experimental.conversational import (\n    ConversationConfig,\n    ConversationState,\n)\n\n\n@ConversationConfig(defer_trace_finalization=True)\nclass SupportFlow(Flow[ConversationState]):\n    conversational = True\n\n    def research_agent(self) -> Agent:\n        return Agent(\n            role=\"Support Research Specialist\",\n            goal=\"Answer the user's current research question with accurate sources.\",\n            backstory=\"You are precise, evidence-driven, and explicit about uncertainty.\",\n            tools=[...],\n        )\n\n    def route_turn(self, context):\n        message = (self.state.current_user_message or \"\").lower()\n        if \"docs\" in message or \"crewai\" in message:\n            return \"CREWAI_DOCS\"\n        if \"research\" in message or \"search\" in message:\n            return \"RESEARCH\"\n        return \"converse\"\n\n    @listen(\"CREWAI_DOCS\")\n    def handle_docs(self):\n        \"\"\"Look up CrewAI documentation for framework/API questions.\"\"\"\n        reply = \"I would query the CrewAI docs here.\"\n        self.append_assistant_message(reply)\n        return reply\n\n    @listen(\"RESEARCH\")\n    def handle_research(self):\n        \"\"\"Fresh research, current lookups, and tool-backed investigation.\"\"\"\n        result = self.research_agent().kickoff(self.state.current_user_message)\n        reply = result.raw\n        self.append_assistant_message(reply)\n        return reply\n\n\nflow = SupportFlow()\nsession_id = str(uuid4())\n\ntry:\n    flow.handle_turn(\"What can you do?\", session_id=session_id)\n    flow.handle_turn(\"Check the CrewAI docs for flows.\", session_id=session_id)\nfinally:\n    flow.finalize_session_traces()\n```\n\nUse `RouterConfig` when you want LLM-driven routing. The router catalog is auto-built from `@listen(\"ROUTE\")` handlers and their docstrings, so do not duplicate the route list in the router prompt.\n\nSee [Conversational Flows](references/conversational-flows.md) for the full lifecycle, routing, persistence, and trace guidance.\n\n### Human-in-the-Loop with `@human_feedback`\n\n```python\nfrom crewai.flow.flow import Flow, start, listen, router\nfrom crewai.flow.human_feedback import human_feedback\n\nclass ApprovalFlow(Flow[ReviewState]):\n\n    @start()\n    def generate_draft(self):\n        result = WriterCrew().crew().kickoff(inputs={\"topic\": self.state.topic})\n        self.state.draft = result.raw\n\n    @human_feedback(\n        message=\"Review the draft and provide feedback\",\n        emit=[\"approved\", \"needs_revision\"],\n        llm=\"openai/gpt-4o\",\n        default_outcome=\"approved\"\n    )\n    @listen(generate_draft)\n    def review_step(self):\n        return self.state.draft\n\n    @listen(\"approved\")\n    def publish(self):\n        ...\n\n    @listen(\"needs_revision\")\n    def revise(self):\n        feedback = self.last_human_feedback\n        # Use feedback.feedback_text for revision\n        ...\n```\n\n### Flow Visualization\n\n```python\nflow = MyFlow()\nflow.plot()             # Display in notebook\nflow.plot(\"my_flow\")    # Save as my_flow.png\n```\n\n---\n\n## 8. Variable Interpolation with `inputs`\n\nThe `{variable}` pattern is how you make crews reusable.\n\n```python\n# Variables flow through: kickoff → YAML templates → agent/task prompts\ncrew.kickoff(inputs={\n    \"topic\": \"AI Agents\",\n    \"current_year\": \"2025\",\n    \"target_audience\": \"developers\",\n})\n```\n\nIn YAML, `{topic}` and `{current_year}` get replaced:\n\n```yaml\nresearch_task:\n  description: >\n    Research {topic} trends for {current_year},\n    targeting {target_audience}.\n```\n\n**Common mistakes:**\n- Forgetting to pass a variable that's referenced in YAML → results in literal `{variable}` in the prompt\n- Using Jinja2 syntax `{{ }}` instead of single-brace `{ }` → crewAI uses single braces\n- Passing variables that don't match any YAML placeholder → silently ignored\n\n---\n\n## 9. Running Your Project\n\n```bash\n# Install dependencies\ncrewai install\n\n# Run the flow\ncrewai run\n```\n\nOr run directly:\n\n```bash\ncd my_project\nuv run src/my_project/main.py\n```\n\n---\n\n## 10. Quick Diagnostic Checklist\n\n| Symptom | Likely Cause | Fix |\n|---|---|---|\n| `{topic}` appears literally in agent output | Missing `inputs=` in `kickoff()` | Pass `crew.kickoff(inputs={\"topic\": \"...\"})` |\n| `KeyError` on `self.agents_config['name']` | Method name doesn't match YAML key | Ensure `@agent def researcher` matches `researcher:` in YAML |\n| `ModuleNotFoundError` on import | Wrong path or hyphens in project name | Use underscores; check `from .crews.crew_name.crew_name import CrewClass` |\n| Crew runs but Flow state is empty | Not writing results back to `self.state` | Assign crew output to `self.state.field` in the `@listen` method |\n| `Process.SEQUENTIAL` raises `AttributeError` | Uppercase enum | Use lowercase: `Process.sequential` |\n| Agent ignores tools | Tools assigned to agent but task needs them | Move tools to task level or verify agent has the right tools |\n| Agent fabricates search results | No tools assigned — agent can't actually search | Add `tools=[SerperDevTool()]` or equivalent; an agent with no tools will hallucinate data |\n| `@listen` never fires | Listener string doesn't match router return value, or passed a string instead of method reference | `@router` must return the exact string `@listen(\"label\")` expects; for method chaining use `@listen(method_ref)` not `@listen(\"method_name\")` |\n| Flow step runs twice unexpectedly | Multiple `@start()` methods or `or_` listener | Use `and_()` if you need all upstream steps to complete first |\n| `AuthenticationError` or `API key not found` | Missing env var | Set `OPENAI_API_KEY` (and `SERPER_API_KEY` for search tools) in `.env` |\n| Agent retries endlessly on structured output | Pydantic model too complex for the LLM | Simplify the model, reduce nesting, or use a more capable `llm` |\n| Agent loops to `max_iter` without finishing | Task description too vague or conflicting with `expected_output` | Make `expected_output` specific and achievable; lower `max_iter` to fail faster |\n| Flow state not updating across steps | Using unstructured state without proper key access | Switch to structured Pydantic state or ensure dict keys are consistent |\n| `@router` return value ignored | Method not decorated with `@router` | Use `@router(condition)` not `@listen(condition)` for branching methods |\n| `Flow.kickoff(user_message=..., session_id=...)` fails | Conversational kwargs are not accepted by `kickoff()` | Use `flow.handle_turn(message, session_id=...)` for chat messages |\n| Chat history missing assistant replies | Handler returned text but did not record it on older/explicit paths | Call `self.append_assistant_message(reply)` inside route handlers |\n| Trace never exports for chat session | Deferred conversational trace was not finalized | Call `flow.finalize_session_traces()` in `finally`, or use `flow.chat()` |\n| Follow-up chat modeled with `@human_feedback` | Human feedback approves a step output, not the next user message | Use conversational `handle_turn()` for follow-up chat lines |\n\n---\n\n## References\n\nFor deeper dives into specific topics, see:\n\n- [Flow Routing, Persistence, Streaming & Human Feedback](references/flow-routing.md) — complete `@router`, `or_()`, `and_()`, `@persist`, streaming, and `@human_feedback` patterns\n- [Conversational Flows](references/conversational-flows.md) — experimental multi-turn Flow API with `handle_turn()`, `chat()`, `ConversationConfig`, router behavior, persistence, and tracing\n- [MCP Servers](references/mcp-servers.md) — prefer official MCP servers over native tools; setup, DSL integration, and known official servers\n- [Tools Catalog](references/tools-catalog.md) — all 80+ built-in tools with imports, env vars, and common combos (use as fallback when no MCP server exists)\n\nFor related skills:\n\n- **design-agent** — agent Role-Goal-Backstory framework, parameter tuning, tool assignment, memory & knowledge configuration\n- **design-task** — task description/expected_output best practices, guardrails, structured output, dependencies\n- **ask-docs** — query the live CrewAI documentation MCP server for questions not covered by these skills\n","contentSource":"https://raw.githubusercontent.com/crewaiinc/skills/main/skills/getting-started/SKILL.md","contentFetchedAt":"2026-07-27T09:00:57.876Z"},{"name":"design-agent","url":"https://skills.sh/crewaiinc/skills/design-agent","install":"npx skills add crewaiinc/skills --skill design-agent","sdk":"crewai","key":"crewai/design-agent","description":"CrewAI agent design and configuration. Use when creating, configuring, or debugging crewAI agents — choosing role/goal/backstory, selecting LLMs, assigning tools, tuning max_iter/max_rpm/max_execution_time, enabling planning/code execution/delegation, setting up knowledge sources, using guardrails, or configuring agents in YAML vs code.","hasContent":true,"content":"---\nname: design-agent\ndescription: \"CrewAI agent design and configuration. Use when creating, configuring, or debugging crewAI agents — choosing role/goal/backstory, selecting LLMs, assigning tools, tuning max_iter/max_rpm/max_execution_time, enabling planning/code execution/delegation, setting up knowledge sources, using guardrails, or configuring agents in YAML vs code.\"\n---\n\n# CrewAI Agent Design Guide\n\nHow to design effective agents with the right role, goal, backstory, tools, and configuration.\n\n---\n\n## The 80/20 Rule\n\n**Spend 80% of your effort on task design, 20% on agent design.** A well-designed task elevates even a simple agent. But even the best agent cannot rescue a vague, poorly scoped task. Get the task right first (see the `design-task` skill), then refine the agent.\n\n---\n\n## 0. How Many Agents Do You Actually Need?\n\n**Default to ONE agent.** Add more only when the task genuinely splits into work that requires:\n\n- **Different tools or permissions** — e.g. one agent has Slack write access, another reads docs only.\n- **Different personas the LLM must clearly switch between** — a writer's voice is not a researcher's voice.\n- **Different LLMs** — a cheap model for mechanical steps, a stronger one for synthesis.\n- **Different guardrails or output schemas** — separate agents make the contract per stage explicit.\n\n**DO NOT add an agent just because the workflow has multiple steps.** A single agent can:\n- Call multiple tools in sequence within one kickoff (search → scrape → summarize is one agent's loop).\n- Produce structured multi-section output in one response.\n- Iterate via its own tool-use loop without you orchestrating it as separate agents.\n\n**Cost calculus:** every extra agent = at least one more LLM kickoff plus a context handoff. Splitting linear, single-persona work into multiple agents multiplies token cost and adds fragility for marginal quality wins.\n\n### Anti-pattern: Sequential mechanical steps as separate agents\n\n❌ Three agents for what is one researcher's job:\n```python\nsource_finder = Agent(role=\"Finds URLs via Firecrawl search\", tools=[firecrawl_search])\nscraper       = Agent(role=\"Scrapes URLs via Firecrawl scrape\", tools=[firecrawl_scrape])\nwriter        = Agent(role=\"Writes the report\", ...)\n```\n\n✅ One researcher does the gathering loop; one writer synthesizes — two agents because the personas and LLMs genuinely differ:\n```python\nresearcher = Agent(role=\"Web Researcher\", tools=[firecrawl_search, firecrawl_scrape], llm=\"anthropic/claude-haiku-4-5\")\nwriter     = Agent(role=\"Technical Report Writer\",                                    llm=\"anthropic/claude-sonnet-4-6\")\n```\nThe researcher's task description tells it to search, then scrape, then return structured findings. One LLM loop, multiple tool calls.\n\n### Anti-pattern: \"Summarize then send\" as two agents\n\n❌ Two agents to read a string, summarize it, and post a Slack DM:\n```python\nsummarizer       = Agent(role=\"Summarizer\")\nslack_messenger  = Agent(role=\"Slack Sender\", apps=[\"slack\"])\n```\n\n✅ One agent with the connector and a task that tells it to summarize on top, then DM:\n```python\nslack_dm_agent = Agent(\n    role=\"Slack Reporter\",\n    goal=\"Post a Slack DM containing a one-paragraph summary plus the full markdown body.\",\n    apps=[\"slack\"],\n)\n# Task: \"Read the report below. Write a 2-3 sentence executive summary at the top.\n#        Post a DM to {recipient_email} with the summary followed by the full body.\"\n```\n\n### Heuristic\n\n> If two \"agents\" share the same persona, the same tool surface, and the same LLM, they are one agent with a longer task description.\n\n### Once you've decided \"one agent is enough\"\n\nUse `Agent.kickoff()` directly inside a Flow method — no `Crew`, no `Task` ceremony. The Flow owns sequencing and state; each step is a single agent kickoff. See **Section 4 — Agent.kickoff() — Direct Agent Execution** below for the full pattern, and the upstream docs at <https://docs.crewai.com/en/concepts/agents#direct-agent-interaction-with-kickoff>.\n\nQuick shape:\n\n```python\n@listen(previous_step)\ndef my_step(self):\n    agent = Agent(role=\"…\", goal=\"…\", backstory=\"…\", tools=[...])\n    result = agent.kickoff(\n        messages=f\"Use this prior step's output: {self.state.prior_field}\",\n        response_format=MyPydanticModel,  # optional\n    )\n    self.state.my_field = result.pydantic  # or result.raw\n```\n\nReach for `Crew.kickoff()` *only* when a step genuinely benefits from multi-agent collaboration (delegation, hierarchical management, parallel specialists feeding one synthesis). For \"one agent does one job\", `Agent.kickoff()` inside a Flow listener is the right primitive.\n\nOnly after you've decided multi-agent is justified, read on for how to design each one.\n\n---\n\n## 1. The Role-Goal-Backstory Framework\n\nEvery agent needs three things: **who** it is, **what** it wants, and **why** it's qualified.\n\n### Role — Who the Agent Is\n\nThe role defines the agent's area of expertise. **Be specific, not generic.**\n\n| Bad | Good |\n|---|---|\n| `Researcher` | `Senior Data Researcher specializing in {topic}` |\n| `Writer` | `Technical Blog Writer for developer audiences` |\n| `Analyst` | `Financial Risk Analyst with regulatory compliance expertise` |\n\nThe role directly shapes how the LLM reasons. A \"Senior Data Researcher\" will produce different output than a \"Research Assistant\" even with the same task.\n\n### Goal — What the Agent Wants\n\nThe goal is the agent's individual objective. It should be **outcome-focused with quality standards**.\n\n| Bad | Good |\n|---|---|\n| `Do research` | `Uncover cutting-edge developments in {topic} and identify the top 5 trends with supporting evidence` |\n| `Write content` | `Produce publication-ready technical articles that explain complex topics clearly for non-technical readers` |\n| `Analyze data` | `Deliver actionable risk assessments with confidence levels and recommended mitigations` |\n\n### Backstory — Why the Agent Is Qualified\n\nThe backstory establishes expertise, experience, values, and working style. It's the agent's \"personality prompt.\"\n\n```yaml\nbackstory: >\n  You're a seasoned researcher with 15 years of experience in AI/ML.\n  You're known for your ability to find obscure but relevant papers\n  and synthesize complex findings into clear, actionable insights.\n  You always cite your sources and flag uncertainty explicitly.\n```\n\n**What to include in a backstory:**\n- Years/depth of experience\n- Specific domain knowledge\n- Working style and values (e.g., \"always cites sources\", \"prefers concise output\")\n- Quality standards the agent holds itself to\n\n**What NOT to include:**\n- Implementation details (tools, models, config)\n- Task-specific instructions (those go in the task description)\n- Arbitrary personality traits that don't affect output quality\n\n---\n\n## 2. Agent Configuration Reference\n\n### Essential Parameters\n\n```python\nAgent(\n    role=\"...\",              # Required: agent's expertise area\n    goal=\"...\",              # Required: what the agent aims to achieve\n    backstory=\"...\",         # Required: context and personality\n    llm=\"openai/gpt-4o\",    # Optional: defaults to OPENAI_MODEL_NAME env var or \"gpt-4\"\n    tools=[...],             # Optional: list of tool instances\n)\n```\n\n### Execution Control\n\n```python\nAgent(\n    ...,\n    max_iter=25,             # Max reasoning iterations per task (default: 25)\n    max_execution_time=300,  # Timeout in seconds (default: None — no limit)\n    max_rpm=10,              # Rate limit: max API calls per minute (default: None)\n    max_retry_limit=2,       # Retries on error (default: 2)\n    verbose=True,            # Show detailed execution logs (default: False)\n)\n```\n\n**Tuning `max_iter`:**\n- Default 25 is generous — most tasks finish in 3-8 iterations\n- Lower to 10-15 to fail faster when tasks are well-defined\n- If agent consistently hits max_iter, the task is too vague (fix the task, not the limit)\n\n### Tool Configuration\n\n```python\nfrom crewai_tools import SerperDevTool, ScrapeWebsiteTool, FileReadTool\n\nAgent(\n    ...,\n    tools=[SerperDevTool(), ScrapeWebsiteTool()],  # Agent-level tools\n)\n```\n\n**Key rules:**\n- An agent with **no tools** will hallucinate data when asked to search, fetch, or read files — always provide tools for tasks that require external data\n- Prefer **fewer, focused tools** over many tools — too many tools confuses the agent\n- Tools can also be assigned at the **task level** for task-specific access (see `design-task` skill)\n- Agent-level tools are available for all tasks the agent performs; task-level tools override for that specific task\n\n### LLM Selection\n\n```python\nAgent(\n    ...,\n    llm=\"openai/gpt-4o\",              # Main reasoning model\n    function_calling_llm=\"openai/gpt-4o-mini\",  # Cheaper model for tool calls only\n)\n```\n\nUse `function_calling_llm` to save costs: the main `llm` handles reasoning while a cheaper model handles tool-calling mechanics.\n\n### Collaboration\n\n```python\nAgent(\n    ...,\n    allow_delegation=False,  # Default: False — agent works alone\n)\n```\n\nSet `allow_delegation=True` only when:\n- The agent is part of a crew with other specialized agents\n- The task genuinely benefits from the agent handing off subtasks\n- You're using hierarchical process where the manager delegates\n\n**Warning:** Delegation without clear task boundaries leads to infinite loops or wasted iterations.\n\n### Planning (Plan-and-Execute Mode)\n\nWhen a `PlanningConfig` is set on an agent, `Agent.kickoff()` (and `Agent.execute_task()`) routes through the new `crewai.experimental.AgentExecutor`. Instead of a single ReAct-style loop, the agent:\n\n1. **Generates a plan** — a list of `PlanStep`s, each with a description and optional `tool_to_use`. Stored as `state.todos`.\n2. **Executes each step** via a `StepExecutor` in an isolated multi-turn LLM loop (capped by `max_step_iterations`).\n3. **Observes the result** via a `PlannerObserver` after every step — did the step succeed? Is the remaining plan still valid?\n4. **Routes the next action** based on the agent's `reasoning_effort` setting (see below).\n\nThe presence of a `PlanningConfig` enables the mode. To disable: don't pass one, or set `planning=False`.\n\n```python\nfrom crewai import Agent\nfrom crewai.agent.planning_config import PlanningConfig\n\nagent = Agent(\n    role=\"…\",\n    goal=\"…\",\n    backstory=\"…\",\n    tools=[...],\n    planning_config=PlanningConfig(reasoning_effort=\"medium\"),  # most common\n)\n```\n\n#### `reasoning_effort` — pick one\n\n| Level | After each step the planner... | Pick when |\n|---|---|---|\n| `\"low\"` | observes (validates success), marks the todo complete, continues. **No replan, no refine.** | You want plan visibility (todos, observations) but trust the agent to follow it linearly. Fastest. |\n| `\"medium\"` (default) | observes; **replans on failure only**. Successful steps just continue. | The agent's tools can fail (network, exec, scrape) and you want graceful recovery without paying refinement cost on every success. **The right default for sandbox-coding, research, and other tool-heavy loops.** |\n| `\"high\"` | observes, then routes through `decide_next_action` which can trigger early goal achievement, full replan, or lightweight refinement after every step. | The task changes shape based on intermediate findings, or you need maximum adaptiveness. Most LLM calls per run. |\n\nSource: `crewai/experimental/agent_executor.py:450` (`observe_step_result` router) and `crewai/agent/planning_config.py`.\n\n#### Other `PlanningConfig` knobs\n\n```python\nPlanningConfig(\n    reasoning_effort=\"medium\",\n    max_steps=20,            # cap on planned steps (default 20)\n    max_replans=3,           # max full re-plans before finalizing (default 3)\n    max_attempts=None,       # planning refinement attempts during plan generation\n    max_step_iterations=15,  # max LLM turns per step's StepExecutor (default 15)\n    step_timeout=None,       # wall-clock seconds per step; None = no cap\n    system_prompt=None,      # custom planning system prompt (uses default if None)\n    plan_prompt=None,        # custom initial-plan prompt; placeholders: {description}, {expected_output}, {tools}, {max_steps}\n    refine_prompt=None,      # custom refinement prompt\n    llm=None,                # separate LLM for planning (else uses agent.llm)\n)\n```\n\nUse `llm=\"anthropic/claude-haiku-4-5\"` (cheap) for the planner while keeping `agent.llm=\"anthropic/claude-opus-4-7\"` (strong) for execution — common cost optimization.\n\n#### When to enable\n\n- **Enable** for autonomous loops where the agent picks its own steps and you want failure recovery (e.g. coding agent that writes → runs → patches; research agent that searches → scrapes → revises).\n- **Skip** for single-tool, single-purpose calls (e.g. \"summarize this string\", \"post this Slack DM\") — observation overhead doesn't pay off.\n\n#### Cost shape\n\nEvery step gets a `PlannerObserver` LLM call (~1 extra call per step). On `\"medium\"` a failed step adds a replan call. On `\"high\"` every step adds a `decide_next_action` call too. For an N-step plan, expect roughly:\n\n- `low`: N execution + N observation = **2N calls**\n- `medium`: 2N + (failures × 1 replan)\n- `high`: ~3N + replans/refines\n\nMaterial at scale — measure before defaulting `high` for everything.\n\n#### Custom `plan_prompt`\n\nIf you supply `plan_prompt`, include the placeholders the planner template expects: `{description}`, `{expected_output}`, `{tools}`, `{max_steps}`. The planner LLM gets these interpolated. Keep custom prompts focused on *project-specific* rules; let `description`/`tools` (auto-injected) carry the dynamic content.\n\n### Code Execution\n\n```python\nAgent(\n    ...,\n    allow_code_execution=True,        # Enable code execution (default: False)\n    code_execution_mode=\"safe\",       # \"safe\" (Docker) or \"unsafe\" (direct) — default: \"safe\"\n)\n```\n\n- `\"safe\"` requires Docker installed and running — executes in a container\n- `\"unsafe\"` runs code directly on the host — only use in controlled environments\n\n### Context Window Management\n\n```python\nAgent(\n    ...,\n    respect_context_window=True,      # Auto-summarize to stay within limits (default: True)\n)\n```\n\nWhen `True`, the agent automatically summarizes prior context if it approaches the LLM's token limit. When `False`, execution stops with an error on overflow.\n\n### Date Injection\n\n```python\nAgent(\n    ...,\n    inject_date=True,                 # Add current date to task context (default: False)\n    date_format=\"%Y-%m-%d\",           # Date format (default: \"%Y-%m-%d\")\n)\n```\n\nEnable for time-sensitive tasks (research, news analysis, scheduling).\n\n### Agent Guardrails\n\n```python\ndef validate_no_pii(result) -> tuple[bool, Any]:\n    \"\"\"Reject output containing PII.\"\"\"\n    if contains_pii(result.raw):\n        return (False, \"Output contains PII. Remove all personal information and try again.\")\n    return (True, result)\n\nAgent(\n    ...,\n    guardrail=validate_no_pii,\n    guardrail_max_retries=3,          # default: 3\n)\n```\n\nAgent guardrails validate every output the agent produces. The agent retries on failure up to `guardrail_max_retries`.\n\n### Knowledge Sources\n\n```python\nfrom crewai.knowledge.source.text_file_knowledge_source import TextFileKnowledgeSource\n\nAgent(\n    ...,\n    knowledge_sources=[\n        TextFileKnowledgeSource(file_paths=[\"company_handbook.txt\"]),\n    ],\n    embedder={\n        \"provider\": \"openai\",\n        \"config\": {\"model\": \"text-embedding-3-small\"},\n    },\n)\n```\n\nKnowledge sources give agents access to domain-specific data via RAG. Use when agents need to reference large documents, policies, or datasets.\n\n---\n\n## 3. YAML Configuration (Recommended)\n\nDefine agents in `agents.yaml` for clean separation of config and code:\n\n```yaml\nresearcher:\n  role: >\n    {topic} Senior Data Researcher\n  goal: >\n    Uncover cutting-edge developments in {topic}\n    with supporting evidence and source citations\n  backstory: >\n    You're a seasoned researcher with 15 years of experience.\n    Known for finding obscure but relevant sources and\n    synthesizing complex findings into clear insights.\n    You always cite your sources and flag uncertainty.\n  # Optional overrides (uncomment as needed):\n  # llm: openai/gpt-4o\n  # max_iter: 15\n  # max_rpm: 10\n  # allow_delegation: false\n  # verbose: true\n```\n\nThen wire in `crew.py`:\n\n```python\n@CrewBase\nclass MyCrew:\n    agents_config = \"config/agents.yaml\"\n    tasks_config = \"config/tasks.yaml\"\n\n    @agent\n    def researcher(self) -> Agent:\n        return Agent(\n            config=self.agents_config[\"researcher\"],\n            tools=[SerperDevTool()],\n        )\n```\n\n**Critical:** The method name (`def researcher`) must match the YAML key (`researcher:`). Mismatch causes `KeyError`.\n\n---\n\n## 4. Agent.kickoff() — Direct Agent Execution\n\nUse `Agent.kickoff()` when you need one agent with tools and reasoning, without crew overhead. This is the most common pattern in Flows.\n\n### Basic Usage\n\n```python\nfrom crewai import Agent\nfrom crewai_tools import SerperDevTool\n\nresearcher = Agent(\n    role=\"Senior Research Analyst\",\n    goal=\"Find comprehensive, factual information with source citations\",\n    backstory=\"Expert researcher known for thorough, evidence-based analysis.\",\n    tools=[SerperDevTool()],\n    llm=\"openai/gpt-4o\",\n)\n\n# Pass a string prompt — the agent reasons, uses tools, and returns a result\nresult = researcher.kickoff(\"What are the latest developments in quantum computing?\")\nprint(result.raw)             # str — the agent's full response\nprint(result.usage_metrics)   # token usage stats\n```\n\n### With Structured Output\n\n```python\nfrom pydantic import BaseModel\n\nclass ResearchFindings(BaseModel):\n    key_trends: list[str]\n    sources: list[str]\n    confidence: float\n\nresult = researcher.kickoff(\n    \"Research the latest AI agent frameworks\",\n    response_format=ResearchFindings,\n)\n\n# Access via .pydantic (NOT directly — Agent.kickoff wraps the result)\nprint(result.pydantic.key_trends)    # list[str]\nprint(result.pydantic.confidence)    # float\nprint(result.raw)                    # raw string version\n```\n\n> **Note:** `Agent.kickoff()` returns `LiteAgentOutput` — access structured output via `result.pydantic`. This differs from `LLM.call()` which returns the Pydantic object directly.\n\n### With File Inputs\n\n```python\nresult = researcher.kickoff(\n    \"Analyze this document and summarize the key findings\",\n    input_files={\"document\": FileInput(path=\"report.pdf\")},\n)\n```\n\n### Async Variant\n\n```python\nresult = await researcher.kickoff_async(\n    \"Research quantum computing breakthroughs\",\n    response_format=ResearchFindings,\n)\n```\n\n### Agent.kickoff() in Flows (Recommended Pattern)\n\nThe most powerful pattern is orchestrating multiple `Agent.kickoff()` calls inside a Flow. The Flow handles state and sequencing; each agent handles its specific step:\n\n```python\nfrom crewai import Agent\nfrom crewai.flow.flow import Flow, listen, start\nfrom crewai_tools import SerperDevTool, ScrapeWebsiteTool\nfrom pydantic import BaseModel\n\nclass ResearchState(BaseModel):\n    topic: str = \"\"\n    research: str = \"\"\n    analysis: str = \"\"\n    report: str = \"\"\n\nclass ResearchFlow(Flow[ResearchState]):\n\n    @start()\n    def gather_data(self):\n        researcher = Agent(\n            role=\"Senior Researcher\",\n            goal=\"Find comprehensive data with sources\",\n            backstory=\"Expert at finding and validating information.\",\n            tools=[SerperDevTool(), ScrapeWebsiteTool()],\n        )\n        result = researcher.kickoff(f\"Research: {self.state.topic}\")\n        self.state.research = result.raw\n\n    @listen(gather_data)\n    def analyze(self):\n        analyst = Agent(\n            role=\"Data Analyst\",\n            goal=\"Extract actionable insights from raw research\",\n            backstory=\"Skilled at pattern recognition and synthesis.\",\n        )\n        result = analyst.kickoff(\n            f\"Analyze this research and extract key insights:\\n\\n{self.state.research}\"\n        )\n        self.state.analysis = result.raw\n\n    @listen(analyze)\n    def write_report(self):\n        writer = Agent(\n            role=\"Report Writer\",\n            goal=\"Create clear, well-structured reports\",\n            backstory=\"Technical writer who makes complex topics accessible.\",\n        )\n        result = writer.kickoff(\n            f\"Write a comprehensive report from this analysis:\\n\\n{self.state.analysis}\"\n        )\n        self.state.report = result.raw\n\nflow = ResearchFlow()\nflow.kickoff(inputs={\"topic\": \"AI agents\"})\nprint(flow.state.report)\n```\n\n**When to use Agent.kickoff() vs Crew.kickoff():**\n- Use `Agent.kickoff()` when each step is a distinct agent and the Flow controls sequencing\n- Use `Crew.kickoff()` when multiple agents need to collaborate on related tasks within a single step\n\n### Agent.kickoff() in Conversational Flow Routes\n\nIn experimental conversational Flows, the Flow owns the chat lifecycle and route selection. Agents should be called inside route handlers for bounded tool-backed work: research, docs lookup, account actions, triage, drafting, or escalation prep.\n\n```python\nfrom crewai import Agent, Flow\nfrom crewai.flow import listen\nfrom crewai.experimental.conversational import ConversationState\n\n\nclass SupportFlow(Flow[ConversationState]):\n    conversational = True\n\n    def research_agent(self) -> Agent:\n        return Agent(\n            role=\"Support Research Specialist\",\n            goal=\"Find accurate information with sources for the user's current question.\",\n            backstory=\"You are precise, evidence-driven, and explicit about uncertainty.\",\n            tools=[...],\n        )\n\n    @listen(\"RESEARCH\")\n    def handle_research(self) -> str:\n        \"\"\"Fresh research, current lookups, and source-backed synthesis.\"\"\"\n        result = self.research_agent().kickoff(self.state.current_user_message)\n        self.append_agent_result(\"research_agent\", result, visibility=\"private\")\n        reply = result.raw\n        self.append_assistant_message(reply)\n        return reply\n```\n\nDesign implications:\n- Keep the conversational `Flow` responsible for session id, message history, routing, trace finalization, and approvals.\n- Keep each agent narrow: one route, one tool surface, one job.\n- Use `append_agent_result(..., visibility=\"private\")` for scratch work that should not enter canonical chat history.\n- Use `append_assistant_message(reply)` for the user-visible answer so the next turn has the assistant context.\n- Do not make a \"chat agent\" with every tool. Route first, then invoke a focused agent for the selected route.\n\nSee the getting-started reference for the Flow lifecycle: `skills/getting-started/references/conversational-flows.md`.\n\n---\n\n## 5. Specialist vs Generalist Agents\n\n> **Note:** Apply this section *after* you've decided you genuinely need multiple agents (see Section 0). If you only need one agent, \"specialist vs generalist\" is not the question — the question is just how to design that one agent.\n\n**When you do need multiple agents, prefer specialists.** An agent that does one thing well outperforms one that does many things acceptably.\n\n### When to Use a Specialist\n\n- Task requires deep domain knowledge\n- Output quality matters more than speed\n- The task is complex enough to benefit from focused expertise\n\n### When a Generalist Is Acceptable\n\n- Simple tasks with clear instructions\n- Prototyping where you'll specialize later\n- Tasks that truly span multiple domains equally\n\n### Specialist Design Pattern\n\nInstead of one \"Content Writer\" agent, create:\n- `technical_writer` — deep technical accuracy, code examples\n- `copywriter` — persuasive, audience-focused marketing copy\n- `editor` — grammar, consistency, style guide enforcement\n\nEach specialist has a narrow role, specific goal, and backstory that reinforces their expertise.\n\n---\n\n## 6. Agent Interaction Patterns\n\n### Sequential (Default)\n\nAgents work one after another. Each agent receives prior agents' outputs as context.\n\n```\nResearcher → Writer → Editor\n```\n\nBest for: linear pipelines where each step builds on the last.\n\n### Hierarchical\n\nA manager agent delegates and validates. Task assignment is dynamic.\n\n```python\nCrew(\n    agents=[researcher, writer, editor],\n    tasks=[research_task, writing_task, editing_task],\n    process=Process.hierarchical,\n    manager_llm=\"openai/gpt-4o\",\n)\n```\n\nBest for: complex workflows where task assignment depends on intermediate results.\n\n### Agent-to-Agent Delegation\n\nWhen `allow_delegation=True`, an agent can ask another crew agent for help:\n\n```python\nlead_researcher = Agent(\n    role=\"Lead Researcher\",\n    goal=\"Coordinate research efforts\",\n    backstory=\"...\",\n    allow_delegation=True,  # Can delegate to other agents in the crew\n)\n```\n\nThe agent will automatically discover other crew members and delegate subtasks as needed.\n\n---\n\n## 7. Common Agent Design Mistakes\n\n| Mistake | Impact | Fix |\n|---|---|---|\n| Generic role like \"Assistant\" | Agent produces unfocused, shallow output | Use specific expertise: \"Senior Financial Analyst\" |\n| No tools for data-gathering tasks | Agent hallucinates data instead of searching | Always add tools when the task requires external info |\n| Too many tools (10+) | Agent gets confused choosing between tools | Limit to 3-5 relevant tools per agent |\n| Backstory full of task instructions | Agent mixes personality with task execution | Keep backstory about WHO the agent is; task details go in the task |\n| `allow_delegation=True` by default | Agents waste iterations delegating trivially | Only enable when delegation genuinely helps |\n| max_iter too high for simple tasks | Agent loops unnecessarily on vague tasks | Lower max_iter; fix the task description instead |\n| No guardrail on critical output | Bad output passes through unchecked | Add guardrails for outputs that feed into production systems |\n| Using expensive LLM for tool calls | Unnecessary cost for mechanical operations | Set `function_calling_llm` to a cheaper model |\n\n---\n\n## 8. Agent Design Checklist\n\nBefore deploying an agent, verify:\n\n- [ ] **Role** is specific and domain-focused (not \"Assistant\" or \"Helper\")\n- [ ] **Goal** includes desired outcome AND quality standards\n- [ ] **Backstory** establishes expertise and working style\n- [ ] **Tools** are assigned for any task requiring external data\n- [ ] **No excess tools** — 3-5 per agent maximum\n- [ ] **max_iter** is tuned for expected task complexity (10-15 for simple, 20-25 for complex)\n- [ ] **max_execution_time** is set for production agents to prevent hangs\n- [ ] **Guardrails** are configured for critical outputs\n- [ ] **LLM** is appropriate for task complexity (don't use GPT-4 for classification)\n- [ ] **Delegation** is disabled unless genuinely needed\n\n---\n\n## References\n\nFor deeper dives into specific topics, see:\n\n- [Custom Tools](references/custom-tools.md) — building your own tools with `@tool` decorator and `BaseTool` subclass\n- [Memory & Knowledge](references/memory-and-knowledge.md) — memory configuration, knowledge sources, embedder setup, scoping\n\nFor related skills:\n\n- **getting-started** — project scaffolding, choosing the right abstraction, Flow architecture\n- **design-task** — task description/expected_output best practices, guardrails, structured output, dependencies\n- **ask-docs** — query the live CrewAI documentation MCP server for questions not covered by these skills\n","contentSource":"https://raw.githubusercontent.com/crewaiinc/skills/main/skills/design-agent/SKILL.md","contentFetchedAt":"2026-07-27T09:00:57.983Z"},{"name":"ask-docs","url":"https://skills.sh/crewaiinc/skills/ask-docs","install":"npx skills add crewaiinc/skills --skill ask-docs","sdk":"crewai","key":"crewai/ask-docs","description":"Query the official CrewAI documentation for answers. Use when the user has a CrewAI question that isn't fully covered by the getting-started, design-agent, design-task skills — e.g., specific API details, configuration options, advanced features, troubleshooting errors, enterprise features, tool references, or anything where the latest docs are the best source of truth.","hasContent":true,"content":"---\nname: ask-docs\ndescription: \"Query the official CrewAI documentation for answers. Use when the user has a CrewAI question that isn't fully covered by the getting-started, design-agent, design-task skills — e.g., specific API details, configuration options, advanced features, troubleshooting errors, enterprise features, tool references, or anything where the latest docs are the best source of truth.\"\n---\n\n# Ask CrewAI Docs\n\nAnswer CrewAI questions by looking up the official documentation at `docs.crewai.com`.\n\n---\n\n## When to Use This Skill\n\nUse this skill when:\n\n- The user asks about a CrewAI feature, parameter, or behavior not covered in detail by the other skills\n- You need to verify current API syntax, method signatures, or configuration options\n- The user hits an error and needs troubleshooting guidance from official docs\n- The question is about a newer or less common CrewAI feature (e.g., telemetry, testing, CLI commands, deployment, enterprise features)\n- The question is about experimental conversational Flows and you need the current `handle_turn()`, `ConversationConfig`, `RouterConfig`, tracing, or streaming behavior\n- You're unsure whether your knowledge is current — the docs reflect the latest published state\n\n**Do NOT use this skill** when the question is clearly answered by one of the other skills (getting-started, design-agent, design-task). Those skills contain curated, opinionated guidance. This skill is for filling gaps and verifying details.\n\n---\n\n## How to Query the Docs\n\n### Step 1: Fetch the docs index\n\nThe CrewAI docs site publishes an `llms.txt` file — a structured index of every documentation page with descriptions. Fetch it first to find the right page:\n\n```\nWebFetch: https://docs.crewai.com/llms.txt\n```\n\nThis returns a categorized list of all doc pages in the format:\n\n```\n- [Page Title](https://docs.crewai.com/path/to/page): \"Description of what the page covers\"\n```\n\nCategories include:\n- **API Reference** — REST endpoints (kickoff, status, resume, inputs)\n- **Concepts** — agents, crews, tasks, tools, flows, memory, knowledge, LLMs, processes, training, testing\n- **Enterprise** — RBAC, SSO, automations, traces, deployment, triggers, integrations\n- **Tools Library** — 40+ tools organized by category (AI/ML, automation, cloud, database, files, search, web scraping)\n- **MCP Integration** — MCP server setup, transports, DSL, security\n- **Examples & Cookbooks** — practical implementations\n- **Learning Paths** — tutorials and advanced topics\n- **Observability** — monitoring integrations\n\nFor conversational Flow questions, go directly to:\n\n```\nWebFetch: https://docs.crewai.com/en/guides/flows/conversational-flows\n```\n\nTreat this page as the source of truth for the experimental `crewai.experimental.conversational` surface. Verify it before answering detailed API questions because the feature may change before it graduates.\n\n### Step 2: Fetch the relevant page\n\nOnce you identify the right page from the index, fetch its content:\n\n```\nWebFetch: https://docs.crewai.com/<path-from-index>\n```\n\n### Step 3: Synthesize and cite\n\nCombine what you find from the docs with context from the other skills to give a clear, actionable response. Always include the docs URL so the user can read further.\n\n---\n\n## Workflow Summary\n\n1. **Understand the user's question** — what specific CrewAI concept, API, or behavior are they asking about?\n2. **Fetch `llms.txt`** — scan the index to find the most relevant page(s)\n3. **Fetch the page(s)** — retrieve the actual documentation content\n4. **Synthesize the answer** — combine docs content with context from other skills\n5. **Cite the source** — include the docs URL in your response\n\n---\n\n## For an Even Better Experience\n\nUsers who frequently query CrewAI docs can configure the CrewAI docs MCP server in their coding agent for richer, structured search:\n\n```\nhttps://docs.crewai.com/mcp\n```\n\nThis is optional — the `llms.txt` workflow above works without any setup.\n\n---\n\n## Examples of Good Use Cases\n\n| User Question | Why This Skill |\n|---|---|\n| \"What parameters does `Crew()` accept?\" | Specific API reference — docs are authoritative |\n| \"How do I set up telemetry in CrewAI?\" | Niche feature not covered in other skills |\n| \"What's the difference between `Process.sequential` and `Process.hierarchical`?\" | Detailed comparison best sourced from docs |\n| \"I'm getting `ValidationError` when using `output_pydantic`\" | Troubleshooting — docs may have known issues or caveats |\n| \"How do I deploy a CrewAI flow to production?\" | Deployment guidance lives in docs, not in design skills |\n| \"What CLI commands does `crewai` support?\" | CLI reference is a docs concern |\n| \"How do I configure memory for a crew?\" | Detailed config options beyond what design-agent covers |\n| \"What tools are available for web scraping?\" | Tools library reference |\n| \"How do I set up SSO for CrewAI enterprise?\" | Enterprise features live in docs |\n| \"How do I build a chat app with Flow.handle_turn()?\" | Experimental conversational Flow API; verify the latest guide |\n\n---\n\n## Related Skills\n\n- **getting-started** — project scaffolding, choosing abstractions, Flow architecture\n- **design-agent** — agent Role-Goal-Backstory, parameter tuning, tools, memory & knowledge\n- **design-task** — task descriptions, expected_output, guardrails, structured output, dependencies\n","contentSource":"https://raw.githubusercontent.com/crewaiinc/skills/main/skills/ask-docs/SKILL.md","contentFetchedAt":"2026-07-27T09:00:58.046Z"}],"official":true,"generatedAt":"2026-07-27T09:02:29.956Z"}