# CrewAI Documentation Source: https://docs.crewai.com/index Build collaborative AI agents, crews, and flows — production ready from day one.
CrewAI

Ship multi‑agent systems with confidence

Design agents, orchestrate crews, and automate flows with guardrails, memory, knowledge, and observability baked in.

Get started Coding-agent guide API Reference
## Get started Overview of CrewAI concepts, architecture, and what you can build with agents, crews, and flows. Install via `uv`, configure API keys, and set up the CLI for local development. Spin up your first crew in minutes. Learn the core runtime, project layout, and dev loop. ## Build the basics Compose agents with tools, memory, knowledge, and structured outputs using Pydantic. Includes templates and best practices. Orchestrate start/listen/router steps, manage state, persist execution, and resume long-running workflows. Define sequential, hierarchical, or hybrid processes with guardrails, callbacks, and human-in-the-loop triggers. ## Enterprise journey Manage environments, redeploy safely, and monitor live runs directly from the Enterprise console. Connect Gmail, Slack, Salesforce, and more. Pass trigger payloads into crews and flows automatically. Invite teammates, configure RBAC, and control access to production automations. ## What’s new Unified overview for Gmail, Drive, Outlook, Teams, OneDrive, HubSpot, and more — now with sample payloads and crews. Call existing CrewAI automations or Amazon Bedrock Agents directly from your crews using the updated integration toolkit. Browse the examples and cookbooks for end-to-end reference implementations across agents, flows, and enterprise automations. ## Stay connected If CrewAI helps you ship faster, give us a star and share your builds with the community. Ask questions, showcase workflows, and request features alongside other builders. # CrewAI Documentation Source: https://docs.crewai.com/index Build collaborative AI agents, crews, and flows — production ready from day one.
CrewAI

Ship multi‑agent systems with confidence

Design agents, orchestrate crews, and automate flows with guardrails, memory, knowledge, and observability baked in.

Get started Coding-agent guide API Reference
## Get started Overview of CrewAI concepts, architecture, and what you can build with agents, crews, and flows. Install via `uv`, configure API keys, and set up the CLI for local development. Spin up your first crew in minutes. Learn the core runtime, project layout, and dev loop. ## Build the basics Compose agents with tools, memory, knowledge, and structured outputs using Pydantic. Includes templates and best practices. Orchestrate start/listen/router steps, manage state, persist execution, and resume long-running workflows. Define sequential, hierarchical, or hybrid processes with guardrails, callbacks, and human-in-the-loop triggers. ## Enterprise journey Manage environments, redeploy safely, and monitor live runs directly from the Enterprise console. Connect Gmail, Slack, Salesforce, and more. Pass trigger payloads into crews and flows automatically. Invite teammates, configure RBAC, and control access to production automations. ## What’s new Unified overview for Gmail, Drive, Outlook, Teams, OneDrive, HubSpot, and more — now with sample payloads and crews. Call existing CrewAI automations or Amazon Bedrock Agents directly from your crews using the updated integration toolkit. Browse the examples and cookbooks for end-to-end reference implementations across agents, flows, and enterprise automations. ## Stay connected If CrewAI helps you ship faster, give us a star and share your builds with the community. Ask questions, showcase workflows, and request features alongside other builders. # Agent Capabilities Source: https://docs.crewai.com/v1.15.16/en/concepts/agent-capabilities Understand the five ways to extend CrewAI agents: Tools, MCPs, Apps, Skills, and Knowledge. ## Overview CrewAI agents can be extended with **five distinct capability types**, each serving a different purpose. Understanding when to use each one — and how they work together — is key to building effective agents. **Callable functions** — give agents the ability to take action. Web searches, file operations, API calls, code execution. **Remote tool servers** — connect agents to external tool servers via the Model Context Protocol. Same effect as tools, but hosted externally. **Platform integrations** — connect agents to SaaS apps (Gmail, Slack, Jira, Salesforce) via CrewAI's platform. Runs locally with a platform integration token. **Domain expertise** — inject instructions, guidelines, and reference material into agent prompts. Skills tell agents *how to think*. **Retrieved facts** — provide agents with data from documents, files, and URLs via semantic search (RAG). Knowledge gives agents *what to know*. *** ## The Key Distinction The most important thing to understand: **these capabilities fall into two categories**. ### Action Capabilities (Tools, MCPs, Apps) These give agents the ability to **do things** — call APIs, read files, search the web, send emails. At execution time, all three resolve into the same internal format (`BaseTool` instances) and appear in a unified tool list the agent can call. ```python theme={null} from crewai import Agent from crewai_tools import SerperDevTool, FileReadTool agent = Agent( role="Researcher", goal="Find and compile market data", backstory="Expert market analyst", tools=[SerperDevTool(), FileReadTool()], # Local tools mcps=["https://mcp.example.com/sse"], # Remote MCP server tools apps=["gmail", "google_sheets"], # Platform integrations ) ``` ### Context Capabilities (Skills, Knowledge) These modify the agent's **prompt** — injecting expertise, instructions, or retrieved data before the agent starts reasoning. They don't give agents new actions; they shape how agents think and what information they have access to. ```python theme={null} from crewai import Agent agent = Agent( role="Security Auditor", goal="Audit cloud infrastructure for vulnerabilities", backstory="Expert in cloud security with 10 years of experience", skills=["./skills/security-audit"], # Domain instructions knowledge_sources=[pdf_source, url_source], # Retrieved facts ) ``` *** ## When to Use What | You need... | Use | Example | | :--------------------------------------------------- | :----------------- | :------------------------------------- | | Agent to search the web | **Tools** | `tools=[SerperDevTool()]` | | Agent to call a remote API via MCP | **MCPs** | `mcps=["https://api.example.com/sse"]` | | Agent to send emails via Gmail | **Apps** | `apps=["gmail"]` | | Agent to follow specific procedures | **Skills** | `skills=["./skills/code-review"]` | | Agent to reference company docs | **Knowledge** | `knowledge_sources=[pdf_source]` | | Agent to search the web AND follow review guidelines | **Tools + Skills** | Use both together | *** ## Combining Capabilities In practice, agents often use **multiple capability types together**. Here's a realistic example: ```python theme={null} from crewai import Agent from crewai_tools import SerperDevTool, FileReadTool, CodeInterpreterTool # A fully-equipped research agent researcher = Agent( role="Senior Research Analyst", goal="Produce comprehensive market analysis reports", backstory="Expert analyst with deep industry knowledge", # ACTION: What the agent can DO tools=[ SerperDevTool(), # Search the web FileReadTool(), # Read local files CodeInterpreterTool(), # Run Python code for analysis ], mcps=["https://data-api.example.com/sse"], # Access remote data API apps=["google_sheets"], # Write to Google Sheets # CONTEXT: What the agent KNOWS skills=["./skills/research-methodology"], # How to conduct research knowledge_sources=[company_docs], # Company-specific data ) ``` *** ## Comparison Table | Feature | Tools | MCPs | Apps | Skills | Knowledge | | :---------------------- | :--------: | :---------: | :----------------: | :-----------: | :--------------------: | | **Gives agent actions** | ✅ | ✅ | ✅ | ❌ | ❌ | | **Modifies prompt** | ❌ | ❌ | ❌ | ✅ | ✅ | | **Requires code** | Yes | Config only | Config only | Markdown only | Config only | | **Runs locally** | Yes | Depends | Yes (with env var) | N/A | Yes | | **Needs API keys** | Per tool | Per server | Integration token | No | Embedder only | | **Set on Agent** | `tools=[]` | `mcps=[]` | `apps=[]` | `skills=[]` | `knowledge_sources=[]` | | **Set on Crew** | ❌ | ❌ | ❌ | `skills=[]` | `knowledge_sources=[]` | *** ## Deep Dives Ready to learn more about each capability type? Create custom tools, use the 75+ OSS catalog, configure caching and async execution. Connect to MCP servers via stdio, SSE, or HTTP. Filter tools, configure auth. Build skill packages with SKILL.md, inject domain expertise, use progressive disclosure. Add knowledge from PDFs, CSVs, URLs, and more. Configure embedders and retrieval. # Agents Source: https://docs.crewai.com/v1.15.16/en/concepts/agents Detailed guide on creating and managing agents within the CrewAI framework. ## Overview of an Agent In the CrewAI framework, an `Agent` is an autonomous unit that can: * Perform specific tasks * Make decisions based on its role and goal * Use tools to accomplish objectives * Communicate and collaborate with other agents * Maintain memory of interactions * Delegate tasks when allowed Think of an agent as a specialized team member with specific skills, expertise, and responsibilities. For example, a `Researcher` agent might excel at gathering and analyzing information, while a `Writer` agent might be better at creating content. CrewAI AMP includes a Visual Agent Builder that simplifies agent creation and configuration without writing code. Design your agents visually and test them in real-time. Visual Agent Builder Screenshot The Visual Agent Builder enables: * Intuitive agent configuration with form-based interfaces * Real-time testing and validation * Template library with pre-configured agent types * Easy customization of agent attributes and behaviors ## Agent Attributes | Attribute | Parameter | Type | Description | | :-------------------------------------- | :----------------------- | :------------------------------------ | :------------------------------------------------------------------------------------------------------- | | **Role** | `role` | `str` | Defines the agent's function and expertise within the crew. | | **Goal** | `goal` | `str` | The individual objective that guides the agent's decision-making. | | **Backstory** | `backstory` | `str` | Provides context and personality to the agent, enriching interactions. | | **LLM** *(optional)* | `llm` | `Union[str, LLM, Any]` | Language model that powers the agent. Defaults to the model specified in `OPENAI_MODEL_NAME` or "gpt-4". | | **Tools** *(optional)* | `tools` | `List[BaseTool]` | Capabilities or functions available to the agent. Defaults to an empty list. | | **Function Calling LLM** *(optional)* | `function_calling_llm` | `Optional[Any]` | Language model for tool calling, overrides crew's LLM if specified. | | **Max Iterations** *(optional)* | `max_iter` | `int` | Maximum iterations before the agent must provide its best answer. Default is 20. | | **Max RPM** *(optional)* | `max_rpm` | `Optional[int]` | Maximum requests per minute to avoid rate limits. | | **Max Execution Time** *(optional)* | `max_execution_time` | `Optional[int]` | Maximum time (in seconds) for task execution. | | **Verbose** *(optional)* | `verbose` | `bool` | Enable detailed execution logs for debugging. Default is False. | | **Allow Delegation** *(optional)* | `allow_delegation` | `bool` | Allow the agent to delegate tasks to other agents. Default is False. | | **Step Callback** *(optional)* | `step_callback` | `Optional[Any]` | Function called after each agent step, overrides crew callback. | | **Cache** *(optional)* | `cache` | `bool` | Enable caching for tool usage. Default is True. | | **System Template** *(optional)* | `system_template` | `Optional[str]` | Custom system prompt template for the agent. | | **Prompt Template** *(optional)* | `prompt_template` | `Optional[str]` | Custom prompt template for the agent. | | **Response Template** *(optional)* | `response_template` | `Optional[str]` | Custom response template for the agent. | | **Allow Code Execution** *(optional)* | `allow_code_execution` | `Optional[bool]` | Enable code execution for the agent. Default is False. | | **Max Retry Limit** *(optional)* | `max_retry_limit` | `int` | Maximum number of retries when an error occurs. Default is 2. | | **Respect Context Window** *(optional)* | `respect_context_window` | `bool` | Keep messages under context window size by summarizing. Default is True. | | **Code Execution Mode** *(optional)* | `code_execution_mode` | `Literal["safe", "unsafe"]` | Mode for code execution: 'safe' (using Docker) or 'unsafe' (direct). Default is 'safe'. | | **Multimodal** *(optional)* | `multimodal` | `bool` | Whether the agent supports multimodal capabilities. Default is False. | | **Inject Date** *(optional)* | `inject_date` | `bool` | Whether to automatically inject the current date into the agent's prompt. Default is False. | | **Date Format** *(optional)* | `date_format` | `str` | Format string for date when inject\_date is enabled. Default is "%Y-%m-%d" (ISO format). | | **Reasoning** *(optional)* | `reasoning` | `bool` | Whether the agent should reflect and create a plan before executing a task. Default is False. | | **Max Reasoning Attempts** *(optional)* | `max_reasoning_attempts` | `Optional[int]` | Maximum number of reasoning attempts before executing the task. If None, will try until ready. | | **Embedder** *(optional)* | `embedder` | `Optional[Dict[str, Any]]` | Configuration for the embedder used by the agent. | | **Knowledge Sources** *(optional)* | `knowledge_sources` | `Optional[List[BaseKnowledgeSource]]` | Knowledge sources available to the agent. | | **Use System Prompt** *(optional)* | `use_system_prompt` | `Optional[bool]` | Whether to use system prompt (for o1 model support). Default is True. | ## Creating Agents There are two common ways to create agents in CrewAI: using **JSONC project configuration (recommended for new crews)** or defining them **directly in code**. ### JSONC Configuration (Recommended) New projects created with `crewai create crew ` use JSON-first configuration. Each agent is defined in `agents/.jsonc`, and `crew.jsonc` lists which agents are part of the crew. After creating your CrewAI project as outlined in the [Installation](/en/installation) section, edit the generated files in `agents/`. Use `{placeholder}` values in `role`, `goal`, or `backstory`. Put defaults in `crew.jsonc` under `inputs`; `crewai run` prompts for any missing values. Here's an example `agents/researcher.jsonc` file: ```jsonc agents/researcher.jsonc theme={null} { "role": "{topic} Senior Data Researcher", "goal": "Uncover cutting-edge developments in {topic}", "backstory": "You find the most relevant information and present it clearly.", "llm": "openai/gpt-4o", "tools": ["SerperDevTool"], "settings": { "verbose": true, "allow_delegation": false, "max_iter": 20 } } ``` Then include that agent from `crew.jsonc`: ```jsonc crew.jsonc theme={null} { "name": "Research Crew", "agents": ["researcher"], "tasks": [ { "name": "research_task", "description": "Research {topic}", "expected_output": "A concise briefing about {topic}", "agent": "researcher" } ], "inputs": { "topic": "AI Agents" } } ``` Agent files support any public `Agent` field. Common fields include `role`, `goal`, `backstory`, `llm`, `tools`, `function_calling_llm`, `guardrail`, `step_callback`, and `settings`. Behavior options such as `verbose`, `allow_delegation`, `max_iter`, `max_rpm`, `memory`, `cache`, `planning_config`, and `use_system_prompt` can be placed at the top level or under `settings`; values in `settings` take precedence. JSONC supports comments and trailing commas. If both `agents/.jsonc` and `agents/.json` exist, CrewAI uses the JSONC file. ### Classic YAML Configuration Classic projects created with `crewai create crew --classic` use `config/agents.yaml` and a `@CrewBase` class in `crew.py`. This remains supported for teams that want Python decorators or existing YAML projects. ### Direct Code Definition You can create agents directly in code by instantiating the `Agent` class. Here's a comprehensive example showing all available parameters: ```python Code theme={null} from crewai import Agent from crewai_tools import SerperDevTool # Create an agent with all available parameters agent = Agent( role="Senior Data Scientist", goal="Analyze and interpret complex datasets to provide actionable insights", backstory="With over 10 years of experience in data science and machine learning, " "you excel at finding patterns in complex datasets.", llm="gpt-4", # Default: OPENAI_MODEL_NAME or "gpt-4" function_calling_llm=None, # Optional: Separate LLM for tool calling verbose=False, # Default: False allow_delegation=False, # Default: False max_iter=20, # Default: 20 iterations max_rpm=None, # Optional: Rate limit for API calls max_execution_time=None, # Optional: Maximum execution time in seconds max_retry_limit=2, # Default: 2 retries on error allow_code_execution=False, # Default: False code_execution_mode="safe", # Default: "safe" (options: "safe", "unsafe") respect_context_window=True, # Default: True use_system_prompt=True, # Default: True multimodal=False, # Default: False inject_date=False, # Default: False date_format="%Y-%m-%d", # Default: ISO format reasoning=False, # Default: False max_reasoning_attempts=None, # Default: None tools=[SerperDevTool()], # Optional: List of tools knowledge_sources=None, # Optional: List of knowledge sources embedder=None, # Optional: Custom embedder configuration system_template=None, # Optional: Custom system prompt template prompt_template=None, # Optional: Custom prompt template response_template=None, # Optional: Custom response template step_callback=None, # Optional: Callback function for monitoring ) ``` Let's break down some key parameter combinations for common use cases: #### Basic Research Agent ```python Code theme={null} research_agent = Agent( role="Research Analyst", goal="Find and summarize information about specific topics", backstory="You are an experienced researcher with attention to detail", tools=[SerperDevTool()], verbose=True # Enable logging for debugging ) ``` #### Code Development Agent ```python Code theme={null} dev_agent = Agent( role="Senior Python Developer", goal="Write and debug Python code", backstory="Expert Python developer with 10 years of experience", allow_code_execution=True, code_execution_mode="safe", # Uses Docker for safety max_execution_time=300, # 5-minute timeout max_retry_limit=3 # More retries for complex code tasks ) ``` #### Long-Running Analysis Agent ```python Code theme={null} analysis_agent = Agent( role="Data Analyst", goal="Perform deep analysis of large datasets", backstory="Specialized in big data analysis and pattern recognition", memory=True, respect_context_window=True, max_rpm=10, # Limit API calls function_calling_llm="gpt-4o-mini" # Cheaper model for tool calls ) ``` #### Custom Template Agent ```python Code theme={null} custom_agent = Agent( role="Customer Service Representative", goal="Assist customers with their inquiries", backstory="Experienced in customer support with a focus on satisfaction", system_template="""<|start_header_id|>system<|end_header_id|> {{ .System }}<|eot_id|>""", prompt_template="""<|start_header_id|>user<|end_header_id|> {{ .Prompt }}<|eot_id|>""", response_template="""<|start_header_id|>assistant<|end_header_id|> {{ .Response }}<|eot_id|>""", ) ``` #### Date-Aware Agent with Reasoning ```python Code theme={null} strategic_agent = Agent( role="Market Analyst", goal="Track market movements with precise date references and strategic planning", backstory="Expert in time-sensitive financial analysis and strategic reporting", inject_date=True, # Automatically inject current date into the prompt date_format="%B %d, %Y", # Format as "May 21, 2025" reasoning=True, # Enable strategic planning max_reasoning_attempts=2, # Limit planning iterations verbose=True ) ``` #### Reasoning Agent ```python Code theme={null} reasoning_agent = Agent( role="Strategic Planner", goal="Analyze complex problems and create detailed execution plans", backstory="Expert strategic planner who methodically breaks down complex challenges", reasoning=True, # Enable reasoning and planning max_reasoning_attempts=3, # Limit reasoning attempts max_iter=30, # Allow more iterations for complex planning verbose=True ) ``` #### Multimodal Agent ```python Code theme={null} multimodal_agent = Agent( role="Visual Content Analyst", goal="Analyze and process both text and visual content", backstory="Specialized in multimodal analysis combining text and image understanding", multimodal=True, # Enable multimodal capabilities verbose=True ) ``` ### Parameter Details #### Critical Parameters * `role`, `goal`, and `backstory` are required and shape the agent's behavior * `llm` determines the language model used (default: OpenAI's GPT-4) #### Memory and Context * `memory`: Enable to maintain conversation history * `respect_context_window`: Prevents token limit issues * `knowledge_sources`: Add domain-specific knowledge bases #### Execution Control * `max_iter`: Maximum attempts before giving best answer * `max_execution_time`: Timeout in seconds * `max_rpm`: Rate limiting for API calls * `max_retry_limit`: Retries on error #### Code Execution `allow_code_execution` and `code_execution_mode` are deprecated. `CodeInterpreterTool` has been removed from `crewai-tools`. Use a dedicated sandbox service such as [E2B](https://e2b.dev) or [Modal](https://modal.com) for secure code execution. * `allow_code_execution` *(deprecated)*: Previously enabled built-in code execution via `CodeInterpreterTool`. * `code_execution_mode` *(deprecated)*: Previously controlled execution mode (`"safe"` for Docker, `"unsafe"` for direct execution). #### Advanced Features * `multimodal`: Enable multimodal capabilities for processing text and visual content * `reasoning`: Enable agent to reflect and create plans before executing tasks * `inject_date`: Automatically inject current date into the agents prompt #### Templates * `system_template`: Defines agent's core behavior * `prompt_template`: Structures input format * `response_template`: Formats agent responses When using custom templates, ensure that both `system_template` and `prompt_template` are defined. The `response_template` is optional but recommended for consistent output formatting. When using custom templates, you can use variables like `{role}`, `{goal}`, and `{backstory}` in your templates. These will be automatically populated during execution. ## Agent Tools Agents can be equipped with various tools to enhance their capabilities. CrewAI supports tools from: * [CrewAI Toolkit](https://github.com/joaomdmoura/crewai-tools) * [LangChain Tools](https://python.langchain.com/docs/integrations/tools) Here's how to add tools to an agent: ```python Code theme={null} from crewai import Agent from crewai_tools import SerperDevTool, WikipediaTools # Create tools search_tool = SerperDevTool() wiki_tool = WikipediaTools() # Add tools to agent researcher = Agent( role="AI Technology Researcher", goal="Research the latest AI developments", tools=[search_tool, wiki_tool], verbose=True ) ``` ## Agent Memory and Context Agents can maintain memory of their interactions and use context from previous tasks. This is particularly useful for complex workflows where information needs to be retained across multiple tasks. ```python Code theme={null} from crewai import Agent analyst = Agent( role="Data Analyst", goal="Analyze and remember complex data patterns", memory=True, # Enable memory verbose=True ) ``` When `memory` is enabled, the agent will maintain context across multiple interactions, improving its ability to handle complex, multi-step tasks. ## Context Window Management CrewAI includes sophisticated automatic context window management to handle situations where conversations exceed the language model's token limits. This powerful feature is controlled by the `respect_context_window` parameter. ### How Context Window Management Works When an agent's conversation history grows too large for the LLM's context window, CrewAI automatically detects this situation and can either: 1. **Automatically summarize content** (when `respect_context_window=True`) 2. **Stop execution with an error** (when `respect_context_window=False`) ### Automatic Context Handling (`respect_context_window=True`) This is the **default and recommended setting** for most use cases. When enabled, CrewAI will: ```python Code theme={null} # Agent with automatic context management (default) smart_agent = Agent( role="Research Analyst", goal="Analyze large documents and datasets", backstory="Expert at processing extensive information", respect_context_window=True, # 🔑 Default: auto-handle context limits verbose=True ) ``` **What happens when context limits are exceeded:** * ⚠️ **Warning message**: `"Context length exceeded. Summarizing content to fit the model context window."` * 🔄 **Automatic summarization**: CrewAI intelligently summarizes the conversation history * ✅ **Continued execution**: Task execution continues seamlessly with the summarized context * 📝 **Preserved information**: Key information is retained while reducing token count ### Strict Context Limits (`respect_context_window=False`) When you need precise control and prefer execution to stop rather than lose any information: ```python Code theme={null} # Agent with strict context limits strict_agent = Agent( role="Legal Document Reviewer", goal="Provide precise legal analysis without information loss", backstory="Legal expert requiring complete context for accurate analysis", respect_context_window=False, # ❌ Stop execution on context limit verbose=True ) ``` **What happens when context limits are exceeded:** * ❌ **Error message**: `"Context length exceeded. Consider using smaller text or RAG tools from crewai_tools."` * 🛑 **Execution stops**: Task execution halts immediately * 🔧 **Manual intervention required**: You need to modify your approach ### Choosing the Right Setting #### Use `respect_context_window=True` (Default) when: * **Processing large documents** that might exceed context limits * **Long-running conversations** where some summarization is acceptable * **Research tasks** where general context is more important than exact details * **Prototyping and development** where you want robust execution ```python Code theme={null} # Perfect for document processing document_processor = Agent( role="Document Analyst", goal="Extract insights from large research papers", backstory="Expert at analyzing extensive documentation", respect_context_window=True, # Handle large documents gracefully max_iter=50, # Allow more iterations for complex analysis verbose=True ) ``` #### Use `respect_context_window=False` when: * **Precision is critical** and information loss is unacceptable * **Legal or medical tasks** requiring complete context * **Code review** where missing details could introduce bugs * **Financial analysis** where accuracy is paramount ```python Code theme={null} # Perfect for precision tasks precision_agent = Agent( role="Code Security Auditor", goal="Identify security vulnerabilities in code", backstory="Security expert requiring complete code context", respect_context_window=False, # Prefer failure over incomplete analysis max_retry_limit=1, # Fail fast on context issues verbose=True ) ``` ### Alternative Approaches for Large Data When dealing with very large datasets, consider these strategies: #### 1. Use RAG Tools ```python Code theme={null} from crewai_tools import RagTool # Create RAG tool for large document processing rag_tool = RagTool() rag_agent = Agent( role="Research Assistant", goal="Query large knowledge bases efficiently", backstory="Expert at using RAG tools for information retrieval", tools=[rag_tool], # Use RAG instead of large context windows respect_context_window=True, verbose=True ) ``` #### 2. Use Knowledge Sources ```python Code theme={null} # Use knowledge sources instead of large prompts knowledge_agent = Agent( role="Knowledge Expert", goal="Answer questions using curated knowledge", backstory="Expert at leveraging structured knowledge sources", knowledge_sources=[your_knowledge_sources], # Pre-processed knowledge respect_context_window=True, verbose=True ) ``` ### Context Window Best Practices 1. **Monitor Context Usage**: Enable `verbose=True` to see context management in action 2. **Design for Efficiency**: Structure tasks to minimize context accumulation 3. **Use Appropriate Models**: Choose LLMs with context windows suitable for your tasks 4. **Test Both Settings**: Try both `True` and `False` to see which works better for your use case 5. **Combine with RAG**: Use RAG tools for very large datasets instead of relying solely on context windows ### Troubleshooting Context Issues **If you're getting context limit errors:** ```python Code theme={null} # Quick fix: Enable automatic handling agent.respect_context_window = True # Better solution: Use RAG tools for large data from crewai_tools import RagTool agent.tools = [RagTool()] # Alternative: Break tasks into smaller pieces # Or use knowledge sources instead of large prompts ``` **If automatic summarization loses important information:** ```python Code theme={null} # Disable auto-summarization and use RAG instead agent = Agent( role="Detailed Analyst", goal="Maintain complete information accuracy", backstory="Expert requiring full context", respect_context_window=False, # No summarization tools=[RagTool()], # Use RAG for large data verbose=True ) ``` The context window management feature works automatically in the background. You don't need to call any special functions - just set `respect_context_window` to your preferred behavior and CrewAI handles the rest! ## Direct Agent Interaction with `kickoff()` Agents can be used directly without going through a task or crew workflow using the `kickoff()` method. This provides a simpler way to interact with an agent when you don't need the full crew orchestration capabilities. ### How `kickoff()` Works The `kickoff()` method allows you to send messages directly to an agent and get a response, similar to how you would interact with an LLM but with all the agent's capabilities (tools, reasoning, etc.). ```python Code theme={null} from crewai import Agent from crewai_tools import SerperDevTool # Create an agent researcher = Agent( role="AI Technology Researcher", goal="Research the latest AI developments", tools=[SerperDevTool()], verbose=True ) # Use kickoff() to interact directly with the agent result = researcher.kickoff("What are the latest developments in language models?") # Access the raw response print(result.raw) ``` ### Parameters and Return Values | Parameter | Type | Description | | :---------------- | :--------------------------------- | :------------------------------------------------------------------------ | | `messages` | `Union[str, List[Dict[str, str]]]` | Either a string query or a list of message dictionaries with role/content | | `response_format` | `Optional[Type[Any]]` | Optional Pydantic model for structured output | The method returns a `LiteAgentOutput` object with the following properties: * `raw`: String containing the raw output text * `pydantic`: Parsed Pydantic model (if a `response_format` was provided) * `agent_role`: Role of the agent that produced the output * `usage_metrics`: Token usage metrics for the execution ### Structured Output You can get structured output by providing a Pydantic model as the `response_format`: ```python Code theme={null} from pydantic import BaseModel from typing import List class ResearchFindings(BaseModel): main_points: List[str] key_technologies: List[str] future_predictions: str # Get structured output result = researcher.kickoff( "Summarize the latest developments in AI for 2025", response_format=ResearchFindings ) # Access structured data print(result.pydantic.main_points) print(result.pydantic.future_predictions) ``` ### Multiple Messages You can also provide a conversation history as a list of message dictionaries: ```python Code theme={null} messages = [ {"role": "user", "content": "I need information about large language models"}, {"role": "assistant", "content": "I'd be happy to help with that! What specifically would you like to know?"}, {"role": "user", "content": "What are the latest developments in 2025?"} ] result = researcher.kickoff(messages) ``` ### Async Support An asynchronous version is available via `kickoff_async()` with the same parameters: ```python Code theme={null} import asyncio async def main(): result = await researcher.kickoff_async("What are the latest developments in AI?") print(result.raw) asyncio.run(main()) ``` The `kickoff()` method uses a `LiteAgent` internally, which provides a simpler execution flow while preserving all of the agent's configuration (role, goal, backstory, tools, etc.). ## Important Considerations and Best Practices ### Security and Code Execution `allow_code_execution` and `code_execution_mode` are deprecated and `CodeInterpreterTool` has been removed. Use a dedicated sandbox service such as [E2B](https://e2b.dev) or [Modal](https://modal.com) for secure code execution. ### Performance Optimization * Use `respect_context_window: true` to prevent token limit issues * Set appropriate `max_rpm` to avoid rate limiting * Enable `cache: true` to improve performance for repetitive tasks * Adjust `max_iter` and `max_retry_limit` based on task complexity ### Memory and Context Management * Leverage `knowledge_sources` for domain-specific information * Configure `embedder` when using custom embedding models * Use custom templates (`system_template`, `prompt_template`, `response_template`) for fine-grained control over agent behavior ### Advanced Features * Enable `reasoning: true` for agents that need to plan and reflect before executing complex tasks * Set appropriate `max_reasoning_attempts` to control planning iterations (None for unlimited attempts) * Use `inject_date: true` to provide agents with current date awareness for time-sensitive tasks * Customize the date format with `date_format` using standard Python datetime format codes * Enable `multimodal: true` for agents that need to process both text and visual content ### Agent Collaboration * Enable `allow_delegation: true` when agents need to work together * Use `step_callback` to monitor and log agent interactions * Consider using different LLMs for different purposes: * Main `llm` for complex reasoning * `function_calling_llm` for efficient tool usage ### Date Awareness and Reasoning * Use `inject_date: true` to provide agents with current date awareness for time-sensitive tasks * Customize the date format with `date_format` using standard Python datetime format codes * Valid format codes include: %Y (year), %m (month), %d (day), %B (full month name), etc. * Invalid date formats will be logged as warnings and will not modify the task description * Enable `reasoning: true` for complex tasks that benefit from upfront planning and reflection ### Model Compatibility * Set `use_system_prompt: false` for older models that don't support system messages * Ensure your chosen `llm` supports the features you need (like function calling) ## Troubleshooting Common Issues 1. **Rate Limiting**: If you're hitting API rate limits: * Implement appropriate `max_rpm` * Use caching for repetitive operations * Consider batching requests 2. **Context Window Errors**: If you're exceeding context limits: * Enable `respect_context_window` * Use more efficient prompts * Clear agent memory periodically 3. **Code Execution Issues**: If code execution fails: * Verify Docker is installed for safe mode * Check execution permissions * Review code sandbox settings 4. **Memory Issues**: If agent responses seem inconsistent: * Check knowledge source configuration * Review conversation history management Remember that agents are most effective when configured according to their specific use case. Take time to understand your requirements and adjust these parameters accordingly. # Checkpointing Source: https://docs.crewai.com/v1.15.16/en/concepts/checkpointing Automatically save execution state so crews, flows, and agents can resume after failures. Checkpointing saves a snapshot of execution state during a run so a crew, flow, or agent can resume after a failure or be forked into an alternate branch. How checkpointing works: events, storage, and inheritance. A 5-minute walkthrough: run, interrupt, resume. Task-focused recipes for common workflows. `CheckpointConfig`, events, providers, and CLI. ## Explanation ### What a checkpoint is A checkpoint captures everything CrewAI needs to recreate a run mid-flight: the full state of the crew, flow, or agent — configuration, agent memory and knowledge sources, task progress, intermediate outputs, internal state and attributes — alongside the kickoff inputs, the event history up to that point, and a lineage ID that ties the checkpoint to the run it came from. Restoring rebuilds that state and continues. Completed tasks are skipped, memory and knowledge are rehydrated, and downstream work runs against the same outputs the original run produced. Forking does the same restore under a new lineage, so the new branch and the original run can write checkpoints side by side without overwriting each other. ### When checkpoints are written Checkpointing is event-driven. The runtime subscribes to events you select via `on_events` and writes a checkpoint each time one fires. The default `task_completed` produces one checkpoint per finished task — a sensible tradeoff between granularity and disk use. Higher-frequency events like `llm_call_completed` are available for fine-grained recovery but write far more files. ### Storage Two providers ship with CrewAI: * `JsonProvider` writes one file per checkpoint. Human-readable and easy to inspect. * `SqliteProvider` writes to a single SQLite database. Better for high-frequency checkpointing. Both prune oldest checkpoints when `max_checkpoints` is set. Auto-checkpoint writes (event-driven) are best-effort: a failed write is logged and the run continues. Manual `state.checkpoint()` and `state.acheckpoint()` calls re-raise on failure. ### Inheritance model `Crew`, `Flow`, and `Agent` all accept a `checkpoint` argument. Children inherit from their parent unless they set their own value or pass `False` to opt out. Enable checkpointing once on the crew and every agent participates, or selectively exclude one agent. ## Tutorial: Resume a failing crew This walkthrough takes \~5 minutes. You will run a two-task crew, kill it midway, and resume from the saved checkpoint. ```python theme={null} from crewai import Agent, Crew, Task researcher = Agent(role="Researcher", goal="Research", backstory="Expert") writer = Agent(role="Writer", goal="Write", backstory="Expert") crew = Crew( agents=[researcher, writer], tasks=[ Task(description="Research AI trends", agent=researcher, expected_output="bullets"), Task(description="Write a summary", agent=writer, expected_output="paragraph"), ], checkpoint=True, ) ``` ```python theme={null} result = crew.kickoff() ``` Press `Ctrl+C` after the first task finishes. Look in `./.checkpoints/` — a file named `_.json` is the checkpoint. ```python theme={null} from crewai import CheckpointConfig result = crew.kickoff( from_checkpoint=CheckpointConfig( restore_from="./.checkpoints/_.json", ), ) ``` The research task is skipped, the writer runs against the saved research output, and the crew finishes. ## How-to guides ```python theme={null} crew = Crew(agents=[...], tasks=[...], checkpoint=True) ``` Writes to `./.checkpoints/` on every `task_completed`. ```python theme={null} from crewai import Crew, CheckpointConfig crew = Crew( agents=[...], tasks=[...], checkpoint=CheckpointConfig( location="./my_checkpoints", on_events=["task_completed", "crew_kickoff_completed"], max_checkpoints=5, ), ) ``` ```python JsonProvider theme={null} from crewai import Crew, CheckpointConfig from crewai.state import JsonProvider crew = Crew( agents=[...], tasks=[...], checkpoint=CheckpointConfig( location="./my_checkpoints", provider=JsonProvider(), max_checkpoints=5, ), ) ``` ```python SqliteProvider theme={null} from crewai import Crew, CheckpointConfig from crewai.state import SqliteProvider crew = Crew( agents=[...], tasks=[...], checkpoint=CheckpointConfig( location="./.checkpoints.db", provider=SqliteProvider(), max_checkpoints=50, ), ) ``` SQLite enables WAL journal mode for concurrent reads. Prefer it for high-frequency checkpointing. ```python theme={null} crew = Crew( agents=[ Agent(role="Researcher", ...), Agent(role="Writer", ..., checkpoint=False), ], tasks=[...], checkpoint=True, ) ``` `fork()` restores a checkpoint under a fresh lineage so the new run does not collide with the original. ```python theme={null} config = CheckpointConfig(restore_from="./my_checkpoints/.json") crew = Crew.fork(config, branch="experiment-a") result = crew.kickoff(inputs={"strategy": "aggressive"}) ``` The `branch` label is optional; one is generated if omitted. ```python theme={null} crew = Crew( agents=[researcher, writer], tasks=[research_task, write_task, review_task], checkpoint=CheckpointConfig(location="./crew_cp"), ) ``` Default trigger: `task_completed`. ```python theme={null} from crewai.flow.flow import Flow, start, listen from crewai import CheckpointConfig class MyFlow(Flow): @start() def step_one(self): return "data" @listen(step_one) def step_two(self, data): return process(data) flow = MyFlow( checkpoint=CheckpointConfig( location="./flow_cp", on_events=["method_execution_finished"], ), ) result = flow.kickoff() ``` ```python theme={null} agent = Agent( role="Researcher", goal="Research topics", backstory="Expert researcher", checkpoint=CheckpointConfig( location="./agent_cp", on_events=["lite_agent_execution_completed"], ), ) result = agent.kickoff(messages=[{"role": "user", "content": "Research AI trends"}]) ``` Register a handler on any event and call `state.checkpoint()`. ```python Sync theme={null} from __future__ import annotations from typing import TYPE_CHECKING, Any from crewai.events.event_bus import crewai_event_bus from crewai.events.types.llm_events import LLMCallCompletedEvent if TYPE_CHECKING: from crewai.state.runtime import RuntimeState @crewai_event_bus.on(LLMCallCompletedEvent) def on_llm_done(source: Any, event: LLMCallCompletedEvent, state: RuntimeState) -> None: path = state.checkpoint("./my_checkpoints") print(f"Saved checkpoint: {path}") ``` ```python Async theme={null} from __future__ import annotations from typing import TYPE_CHECKING, Any from crewai.events.event_bus import crewai_event_bus from crewai.events.types.llm_events import LLMCallCompletedEvent if TYPE_CHECKING: from crewai.state.runtime import RuntimeState @crewai_event_bus.on(LLMCallCompletedEvent) async def on_llm_done_async(source: Any, event: LLMCallCompletedEvent, state: RuntimeState) -> None: path = await state.acheckpoint("./my_checkpoints") print(f"Saved checkpoint: {path}") ``` A `state` argument is supplied automatically when the handler takes three parameters. See [Event Listeners](/en/concepts/event-listener) for the full event catalog. ```bash theme={null} crewai checkpoint crewai checkpoint --location ./my_checkpoints crewai checkpoint --location ./.checkpoints.db ``` Checkpoint TUI tree view 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. Checkpoint detail overview tab The detail panel exposes two editable areas: * **Inputs** — original kickoff inputs, pre-filled and editable. Editable kickoff inputs * **Task outputs** — outputs of completed tasks. Editing an output and hitting **Fork** invalidates downstream tasks so they re-run against the modified context. Editable task outputs Fork confirmation panel Useful for "what if" exploration: fork, tweak, observe. ```bash theme={null} crewai checkpoint list ./my_checkpoints crewai checkpoint info ./my_checkpoints/.json crewai checkpoint info ./.checkpoints.db ``` ## Reference ### `CheckpointConfig` Storage destination. A directory for `JsonProvider`, a database file path for `SqliteProvider`. Event types that trigger a checkpoint. `CheckpointEventType` is a `Literal` — your type checker will autocomplete and reject unsupported values. See [event types](#event-types) for the full list. Storage backend. Either `JsonProvider` or `SqliteProvider`. Maximum checkpoints to retain. Oldest are pruned after each write. Checkpoint to restore from when passed via `from_checkpoint`. ### `checkpoint` field values Accepted by `Crew`, `Flow`, and `Agent`. Inherit from parent. Enable with defaults. Explicit opt-out. Stops inheritance. Custom configuration. ### Event types `on_events` accepts any combination of `CheckpointEventType` values. The default `["task_completed"]` writes one checkpoint per finished task; `["*"]` matches every event. `["*"]` and high-frequency events like `llm_call_completed` write many checkpoints and can degrade performance. Pair them with `max_checkpoints`. * **Task** — `task_started`, `task_completed`, `task_failed`, `task_evaluation` * **Crew** — `crew_kickoff_started`, `crew_kickoff_completed`, `crew_kickoff_failed`, `crew_train_started`, `crew_train_completed`, `crew_train_failed`, `crew_test_started`, `crew_test_completed`, `crew_test_failed`, `crew_test_result` * **Agent** — `agent_execution_started`, `agent_execution_completed`, `agent_execution_error`, `lite_agent_execution_started`, `lite_agent_execution_completed`, `lite_agent_execution_error`, `agent_evaluation_started`, `agent_evaluation_completed`, `agent_evaluation_failed` * **Flow** — `flow_created`, `flow_started`, `flow_finished`, `flow_paused`, `method_execution_started`, `method_execution_finished`, `method_execution_failed`, `method_execution_paused`, `human_feedback_requested`, `human_feedback_received`, `flow_input_requested`, `flow_input_received` * **LLM** — `llm_call_started`, `llm_call_completed`, `llm_call_failed`, `llm_stream_chunk`, `llm_thinking_chunk` * **LLM Guardrail** — `llm_guardrail_started`, `llm_guardrail_completed`, `llm_guardrail_failed` * **Tool** — `tool_usage_started`, `tool_usage_finished`, `tool_usage_error`, `tool_validate_input_error`, `tool_selection_error`, `tool_execution_error` * **Memory** — `memory_save_started`, `memory_save_completed`, `memory_save_failed`, `memory_query_started`, `memory_query_completed`, `memory_query_failed`, `memory_retrieval_started`, `memory_retrieval_completed`, `memory_retrieval_failed` * **Knowledge** — `knowledge_search_query_started`, `knowledge_search_query_completed`, `knowledge_query_started`, `knowledge_query_completed`, `knowledge_query_failed`, `knowledge_search_query_failed` * **Reasoning** — `agent_reasoning_started`, `agent_reasoning_completed`, `agent_reasoning_failed` * **MCP** — `mcp_connection_started`, `mcp_connection_completed`, `mcp_connection_failed`, `mcp_tool_execution_started`, `mcp_tool_execution_completed`, `mcp_tool_execution_failed`, `mcp_config_fetch_failed` * **Observation** — `step_observation_started`, `step_observation_completed`, `step_observation_failed`, `plan_refinement`, `plan_replan_triggered`, `goal_achieved_early` * **Skill** — `skill_discovery_started`, `skill_discovery_completed`, `skill_loaded`, `skill_activated`, `skill_load_failed` * **Logging** — `agent_logs_started`, `agent_logs_execution` * **A2A** — `a2a_delegation_started`, `a2a_delegation_completed`, `a2a_conversation_started`, `a2a_conversation_completed`, `a2a_message_sent`, `a2a_response_received`, `a2a_polling_started`, `a2a_polling_status`, `a2a_push_notification_registered`, `a2a_push_notification_received`, `a2a_push_notification_sent`, `a2a_push_notification_timeout`, `a2a_streaming_started`, `a2a_streaming_chunk`, `a2a_agent_card_fetched`, `a2a_authentication_failed`, `a2a_artifact_received`, `a2a_connection_error`, `a2a_server_task_started`, `a2a_server_task_completed`, `a2a_server_task_canceled`, `a2a_server_task_failed`, `a2a_parallel_delegation_started`, `a2a_parallel_delegation_completed`, `a2a_transport_negotiated`, `a2a_content_type_negotiated`, `a2a_context_created`, `a2a_context_expired`, `a2a_context_idle`, `a2a_context_completed`, `a2a_context_pruned` * **System signals** — `SIGTERM`, `SIGINT`, `SIGHUP`, `SIGTSTP`, `SIGCONT` * **Wildcard** — `"*"` matches every event. ### Storage providers One file per checkpoint, named `_.json` inside `location`. Single database file at `location` with WAL journaling. ### CLI | Command | Purpose | | :------------------------------------ | :------------------------------------------------------------------ | | `crewai checkpoint` | Launch the TUI; auto-detect storage. | | `crewai checkpoint --location ` | Launch the TUI against a specific location. | | `crewai checkpoint list ` | List checkpoints. | | `crewai checkpoint info ` | Inspect a checkpoint file or the latest entry in a SQLite database. | # CLI Source: https://docs.crewai.com/v1.15.16/en/concepts/cli Learn how to use the CrewAI CLI to interact with CrewAI. Since release 0.140.0, CrewAI AMP started a process of migrating their login provider. As such, the authentication flow via CLI was updated. Users that use Google to login, or that created their account after July 3rd, 2025 will be unable to log in with older versions of the `crewai` library. ## Overview The CrewAI CLI provides a set of commands to interact with CrewAI, allowing you to create, train, run, and manage crews & flows. ## Installation To use the CrewAI CLI, make sure you have CrewAI installed: ```shell Terminal theme={null} pip install crewai ``` ## Basic Usage The basic structure of a CrewAI CLI command is: ```shell Terminal theme={null} crewai [COMMAND] [OPTIONS] [ARGUMENTS] ``` ## Available Commands ### 1. Create Create a new crew, flow, tool, skill, or template project. ```shell Terminal theme={null} crewai create [OPTIONS] TYPE NAME ``` * `TYPE`: `crew`, `flow`, `tool`, `skill`, or `template` * `NAME`: Name of the project, tool handle, skill, or template #### Crew ```shell Terminal theme={null} crewai create crew my_new_crew crewai create crew my_new_crew --classic ``` By default, `crewai create crew` creates a JSON-first crew project with `crew.jsonc` and `agents/*.jsonc`. Use `crewai create crew my_new_crew --classic` only when you want the older Python/YAML scaffold with `crew.py`, `config/agents.yaml`, and `config/tasks.yaml`. #### Flow ```shell Terminal theme={null} crewai create flow my_new_flow crewai create flow my_new_flow --declarative ``` #### Tool Scaffold a custom tool repository: ```shell Terminal theme={null} crewai create tool my_tool ``` #### Skill Scaffold an agent skill. Inside a crew project (where `pyproject.toml` exists), the skill is created under `./skills/`: ```shell Terminal theme={null} crewai create skill my-skill crewai create skill my-skill --no-project ``` Use `--no-project` to create the skill in the current directory instead of `./skills/`. #### Template Add a remote project template to the current directory: ```shell Terminal theme={null} crewai create template my-template crewai create template my-template --output-dir custom_dir ``` Use `--output-dir` to override the output folder name (defaults to the template name). #### Deprecated create aliases These older commands still work but print a yellow deprecation warning. Prefer the `crewai create ` forms above. | Deprecated | Use instead | | :---------------------------- | :------------------------------ | | `crewai tool create ` | `crewai create tool ` | | `crewai skill create ` | `crewai create skill ` | | `crewai template add ` | `crewai create template ` | Lifecycle commands are unchanged — for example `crewai tool install`, `crewai skill publish`, and `crewai template list` stay under their resource groups. #### Deprecated flag aliases These older snake\_case flags still work but are hidden from `--help`. Prefer the kebab-case forms documented in each command section below. | Deprecated | Use instead | | :-------------------------------------------------- | :---------------- | | `--skip_provider` (on `crewai create crew`) | `--skip-provider` | | `--n_iterations` (on `crewai train`, `crewai test`) | `--n-iterations` | | `--task_id` (on `crewai replay`) | `--task-id` | ### 2. Version Show the installed version of CrewAI. ```shell Terminal theme={null} crewai version [OPTIONS] ``` * `--tools`: (Optional) Show the installed version of CrewAI tools Example: ```shell Terminal theme={null} crewai version crewai version --tools ``` ### 3. Train Train the crew for a specified number of iterations. ```shell Terminal theme={null} crewai train [OPTIONS] ``` * `-n, --n-iterations INTEGER`: Number of iterations to train the crew (default: 5) * `-f, --filename TEXT`: Path to a custom file for training (default: "trained\_agents\_data.pkl") Example: ```shell Terminal theme={null} crewai train -n 10 -f my_training_data.pkl ``` ### 4. Replay Replay the crew execution from a specific task. ```shell Terminal theme={null} crewai replay [OPTIONS] ``` * `-t, --task-id TEXT`: Replay the crew from this task ID, including all subsequent tasks Example: ```shell Terminal theme={null} crewai replay -t task_123456 ``` ### 5. Log-tasks-outputs Retrieve your latest crew\.kickoff() task outputs. ```shell Terminal theme={null} crewai log-tasks-outputs ``` ### 6. Reset-memories Reset the crew memories (long, short, entity, latest\_crew\_kickoff\_outputs). ```shell Terminal theme={null} crewai reset-memories [OPTIONS] ``` * `-l, --long`: Reset LONG TERM memory * `-s, --short`: Reset SHORT TERM memory * `-e, --entities`: Reset ENTITIES memory * `-k, --kickoff-outputs`: Reset LATEST KICKOFF TASK OUTPUTS * `-kn, --knowledge`: Reset KNOWLEDGE storage * `-akn, --agent-knowledge`: Reset AGENT KNOWLEDGE storage * `-a, --all`: Reset ALL memories Example: ```shell Terminal theme={null} crewai reset-memories --long --short crewai reset-memories --all ``` ### 7. Test Test the crew and evaluate the results. ```shell Terminal theme={null} crewai test [OPTIONS] ``` * `-n, --n-iterations INTEGER`: Number of iterations to test the crew (default: 3) * `-m, --model TEXT`: LLM Model to run the tests on the Crew (default: "gpt-4o-mini") Example: ```shell Terminal theme={null} crewai test -n 5 -m gpt-3.5-turbo ``` ### 8. Run Run the crew or flow. ```shell Terminal theme={null} crewai run ``` Starting from version 0.103.0, the `crewai run` command can be used to run both standard crews and flows. For flows, it automatically detects the type from pyproject.toml and runs the appropriate command. This is now the recommended way to run both crews and flows. Make sure to run these commands from the directory where your CrewAI project is set up. Some commands may require additional configuration or setup within your project structure. ### 9. Chat Starting in version `0.98.0`, when you run the `crewai chat` command, you start an interactive session with your crew. The AI assistant will guide you by asking for necessary inputs to execute the crew. Once all inputs are provided, the crew will execute its tasks. After receiving the results, you can continue interacting with the assistant for further instructions or questions. ```shell Terminal theme={null} crewai chat ``` Ensure you execute these commands from your CrewAI project's root directory. IMPORTANT: Set the `chat_llm` property in your crew definition to enable this command. For JSON-first crews, add it to `crew.jsonc`: ```jsonc theme={null} { "name": "My Crew", "agents": ["researcher"], "tasks": [], "chat_llm": "openai/gpt-4o" } ``` For classic Python/YAML crews, set it in `crew.py`: ```python theme={null} @crew def crew(self) -> Crew: return Crew( agents=self.agents, tasks=self.tasks, process=Process.sequential, verbose=True, chat_llm="gpt-4o", # LLM for chat orchestration ) ``` ### 10. Deploy Deploy the crew or flow to [CrewAI AMP](https://app.crewai.com). * **Authentication**: You need to be authenticated to deploy to CrewAI AMP. You can login or create an account with: ```shell Terminal theme={null} crewai login ``` * **Create a deployment**: Once you are authenticated, you can create a deployment for your crew or flow from the root of your localproject. ```shell Terminal theme={null} crewai deploy create ``` * Reads your local project configuration. * Prompts you to confirm the environment variables (like `OPENAI_API_KEY`, `SERPER_API_KEY`) found locally. These will be securely stored with the deployment on the Enterprise platform. Ensure your sensitive keys are correctly configured locally (e.g., in a `.env` file) before running this. ### 11. Organization Management Manage your CrewAI AMP organizations. ```shell Terminal theme={null} crewai org [COMMAND] [OPTIONS] ``` #### Commands: * `list`: List all organizations you belong to ```shell Terminal theme={null} crewai org list ``` * `current`: Display your currently active organization ```shell Terminal theme={null} crewai org current ``` * `switch`: Switch to a specific organization ```shell Terminal theme={null} crewai org switch ``` You must be authenticated to CrewAI AMP to use these organization management commands. * **Create a deployment** (continued): * Links the deployment to the corresponding remote GitHub repository (it usually detects this automatically). * **Deploy the Crew**: Once you are authenticated, you can deploy your crew or flow to CrewAI AMP. ```shell Terminal theme={null} crewai deploy push ``` * Initiates the deployment process on the CrewAI AMP platform. * Upon successful initiation, it will output the Deployment created successfully! message along with the Deployment Name and a unique Deployment ID (UUID). * **Deployment Status**: You can check the status of your deployment with: ```shell Terminal theme={null} crewai deploy status ``` This fetches the latest deployment status of your most recent deployment attempt (e.g., `Building Images for Crew`, `Deploy Enqueued`, `Online`). * **Deployment Logs**: You can check the logs of your deployment with: ```shell Terminal theme={null} crewai deploy logs ``` This streams the deployment logs to your terminal. * **List deployments**: You can list all your deployments with: ```shell Terminal theme={null} crewai deploy list ``` This lists all your deployments. * **Delete a deployment**: You can delete a deployment with: ```shell Terminal theme={null} crewai deploy remove ``` This deletes the deployment from the CrewAI AMP platform. * **Help Command**: You can get help with the CLI with: ```shell Terminal theme={null} crewai deploy --help ``` This shows the help message for the CrewAI Deploy CLI. Watch this video tutorial for a step-by-step demonstration of deploying your crew to [CrewAI AMP](http://app.crewai.com) using the CLI.