# https://github.com/crewAIInc/crewAI 项目说明书

生成时间：2026-05-16 06:15:18 UTC

## 目录

- [Installation and Setup](#installation)
- [Quick Start Guide](#quickstart)
- [Agents Architecture](#agents)
- [Tasks and Task Management](#tasks)
- [Crews and Crew Orchestration](#crews)
- [Flows - Event-Driven Workflows](#flows)
- [LLM Providers and Configuration](#llm-providers)
- [Agent-to-Agent (A2A) Communication](#agent-to-agent)
- [Knowledge Management](#knowledge)
- [Memory and Storage System](#memory)

<a id='installation'></a>

## Installation and Setup

### 相关页面

相关主题：[Quick Start Guide](#quickstart), [LLM Providers and Configuration](#llm-providers)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [pyproject.toml](https://github.com/crewAIInc/crewAI/blob/main/pyproject.toml)
- [lib/crewai/pyproject.toml](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/pyproject.toml)
- [lib/crewai-tools/pyproject.toml](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai-tools/pyproject.toml)
- [lib/cli/src/crewai_cli/templates/tool/README.md](https://github.com/crewAIInc/crewAI/blob/main/lib/cli/src/crewai_cli/templates/tool/README.md)
- [lib/cli/src/crewai_cli/templates/AGENTS.md](https://github.com/crewAIInc/crewAI/blob/main/lib/cli/src/crewai_cli/templates/AGENTS.md)
</details>

# Installation and Setup

## Overview

This guide covers the installation and setup procedures for CrewAI, a multi-agent automation framework. The installation process supports multiple methods including pip, UV package manager, and direct source installation. CrewAI requires Python 3.10 to 3.13 and uses modern dependency management practices to ensure consistent environments across development and production.

## System Requirements

### Python Version Compatibility

| Requirement | Specification |
|-------------|----------------|
| Minimum Python | 3.10 |
| Maximum Python | < 3.14 |
| Package Manager | UV (recommended) or pip |

The project enforces version constraints through pyproject.toml configuration files. The version range ensures compatibility with modern Python features while avoiding breaking changes from upcoming releases.

## Installation Methods

### Standard Installation via pip

The primary method for installing CrewAI uses pip, Python's standard package manager:

```bash
pip install crewai
```

This installation includes the core CrewAI framework with essential dependencies. For users requiring additional tooling capabilities, the extended installation includes built-in tools:

```bash
pip install 'crewai[tools]'
```

资料来源：[lib/crewai/pyproject.toml](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/pyproject.toml)

### UV Package Manager Installation

UV is the recommended package manager for CrewAI projects due to its superior performance and dependency resolution capabilities.

```bash
pip install uv
```

After installing UV, create a new project with:

```bash
crewai create crew <project_name> --skip_provider
crewai create flow <project_name> --skip_provider
```

资料来源：[lib/cli/src/crewai_cli/templates/AGENTS.md](https://github.com/crewAIInc/crewAI/blob/main/lib/cli/src/crewai_cli/templates/AGENTS.md)

## Project Structure

After creating a new CrewAI project, the following directory structure is generated:

```
src/<project_name>/
├── __init__.py
├── crew.py
├── main.py
├── tools/
│   ├── custom_tool.py
│   └── __init__.py
└── config/
    ├── agents.yaml
    └── tasks.yaml
```

### Core Files Description

| File | Purpose |
|------|---------|
| `main.py` | Entry point for project execution |
| `crew.py` | Crew definition and agent orchestration logic |
| `agents.yaml` | Agent role, goal, and backstory configurations |
| `tasks.yaml` | Task descriptions and dependencies |
| `tools/` | Custom tool implementations |
| `.env` | Environment variables and API keys |

资料来源：[README.md](https://github.com/crewAIInc/crewAI/blob/main/README.md)

## Dependencies Management

### Using UV for Dependency Operations

UV provides fast and reliable dependency management. The following commands handle common dependency tasks:

```bash
uv add <package>          # Add a new dependency
uv sync                  # Synchronize dependencies with lock file
uv lock                  # Update the lock file
```

### Core Dependencies

The main `crewai` package includes these core dependencies:

- `pydantic` - Data validation and settings management
- `crewai` core modules - Agent orchestration and task management

### Tools Dependencies

Additional packages are required for specific tool integrations:

| Tool | Required Package |
|------|------------------|
| Tavily Search | `tavily-python` |
| File Compression | Built-in |
| PDF Processing | Built-in |
| ArXiv Integration | Built-in |

资料来源：[lib/crewai-tools/pyproject.toml](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai-tools/pyproject.toml)

## Environment Configuration

### Environment Variables Setup

Create a `.env` file in your project root to store sensitive configuration:

```bash
OPENAI_API_KEY=your_openai_api_key
TAVILY_API_KEY=your_tavily_api_key
SERPLY_API_KEY=your_serply_api_key
LINKUP_API_KEY=your_linkup_api_key
```

### Configuration in agents.yaml

Define agent behavior through YAML configuration:

```yaml
researcher:
  role: >
    {topic} Senior Data Researcher
  goal: >
    Uncover cutting-edge developments in {topic}
  backstory: >
    You're a seasoned researcher with a knack for uncovering the latest
    developments in {topic}.
```

资料来源：[README.md](https://github.com/crewAIInc/crewAI/blob/main/README.md)

## Custom Tools Installation

### Publishing Tools

Distribute custom tools within your organization or to the community:

```bash
crewai tool publish <tool_name>
```

### Installing Tools

Install tools published by others or within your organization:

```bash
crewai tool install <tool_name>
```

资料来源：[lib/cli/src/crewai_cli/templates/tool/README.md](https://github.com/crewAIInc/crewAI/blob/main/lib/cli/src/crewai_cli/templates/tool/README.md)

## Installation Verification

### Quick Verification Steps

After installation, verify the setup by running:

```bash
crewai run
```

This command auto-detects the project type from `pyproject.toml` and executes the crew or flow.

### Memory Management Commands

CrewAI provides CLI commands for managing agent memories:

```bash
crewai reset-memories -a              # Reset all memories
crewai reset-memories -s              # Short-term only
crewai reset-memories -l              # Long-term only
crewai reset-memories -e              # Entity only
crewai reset-memories -kn             # Knowledge only
crewai reset-memories -akn            # Agent knowledge only
```

资料来源：[lib/cli/src/crewai_cli/templates/AGENTS.md](https://github.com/crewAIInc/crewAI/blob/main/lib/cli/src/crewai_cli/templates/AGENTS.md)

## Development Workflow

```mermaid
graph TD
    A[Install CrewAI] --> B[Create Project]
    B --> C[Configure Agents]
    C --> D[Define Tasks]
    D --> E[Add Tools]
    E --> F[Set Environment Variables]
    F --> G[Run crewai run]
    G --> H[Test and Iterate]
    H --> I[Deploy]
```

## Troubleshooting Common Issues

### pyproject.toml Validation

The CLI validates `pyproject.toml` for proper CrewAI project structure. If validation fails:

1. Verify `crewai` is listed in project dependencies
2. Check TOML syntax correctness
3. Ensure required configuration keys exist

### Version Conflicts

If dependency conflicts occur:

1. Use `uv lock` to regenerate lock file
2. Verify Python version falls within 3.10-3.13 range
3. Clear cache with `uv cache clean`

资料来源：[lib/crewai-core/src/crewai_core/project.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai-core/src/crewai_core/project.py)

## Next Steps

After successful installation:

1. **Define Agents** - Configure roles, goals, and backstories in `config/agents.yaml`
2. **Create Tasks** - Define task descriptions and expected outputs in `config/tasks.yaml`
3. **Add Tools** - Integrate custom or built-in tools for agent capabilities
4. **Implement Logic** - Customize `crew.py` with specific orchestration requirements
5. **Test** - Use `crewai test` for iterative testing

## Summary

The CrewAI installation process supports multiple package managers and provides flexible project scaffolding. Key points:

- Minimum requirement: Python 3.10
- UV is the recommended package manager for modern workflows
- Project structure separates configuration (YAML) from implementation (Python)
- Custom tools can be published and installed through the CLI
- Environment variables handle sensitive configuration

---

<a id='quickstart'></a>

## Quick Start Guide

### 相关页面

相关主题：[Installation and Setup](#installation), [Agents Architecture](#agents), [Tasks and Task Management](#tasks)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [lib/cli/src/crewai_cli/templates/crew/crew.py](https://github.com/crewAIInc/crewAI/blob/main/lib/cli/src/crewai_cli/templates/crew/crew.py)
- [lib/cli/src/crewai_cli/templates/crew/main.py](https://github.com/crewAIInc/crewAI/blob/main/lib/cli/src/crewai_cli/templates/crew/main.py)
- [lib/cli/src/crewai_cli/templates/crew/config/agents.yaml](https://github.com/crewAIInc/crewAI/blob/main/lib/cli/src/crewai_cli/templates/crew/config/agents.yaml)
- [lib/cli/src/crewai_cli/templates/crew/config/tasks.yaml](https://github.com/crewAIInc/crewAI/blob/main/lib/cli/src/crewai_cli/templates/crew/config/tasks.yaml)
- [lib/cli/src/crewai_cli/templates/AGENTS.md](https://github.com/crewAIInc/crewAI/blob/main/lib/cli/src/crewai_cli/templates/AGENTS.md)
- [lib/crewai/README.md](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/README.md)
</details>

# Quick Start Guide

This guide provides a comprehensive overview for setting up and running your first CrewAI project. CrewAI is a multi-agent automation framework that enables you to build sophisticated AI-powered workflows by composing agents, tasks, and crews.

## Overview

The Quick Start Guide covers the essential steps to:

- Install CrewAI and its dependencies
- Scaffold a new crew project
- Configure agents and tasks using YAML
- Implement crew logic in Python
- Execute and test your crew

**Scope**: This guide focuses on the standard crew workflow using the `@CrewBase` decorator pattern with YAML-based configuration files.

## Prerequisites

| Requirement | Version |
|-------------|---------|
| Python | >=3.10, <3.14 |
| Package Manager | UV (recommended) |

资料来源：[lib/cli/src/crewai_cli/templates/tool/README.md](https://github.com/crewAIInc/crewAI/blob/main/lib/cli/src/crewai_cli/templates/tool/README.md)

## Project Structure

A typical CrewAI project follows this directory layout:

```
my_project/
├── src/my_project/
│   ├── __init__.py
│   ├── main.py              # Entry point
│   ├── crew.py              # Crew definition
│   └── config/
│       ├── agents.yaml      # Agent configurations
│       └── tasks.yaml       # Task configurations
├── .env                      # Environment variables
└── pyproject.toml           # Project configuration
```

资料来源：[lib/crewai/README.md](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/README.md)

## Installation

### Step 1: Install CrewAI CLI

```bash
pip install crewai
```

### Step 2: Install UV (if not already installed)

UV is the recommended package manager for CrewAI projects.

```bash
pip install uv
```

### Step 3: Create a New Crew Project

```bash
crewai create crew my_crew --skip_provider
```

### Step 4: Install Project Dependencies

```bash
cd my_crew
crewai install
```

资料来源：[lib/cli/src/crewai_cli/templates/AGENTS.md](https://github.com/crewAIInc/crewAI/blob/main/lib/cli/src/crewai_cli/templates/AGENTS.md)

## Project Components

### Agent Configuration (agents.yaml)

Agents are defined in YAML format with role, goal, and backstory:

```yaml
researcher:
  role: >
    {topic} Senior Data Researcher
  goal: >
    Uncover cutting-edge developments in {topic}
  backstory: >
    You're a seasoned researcher with a knack for uncovering the latest
    developments in {topic}. Known for your ability to find the most relevant
    information and present it in a clear and concise manner.

reporting_analyst:
  role: >
    {topic} Reporting Analyst
  goal: >
    Create detailed reports based on {topic} data analysis
  backstory: >
    You're a meticulous analyst with a keen eye for detail.
```

资料来源：[lib/crewai/README.md](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/README.md)

### Task Configuration (tasks.yaml)

Tasks define what each agent should accomplish:

```yaml
research_task:
  description: >
    Research the latest developments in {topic}
  expected_output: >
    A list of key findings with sources and implications.
  agent: researcher

reporting_task:
  description: >
    Create a comprehensive report on {topic}
  expected_output: >
    A fully fledged report with the main topics, each with a full section
    of information. Formatted as markdown.
  agent: reporting_analyst
  output_file: report.md
```

资料来源：[lib/crewai/README.md](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/README.md)

## Crew Implementation

### Crew Class (crew.py)

The crew class uses the `@CrewBase` decorator to bind agents and tasks:

```python
from crewai import Agent, Crew, Process, Task
from crewai.project import CrewBase, agent, crew, task
from crewai_tools import SerperDevTool
from crewai.agents.agent_builder.base_agent import BaseAgent
from typing import List

@CrewBase
class MyProjectCrew():
    """My project crew"""
    
    agents: List[BaseAgent]
    tasks: List[Task]

    @agent
    def researcher(self) -> Agent:
        return Agent(
            config=self.agents_config['researcher'],
            verbose=True,
            tools=[SerperDevTool()]
        )

    @agent
    def reporting_analyst(self) -> Agent:
        return Agent(
            config=self.agents_config['reporting_analyst'],
            verbose=True
        )

    @task
    def research_task(self) -> Task:
        return Task(config=self.tasks_config['research_task'])

    @task
    def reporting_task(self) -> Task:
        return Task(
            config=self.tasks_config['reporting_task'],
            output_file='report.md'
        )

    @crew
    def crew(self) -> Crew:
        return Crew(
            agents=self.agents,
            tasks=self.tasks,
            process=Process.sequential,
            verbose=True,
        )
```

资料来源：[lib/cli/src/crewai_cli/templates/crew/crew.py](https://github.com/crewAIInc/crewAI/blob/main/lib/cli/src/crewai_cli/templates/crew/crew.py)

### Entry Point (main.py)

The main entry point kicks off the crew:

```python
from crewai import Crew
from my_project.crew import MyProjectCrew

def run():
    inputs = {
        "topic": "AI LLMs"
    }
    
    crew = MyProjectCrew()
    result = crew.crew().kickoff(inputs=inputs)
    print(result)

if __name__ == "__main__":
    run()
```

资料来源：[lib/cli/src/crewai_cli/templates/crew/main.py](https://github.com/crewAIInc/crewAI/blob/main/lib/cli/src/crewai_cli/templates/crew/main.py)

## Workflow Diagram

```mermaid
graph TD
    A[Start: crewai create crew] --> B[Install Dependencies]
    B --> C[Configure agents.yaml]
    C --> D[Configure tasks.yaml]
    D --> E[Implement crew.py]
    E --> F[Implement main.py]
    F --> G[crewai run]
    G --> H{Crew Execution}
    H --> I[Agents Complete Tasks]
    I --> J[Output Generated]
    J --> K[End]
    
    style A fill:#4CAF50,color:#fff
    style G fill:#2196F3,color:#fff
    style K fill:#FF5722,color:#fff
```

## Development Best Practices

| Practice | Description |
|----------|-------------|
| YAML-first configuration | Define agents and tasks in YAML, keep crew classes minimal |
| Use structured output | Use `output_pydantic` for data flowing between tasks |
| Enable memory | For crews benefiting from cross-session learning |
| Sequential vs Hierarchical | Sequential for linear workflows; hierarchical for dynamic delegation |
| Test frequently | Use `crewai test` to evaluate performance |

资料来源：[lib/cli/src/crewai_cli/templates/AGENTS.md](https://github.com/crewAIInc/crewAI/blob/main/lib/cli/src/crewai_cli/templates/AGENTS.md)

## Common CLI Commands

| Command | Description |
|---------|-------------|
| `crewai create crew <name>` | Create a new crew project |
| `crewai run` | Execute the crew |
| `crewai test` | Test crew (2 iterations, gpt-4o-mini default) |
| `crewai test -n 5 -m gpt-4o` | Custom test iterations and model |
| `crewai train -n 5 -f training.json` | Train the crew |
| `crewai reset-memories -a` | Reset all memories |
| `crewai log-tasks-outputs` | Show latest task outputs |

资料来源：[lib/cli/src/crewai_cli/templates/AGENTS.md](https://github.com/crewAIInc/crewAI/blob/main/lib/cli/src/crewai_cli/templates/AGENTS.md)

## Running Your Crew

Execute your crew using the CLI:

```bash
crewai run
```

Or run the main.py file directly:

```bash
python src/my_project/main.py
```

## Customization

### Adding Tools to Agents

```python
@agent
def researcher(self) -> Agent:
    return Agent(
        config=self.agents_config['researcher'],
        verbose=True,
        tools=[SerperDevTool()]  # Add tools here
    )
```

### Setting Custom LLM Providers

Use the `crewai.LLM` class or string shorthand:

```python
llm="openai/gpt-4o"
llm="anthropic/claude-3-sonnet"
```

### Memory and Knowledge

Enable memory in your crew for cross-session learning:

```python
@crew
def crew(self) -> Crew:
    return Crew(
        agents=self.agents,
        tasks=self.tasks,
        memory=True,  # Enable memory
        verbose=True,
    )
```

## Common Pitfalls

| Pitfall | Solution |
|---------|----------|
| Using `ChatOpenAI()` directly | Use `crewai.LLM` or string shorthand |
| Forgetting type hints | Add `# type: ignore[index]` for YAML config access |
| Token limit issues | Set `respect_context_window=True` |
| API throttling | Configure `max_rpm` rate limiting |

资料来源：[lib/cli/src/crewai_cli/templates/AGENTS.md](https://github.com/crewAIInc/crewAI/blob/main/lib/cli/src/crewai_cli/templates/AGENTS.md)

## Next Steps

After completing this Quick Start Guide:

1. Explore [advanced agent configurations](https://docs.crewai.com) for memory, guardrails, and custom LLMs
2. Learn about [Flows](https://docs.crewai.com) for multi-crew orchestration
3. Review [tool integrations](https://github.com/crewAIInc/crewAI/tree/main/lib/crewai-tools) for additional capabilities
4. Join the [Discord community](https://discord.com/invite/X4JWnZnxPb) for support

---

<a id='agents'></a>

## Agents Architecture

### 相关页面

相关主题：[Tasks and Task Management](#tasks), [Crews and Crew Orchestration](#crews), [LLM Providers and Configuration](#llm-providers)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [lib/crewai/src/crewai/agents/agent_builder/base_agent.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/agents/agent_builder/base_agent.py)
- [lib/crewai/src/crewai/agent/core.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/agent/core.py)
- [lib/crewai/src/crewai/agents/crew_agent_executor.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/agents/crew_agent_executor.py)
- [lib/crewai/src/crewai/agents/parser.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/agents/parser.py)
- [lib/crewai/src/crewai/tasks/hallucination_guardrail.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/tasks/hallucination_guardrail.py)
</details>

# Agents Architecture

## Overview

The CrewAI Agents Architecture provides a flexible, modular framework for creating and orchestrating autonomous AI agents. The architecture is designed around the concept of **agents** as independent entities that can collaborate within **crews** to accomplish complex tasks through both autonomous decision-making and structured workflows.

Agents in CrewAI are composed of several key components:

| Component | Purpose |
|-----------|---------|
| **BaseAgent** | Abstract base class defining the agent interface |
| **Agent (Core)** | Concrete agent implementation with LLM integration |
| **CrewAgentExecutor** | Handles agent execution within crew context |
| **Parser** | Processes LLM outputs and extracts actions |
| **Guardrails** | Validates agent outputs for safety and accuracy |

资料来源：[lib/crewai/src/crewai/agents/agent_builder/base_agent.py:1-50]()

## Architecture Diagram

```mermaid
graph TD
    A[User Defined Agent] --> B[BaseAgent]
    B --> C[Agent Core]
    C --> D[CrewAgentExecutor]
    D --> E[Parser]
    E --> F[LLM]
    F --> G[Tool Calls]
    G --> H[Guardrails]
    H --> D
    
    I[Memory] -.-> C
    J[Knowledge] -.-> C
    K[Tools] --> G
```

## Agent Definition

Agents are defined through YAML configuration files and Python decorators. Each agent requires a minimum of three attributes:

```yaml
# config/agents.yaml
researcher:
  role: "Senior Data Researcher"
  goal: "Uncover cutting-edge developments in {topic}"
  backstory: >
    You're a seasoned researcher with a knack for uncovering the latest
    developments in {topic}. Known for your ability to find the most relevant
    information and present it in a clear and concise manner.
```

### Core Agent Attributes

| Attribute | Type | Required | Description |
|-----------|------|----------|-------------|
| `role` | string | Yes | Defines the agent's function within the crew |
| `goal` | string | Yes | The specific objective the agent aims to achieve |
| `backstory` | string | Yes | Context that shapes the agent's behavior and decision-making |
| `tools` | List[BaseTool] | No | Tools available to the agent for task execution |
| `verbose` | boolean | No | Enable detailed logging (default: False) |
| `llm` | LLM | No | Custom language model configuration |
| `memory` | boolean | No | Enable short/long-term memory (default: True) |
| `max_iter` | int | No | Maximum iterations before forcing response |
| `max_rpm` | int | No | Rate limiting for API calls |

资料来源：[lib/crewai/src/crewai/agent/core.py:1-100]()

## BaseAgent Class

The `BaseAgent` serves as the foundational abstract class for all agent implementations:

```python
from crewai.agents.agent_builder.base_agent import BaseAgent
from typing import List

class BaseAgent:
    agents: List[BaseAgent]  # Type annotation for crew agents
    
    @property
    def role(self) -> str:
        """Returns the role of the agent"""
        
    @property
    def goal(self) -> str:
        """Returns the goal of the agent"""
        
    @property
    def backstory(self) -> str:
        """Returns the backstory of the agent"""
```

### Key Methods

| Method | Return Type | Description |
|--------|-------------|-------------|
| `execute_task(task, context, tools)` | TaskOutput | Execute a specific task |
| `set_memory_memory(memory)` | None | Configure agent memory |
| `set_verbose(verbose)` | None | Toggle verbose logging |
| `create_agent_executor()` | CrewAgentExecutor | Initialize execution context |

资料来源：[lib/crewai/src/crewai/agents/agent_builder/base_agent.py:50-150]()

## Agent Core Implementation

The core agent implementation provides the main interface for agent behavior:

```python
from crewai import Agent
from crewai_tools import SerperDevTool

@CrewBase
class LatestAiDevelopmentCrew():
    agents: List[BaseAgent]
    
    @agent
    def researcher(self) -> Agent:
        return Agent(
            config=self.agents_config['researcher'],
            verbose=True,
            tools=[SerperDevTool()]
        )
```

### LLM Configuration

Agents can be configured with custom LLM providers:

```python
config=dict(
    llm=dict(
        provider="ollama",
        config=dict(
            model="llama2",
            temperature=0.5,
        ),
    ),
)
```

Supported providers include: `openai`, `anthropic`, `google`, `ollama`, `azure`, `bedrock`

资料来源：[lib/crewai/src/crewai/agent/core.py:100-200]()

## CrewAgentExecutor

The `CrewAgentExecutor` manages agent execution within a crew context, handling:

- Task delegation and execution flow
- Tool invocation and result processing
- Guardrail validation
- Response formatting

```mermaid
graph LR
    A[Task Assigned] --> B[Execute with Tools]
    B --> C{Guardrails Check}
    C -->|Pass| D[Return Result]
    C -->|Fail| E[Retry or Fallback]
```

### Execution Parameters

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `task` | Task | Required | The task to execute |
| `context` | str | None | Shared context from previous tasks |
| `tools` | List[BaseTool] | [] | Tools available for this execution |

资料来源：[lib/crewai/src/crewai/agents/crew_agent_executor.py:1-100]()

## Parser

The Parser component processes LLM outputs and extracts structured actions:

```python
from crewai.agents.parser import CrewAgentParser

parser = CrewAgentParser()
result = parser.parse(llm_output)
```

### Parser Responsibilities

| Responsibility | Description |
|----------------|-------------|
| **Action Extraction** | Identify tool calls from LLM responses |
| **Format Normalization** | Convert LLM output to standardized format |
| **Error Handling** | Manage malformed outputs gracefully |
| **Validation** | Ensure parsed actions match expected schemas |

资料来源：[lib/crewai/src/crewai/agents/parser.py:1-80]()

## Guardrails

Guardrails provide validation layers for agent outputs. The framework includes built-in guardrails:

### HallucinationGuardrail

Validates that agent outputs are faithful to provided context:

```python
from crewai.tasks.hallucination_guardrail import HallucinationGuardrail

guardrail = HallucinationGuardrail(
    llm=agent.llm,
    context="Reference document content",
    threshold=7.0,
    tool_response="API response data"
)
```

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `llm` | LLM | Required | Language model for evaluation |
| `context` | str | None | Reference context for validation |
| `threshold` | float | None | Minimum faithfulness score |
| `tool_response` | str | "" | Tool response for additional context |

资料来源：[lib/crewai/src/crewai/tasks/hallucination_guardrail.py:1-80]()

## Agent Creation with Decorators

CrewAI uses Python decorators for declarative agent definition:

```python
from crewai import Agent, Crew, Task
from crewai.project import CrewBase, agent, crew, task
from typing import List

@CrewBase
class MyCrew():
    """My Crew Description"""
    agents: List[BaseAgent]
    tasks: List[Task]

    @agent
    def researcher(self) -> Agent:
        return Agent(
            config=self.agents_config['researcher'],
            verbose=True,
            tools=[SerperDevTool()]
        )

    @agent
    def reporting_analyst(self) -> Agent:
        return Agent(
            config=self.agents_config['reporting_analyst'],
            verbose=True
        )

    @task
    def research_task(self) -> Task:
        return Task(config=self.tasks_config['research_task'])

    @task
    def reporting_task(self) -> Task:
        return Task(
            config=self.tasks_config['reporting_task'],
            output_file='report.md'
        )

    @crew
    def crew(self) -> Crew:
        return Crew(
            agents=self.agents,
            tasks=self.tasks,
            process=Process.sequential,
            verbose=True
        )
```

## Tool Integration

Agents access external capabilities through tools:

### Built-in Tools

| Tool | Purpose |
|------|---------|
| `SerperDevTool` | Web search functionality |
| `CodeDocsSearchTool` | Search code documentation |
| `DirectorySearchTool` | Search within directories |
| `FileWriterTool` | Write content to files |
| `TavilyExtractorTool` | Extract content from URLs |
| `ApifyActorsTool` | Execute Apify actors |
| `LinkupSearchTool` | Search via Linkup API |

### Tool Configuration

```python
from crewai_tools import SerperDevTool, FileWriterTool

researcher = Agent(
    role="Research Analyst",
    goal="Gather and synthesize information",
    backstory="Expert researcher with access to web search",
    tools=[SerperDevTool(), FileWriterTool()],
    verbose=True
)
```

## Memory and Knowledge

Agents can maintain state across interactions:

### Memory Types

| Type | Scope | Persistence |
|------|-------|-------------|
| **Short-term** | Current session | Session lifetime |
| **Long-term** | Across sessions | Database storage |
| **Entity** | Entity tracking | Automatic extraction |
| **Knowledge** | Domain knowledge | Vector store |

### Memory Configuration

```python
crew = Crew(
    agents=[researcher, analyst],
    tasks=[task1, task2],
    memory=True,           # Enable all memory types
    embedder={
        "provider": "openai",
        "config": {"model": "text-embedding-ada-002"}
    }
)
```

## Execution Flow

```mermaid
sequenceDiagram
    participant User
    participant Crew
    participant Agent
    participant Executor
    participant LLM
    participant Tool
    
    User->>Crew: kickoff()
    Crew->>Agent: execute_task(task)
    Agent->>Executor: run()
    Executor->>LLM: generate_response()
    LLM->>Tool: tool_call()
    Tool-->>LLM: result
    LLM-->>Executor: response
    Executor->>Executor: validate_guardrails()
    Executor-->>Agent: TaskOutput
    Agent-->>Crew: result
    Crew-->>User: final_output
```

## Best Practices

### Agent Design

1. **Clear Role Definition**: Define distinct, non-overlapping roles for each agent
2. **Specific Goals**: Ensure each agent has a well-defined, achievable goal
3. **Rich Backstory**: Provide context that guides agent behavior appropriately
4. **Appropriate Tools**: Grant only necessary tools to minimize unnecessary complexity

### Configuration Guidelines

| Aspect | Recommendation |
|--------|----------------|
| **Verbose Mode** | Enable during development, disable in production |
| **Rate Limiting** | Set `max_rpm` to avoid API throttling |
| **Context Window** | Use `respect_context_window=True` for long conversations |
| **Iterations** | Set `max_iter` to prevent infinite loops |

## CLI Commands for Agents

```bash
# Create new agent
crewai create agent <name>

# Test agent
crewai test -n 5 -m gpt-4o

# Reset memories
crewai reset-memories -a              # All memories
crewai reset-memories -s              # Short-term only
crewai reset-memories -l              # Long-term only
```

## Summary

The CrewAI Agents Architecture provides a comprehensive framework for building multi-agent systems:

- **BaseAgent** defines the interface all agents must implement
- **Agent Core** provides the concrete implementation with LLM integration
- **CrewAgentExecutor** manages execution within crew context
- **Parser** handles LLM output processing
- **Guardrails** ensure output quality and safety
- **Decorators** enable declarative agent definition
- **Tools** extend agent capabilities beyond LLM-only responses

---

<a id='tasks'></a>

## Tasks and Task Management

### 相关页面

相关主题：[Agents Architecture](#agents), [Crews and Crew Orchestration](#crews)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this documentation:

- [lib/crewai/src/crewai/task.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/task.py)
- [lib/crewai/src/crewai/tasks/__init__.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/tasks/__init__.py)
- [lib/crewai/src/crewai/tasks/conditional_task.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/tasks/conditional_task.py)
- [lib/crewai/src/crewai/tasks/task_output.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/tasks/task_output.py)
- [lib/cli/src/crewai_cli/templates/AGENTS.md](https://github.com/crewAIInc/crewAI/blob/main/lib/cli/src/crewai_cli/templates/AGENTS.md)
- [lib/cli/src/crewai_cli/templates/flow/README.md](https://github.com/crewAIInc/crewAI/blob/main/lib/cli/src/crewai_cli/templates/flow/README.md)
</details>

# Tasks and Task Management

## Overview

Tasks are the fundamental unit of work in the CrewAI framework. They represent discrete units of work that agents execute within a crew. Each task encapsulates a description of what needs to be accomplished, the expected output format, and optional configurations for output validation, file handling, and dependency management.

Tasks serve as the bridge between agent capabilities and crew objectives, enabling complex multi-agent workflows through declarative configuration and structured output handling. The task management system provides both synchronous execution (via `Task`) and conditional execution (via `ConditionalTask`) to support various workflow patterns.

资料来源：[lib/crewai/src/crewai/task.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/task.py) and [lib/crewai/src/crewai/tasks/__init__.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/tasks/__init__.py)

---

## Core Task Components

### Task Class

The `Task` class is the primary implementation for task definitions in CrewAI. It provides a comprehensive set of attributes to configure task behavior.

```python
class Task(BaseModel):
    description: str                          # Human-readable task description
    expected_output: str                      # Expected output format/content
    agent: Optional[BaseAgent]                # Assigned agent for execution
    crew: Optional[Crew]                      # Parent crew reference
    output_file: Optional[str]                # Optional file path for output
    output_pydantic: Optional[BaseModel]      # Structured output schema
    output_json: Optional[type[BaseModel]]    # JSON output schema
    async_execution: Optional[bool]           # Enable async execution
    context: Optional[List[Task]]             # Tasks whose output this depends on
    config: Optional[dict]                    # Task-specific configuration
    tools: Optional[List[Any]]                # Tools available to the task
```

资料来源：[lib/crewai/src/crewai/task.py:1-50](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/task.py)

### Task Configuration Parameters

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `description` | `str` | Yes | - | Human-readable task description |
| `expected_output` | `str` | Yes | - | Expected format/content of output |
| `agent` | `BaseAgent` | No | `None` | Agent assigned to execute task |
| `crew` | `Crew` | No | `None` | Parent crew reference |
| `output_file` | `str` | No | `None` | File path for writing output |
| `output_pydantic` | `BaseModel` | No | `None` | Pydantic model for structured output |
| `output_json` | `type[BaseModel]` | No | `None` | JSON schema for output validation |
| `async_execution` | `bool` | No | `False` | Enable asynchronous execution |
| `context` | `List[Task]` | No | `None` | Dependent tasks for context |
| `config` | `dict` | No | `None` | Additional configuration |
| `tools` | `List[Any]` | No | `None` | Tools available to task |

资料来源：[lib/crewai/src/crewai/task.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/task.py)

---

## Task Output Management

### TaskOutput Class

The `TaskOutput` class encapsulates the result of task execution, providing a standardized structure for storing and accessing task results.

```python
class TaskOutput(BaseModel):
    name: str                    # Task identifier
    description: str             # Task description
    raw_output: Any              # Raw output from agent execution
    pydantic: Optional[BaseModel]  # Structured Pydantic output
    json_dict: Optional[dict]     # JSON dict output
    
    def to_dict(self) -> dict    # Serialize to dictionary
    def save_to_file(self, path: str)  # Write output to file
```

资料来源：[lib/crewai/src/crewai/tasks/task_output.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/tasks/task_output.py)

### Output File Handling

Tasks can automatically write their output to files using the `output_file` parameter:

```python
from crewai import Agent, Task, Crew

reporting_task = Task(
    description="Create a detailed report on AI trends",
    expected_output="A comprehensive markdown report with sections",
    agent=reporting_analyst,
    output_file="report.md"  # Output will be saved to this file
)
```

资料来源：[README.md](https://github.com/crewAIInc/crewAI/blob/main/README.md)

### Structured Output with Pydantic

Tasks can enforce structured output using Pydantic models:

```python
from pydantic import BaseModel
from crewai import Task

class ReportSchema(BaseModel):
    title: str
    sections: List[str]
    conclusion: str

structured_task = Task(
    description="Generate a structured research report",
    expected_output="JSON object with title, sections, and conclusion",
    output_pydantic=ReportSchema
)
```

资料来源：[lib/cli/src/crewai_cli/templates/AGENTS.md](https://github.com/crewAIInc/crewAI/blob/main/lib/cli/src/crewai_cli/templates/AGENTS.md)

---

## Conditional Tasks

### ConditionalTask Class

`ConditionalTask` extends the base `Task` functionality with conditional execution logic. Tasks are only executed when their provided condition function returns `True`.

```python
class ConditionalTask(Task):
    condition: Callable[[], bool]  # Function that determines if task executes
```

资料来源：[lib/crewai/src/crewai/tasks/conditional_task.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/tasks/conditional_task.py)

### Conditional Task Architecture

```mermaid
graph TD
    A[Crew Execution Starts] --> B{ConditionalTask Condition Check}
    B -->|True| C[Execute Task]
    B -->|False| D[Skip Task]
    C --> E[Continue to Next Task]
    D --> E
    E --> F[Crew Execution Completes]
    
    G[ConditionalTask] -->|inherits| H[Base Task Properties]
    G -->|adds| I[condition: Callable]
```

资料来源：[lib/crewai/src/crewai/tasks/conditional_task.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/tasks/conditional_task.py)

### Conditional Task Usage Example

```python
from crewai import Agent, Task, Crew
from crewai.tasks import ConditionalTask

def should_process_data() -> bool:
    # Only process if certain conditions are met
    return len(available_data) > 0

conditional_task = ConditionalTask(
    description="Process incoming data",
    expected_output="Processed data summary",
    agent=data_processor,
    condition=should_process_data
)
```

资料来源：[lib/crewai/src/crewai/tasks/conditional_task.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/tasks/conditional_task.py)

---

## Task Dependencies and Context

### Context-Based Dependencies

Tasks can depend on the output of other tasks through the `context` parameter. This enables sequential workflows where later tasks have access to earlier task results.

```mermaid
graph LR
    A[Research Task] -->|context| B[Analysis Task]
    B -->|context| C[Reporting Task]
    
    A -->|output| D[Research Data]
    D -->|passed as context| B
    B -->|output| E[Analysis Results]
    E -->|passed as context| C
```

资料来源：[lib/crewai/src/crewai/task.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/task.py)

### Defining Task Context

```python
research_task = Task(
    description="Research latest AI developments",
    expected_output="Summary of key findings",
    agent=researcher
)

reporting_task = Task(
    description="Create comprehensive report",
    expected_output="Detailed markdown report",
    agent=reporter,
    context=[research_task]  # This task receives research_task's output
)
```

资料来源：[README.md](https://github.com/crewAIInc/crewAI/blob/main/README.md)

---

## Task Configuration in YAML

### agents.yaml Structure

Tasks are referenced in the YAML configuration files alongside agent definitions:

```yaml
# config/agents.yaml
researcher:
  role: "{topic} Senior Data Researcher"
  goal: "Uncover cutting-edge developments in {topic}"
  backstory: "You're a seasoned researcher..."

reporting_analyst:
  role: "{topic} Reporting Analyst"
  goal: "Create detailed reports based on research findings"
  backstory: "You're a meticulous analyst..."
```

资料来源：[README.md](https://github.com/crewAIInc/crewAI/blob/main/README.md)

### tasks.yaml Structure

```yaml
# config/tasks.yaml
research_task:
  description: >
    Research the latest developments in {topic}. 
    Identify key trends and important information.
  expected_output: >
    A detailed report with key findings about {topic}.
  agent: researcher

reporting_task:
  description: >
    Create a comprehensive report based on research findings
  expected_output: >
    A fully fledged report with main topics, each with a full section.
    Formatted as markdown without code fences
  agent: reporting_analyst
  output_file: report.md
```

资料来源：[README.md](https://github.com/crewAIInc/crewAI/blob/main/README.md)

---

## Declarative Task Definition with Decorators

### Using the @task Decorator

The `@task` decorator provides a declarative way to define tasks within a CrewBase class:

```python
from crewai import Agent, Task, Crew, Process
from crewai.project import CrewBase, agent, crew, task
from typing import List

@CrewBase
class LatestAiDevelopmentCrew():
    agents: List[BaseAgent]
    tasks: List[Task]

    @task
    def research_task(self) -> Task:
        return Task(
            config=self.tasks_config['research_task'],
        )

    @task
    def reporting_task(self) -> Task:
        return Task(
            config=self.tasks_config['reporting_task'],
            output_file='report.md'
        )

    @crew
    def crew(self) -> Crew:
        return Crew(
            agents=self.agents,
            tasks=self.tasks,
            process=Process.sequential,
            verbose=True,
        )
```

资料来源：[README.md](https://github.com/crewAIInc/crewAI/blob/main/README.md)

### Decorator Flow

```mermaid
graph TD
    A[@CrewBase class] --> B[@agent decorator]
    A --> C[@task decorator]
    A --> D[@crew decorator]
    
    B -->|Creates| E[BaseAgent instances]
    C -->|Creates| F[Task instances from YAML]
    D -->|Creates| G[Crew with agents & tasks]
    
    E --> H[Agent collection]
    F --> I[Task collection]
    G --> J[Configured Crew]
```

资料来源：[lib/cli/src/crewai_cli/templates/AGENTS.md](https://github.com/crewAIInc/crewAI/blob/main/lib/cli/src/crewai_cli/templates/AGENTS.md)

---

## Task Execution in Flows

### Flow Integration

Tasks can be integrated into Flow-based workflows using decorators:

```python
from crewai.flow import Flow, listen, start

class ContentCreationFlow(Flow):
    @start()
    def generate_topic(self):
        topic = "AI Agents"
        return topic

    @listen(generate_topic)
    def research(self, topic):
        return research_crew.kickoff(inputs={'topic': topic})
```

资料来源：[lib/cli/src/crewai_cli/templates/flow/README.md](https://github.com/crewAIInc/crewAI/blob/main/lib/cli/src/crewai_cli/templates/flow/README.md)

### Flow Task Architecture

```mermaid
graph LR
    A[start()] --> B[generate_topic]
    B --> C[@listen decorator]
    C --> D[research_crew]
    D --> E[Task Execution]
    
    F[Flow State] -.->|passes to| D
    G[crewai run] -->|invokes| H[Flow Kickoff]
```

资料来源：[lib/cli/src/crewai_cli/templates/flow/README.md](https://github.com/crewAIInc/crewAI/blob/main/lib/cli/src/crewai_cli/templates/flow/README.md)

---

## Task Export and Import

### Module Exports

The tasks module exports the following classes for public use:

```python
# lib/crewai/src/crewai/tasks/__init__.py
from crewai.tasks.task_output import TaskOutput
from crewai.tasks.conditional_task import ConditionalTask
from crewai.task import Task
```

资料来源：[lib/crewai/src/crewai/tasks/__init__.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/tasks/__init__.py)

---

## Best Practices

### Task Design Guidelines

| Practice | Description |
|----------|-------------|
| **Clear descriptions** | Use specific, actionable descriptions that guide the agent |
| **Structured output** | Use `output_pydantic` for tasks that produce structured data |
| **Dependency management** | Use `context` to pass relevant outputs between tasks |
| **File output** | Use `output_file` for persistent results like reports |
| **Conditional execution** | Use `ConditionalTask` for optional workflow branches |

资料来源：[lib/cli/src/crewai_cli/templates/AGENTS.md](https://github.com/crewAIInc/crewAI/blob/main/lib/cli/src/crewai_cli/templates/AGENTS.md)

### Common Patterns

1. **Sequential Processing**: Tasks execute one after another, each receiving context from previous tasks
2. **Parallel Execution**: Multiple independent tasks execute simultaneously with `async_execution=True`
3. **Conditional Branching**: `ConditionalTask` enables dynamic workflow paths based on runtime conditions
4. **Structured Output**: Pydantic models ensure type-safe output handling between tasks and crews

资料来源：[lib/crewai/src/crewai/tasks/conditional_task.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/tasks/conditional_task.py) and [lib/crewai/src/crewai/tasks/task_output.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/tasks/task_output.py)

---

## Summary

The Task and Task Management system in CrewAI provides:

- **Task**: Core unit of work with configurable output handling
- **TaskOutput**: Standardized result container with file persistence
- **ConditionalTask**: Dynamic execution based on runtime conditions
- **Context Dependencies**: Enable sequential workflows with data passing
- **YAML Configuration**: Declarative task definition alongside agents
- **Decorator Syntax**: Clean, Pythonic task definition within CrewBase classes

Together, these components enable complex multi-agent workflows where tasks coordinate to accomplish sophisticated objectives through structured collaboration.

---

<a id='crews'></a>

## Crews and Crew Orchestration

### 相关页面

相关主题：[Agents Architecture](#agents), [Tasks and Task Management](#tasks), [Flows - Event-Driven Workflows](#flows), [LLM Providers and Configuration](#llm-providers)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [lib/crewai/src/crewai/crew.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/crew.py)
- [lib/crewai/src/crewai/process.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/process.py)
- [lib/crewai/src/crewai/agents/step_executor.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/agents/step_executor.py)
- [lib/crewai/src/crewai/utilities/crew/crew_context.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/utilities/crew/crew_context.py)
</details>

# Crews and Crew Orchestration

## Overview

A **Crew** in CrewAI is a collaborative system of autonomous AI agents working together to accomplish complex tasks. Crew orchestration refers to the mechanism by which these agents coordinate, delegate, and execute tasks based on a defined process type.

Crews are the core building blocks for multi-agent automation in CrewAI. They enable sophisticated workflows where multiple specialized agents combine their capabilities to produce results that exceed what any single agent could achieve alone.

The Crew class serves as the central orchestrator, managing agents, tasks, processes, and shared resources like memory and tools. 资料来源：[lib/crewai/src/crewai/crew.py]()

## Crew Architecture

### Core Components

A Crew consists of four primary components that work together to enable collaborative AI task execution:

| Component | Purpose |
|-----------|---------|
| **Agents** | Autonomous AI entities with specific roles, goals, and tool access |
| **Tasks** | Defined work items with descriptions, expected outputs, and assignments |
| **Process** | Orchestration strategy determining how tasks are executed |
| **Memory** | Shared storage for context, learnings, and inter-agent communication |

### Architecture Diagram

```mermaid
graph TD
    A[Crew] --> B[Agents]
    A --> C[Tasks]
    A --> D[Process]
    A --> E[Memory]
    
    B --> B1[Agent 1]
    B --> B2[Agent 2]
    B --> BN[Agent N]
    
    C --> C1[Task 1]
    C --> C2[Task 2]
    C --> CN[Task N]
    
    D --> D1[Sequential]
    D --> D2[Hierarchical]
    
    E --> E1[Short-term]
    E --> E2[Long-term]
    E --> E3[Entity]
    E --> E4[Knowledge]
```

## Process Types

CrewAI supports two primary process types for orchestrating agent collaboration:

### Sequential Process

In the sequential process, tasks are executed one after another in a predefined order. Each task must complete before the next begins. This is ideal for linear workflows where output from one task feeds into the next.

```python
from crewai import Crew, Process

crew = Crew(
    agents=self.agents,
    tasks=self.tasks,
    process=Process.sequential,
    verbose=True,
)
```

**Use Cases:**
- Research pipelines where findings accumulate
- Report generation requiring sequential information gathering
- Data processing chains where each step depends on the previous

资料来源：[lib/cli/src/crewai_cli/templates/crew/README.md]()

### Hierarchical Process

The hierarchical process introduces an automated manager agent that coordinates the crew. The manager delegates tasks, validates results, and ensures proper workflow execution without manual intervention.

```python
from crewai import Crew, Process

crew = Crew(
    agents=self.agents,
    tasks=self.tasks,
    process=Process.hierarchical,
    verbose=True,
)
```

**Use Cases:**
- Complex projects requiring dynamic task delegation
- Scenarios where a manager role naturally exists
- Workflows needing result validation between steps

资料来源：[lib/crewai/README.md]()

### Process Selection Guide

| Criteria | Sequential | Hierarchical |
|----------|------------|--------------|
| Task Dependencies | Fixed order | Dynamic delegation |
| Manager Required | No | Yes (auto-created) |
| Flexibility | Low | High |
| Best For | Linear pipelines | Complex orchestration |
| Overhead | Minimal | Higher due to management |

## Crew Configuration

### Using the @CrewBase Decorator

Crews are defined using Python decorators combined with YAML configuration files. This approach separates concerns between code logic and agent/task definitions.

```python
from crewai import Agent, Crew, Process, Task
from crewai.project import CrewBase, agent, crew, task
from typing import List

@CrewBase
class LatestAiDevelopmentCrew():
    """LatestAiDevelopment crew"""
    agents: List[BaseAgent]
    tasks: List[Task]

    @agent
    def researcher(self) -> Agent:
        return Agent(
            config=self.agents_config['researcher'],
            verbose=True,
            tools=[SerperDevTool()]
        )

    @task
    def research_task(self) -> Task:
        return Task(
            config=self.tasks_config['research_task'],
        )

    @crew
    def crew(self) -> Crew:
        return Crew(
            agents=self.agents,
            tasks=self.tasks,
            process=Process.sequential,
            verbose=True,
        )
```

资料来源：[lib/crewai/README.md]()

### YAML Configuration Structure

#### agents.yaml

```yaml
researcher:
  role: >
    {topic} Senior Data Researcher
  goal: >
    Uncover cutting-edge developments in {topic}
  backstory: >
    You're a seasoned researcher with a knack for uncovering the latest
    developments in {topic}.

reporting_analyst:
  role: >
    {topic} Reporting Analyst
  goal: >
    Create detailed reports based on {topic} data analysis
```

#### tasks.yaml

```yaml
research_task:
  description: >
    Research the latest developments in {topic}
  expected_output: >
    A comprehensive report on {topic} developments
  agent: researcher

reporting_task:
  description: >
    Create a detailed report based on research findings
  expected_output: >
    A fully fleshed report with main topics
  agent: reporting_analyst
```

资料来源：[lib/cli/src/crewai_cli/templates/crew/README.md]()

## Agent Management

### Agent Roles and Responsibilities

Agents within a crew are defined by four key attributes:

| Attribute | Description |
|-----------|-------------|
| **role** | Defines the agent's function within the crew |
| **goal** | The specific objective the agent works toward |
| **backstory** | Context that shapes the agent's behavior and perspective |
| **tools** | Capabilities the agent can use to accomplish tasks |

### Agent Creation Pattern

```python
@agent
def researcher(self) -> Agent:
    return Agent(
        config=self.agents_config['researcher'],
        verbose=True,
        tools=[SerperDevTool()]
    )
```

Agents receive their configuration from YAML and can be augmented with additional tools or settings at the point of creation.

资料来源：[lib/crewai/src/crewai/crew.py]()

## Task Management

### Task Definition

Tasks represent units of work that agents execute. Each task has:

| Property | Purpose |
|----------|---------|
| **description** | What needs to be accomplished |
| **expected_output** | The format and content of deliverables |
| **agent** | Which agent executes the task |
| **output_file** | Optional file for storing results |
| **dependencies** | Tasks that must complete first |

### Task with Output Handling

```python
@task
def reporting_task(self) -> Task:
    return Task(
        config=self.tasks_config['reporting_task'],
        output_file='report.md'
    )
```

### Task Execution Flow

```mermaid
graph LR
    A[Task Created] --> B{Process Type}
    B -->|Sequential| C[Execute in Order]
    B -->|Hierarchical| D[Manager Delegates]
    
    C --> E[Agent 1 Executes]
    E --> F[Agent 2 Executes]
    F --> G[Complete]
    
    D --> H[Manager Assigns Task]
    H --> I[Agent Executes]
    I --> J[Manager Validates]
    J --> K[Complete]
```

## Memory and Context

### Memory Types

Crews can maintain different types of memory to preserve context across executions:

| Memory Type | Scope | Purpose |
|-------------|-------|---------|
| **Short-term** | Current session | Temporary working memory |
| **Long-term** | Across sessions | Persistent learnings |
| **Entity** | Entity tracking | Knowledge graph of entities |
| **Knowledge** | Structured data | Domain-specific grounding |

### Memory Management Commands

```bash
crewai reset-memories -a              # Reset all memories
crewai reset-memories -s              # Short-term only
crewai reset-memories -l              # Long-term only
crewai reset-memories -e              # Entity only
crewai reset-memories -kn             # Knowledge only
crewai reset-memories -akn            # Agent knowledge only
```

资料来源：[lib/cli/src/crewai_cli/templates/AGENTS.md]()

### Crew Context Utilities

The `CrewContext` class provides utilities for managing scope-based context within crews. Scopes allow hierarchical organization of memory and context:

```python
def join_scope_paths(root: str | None, inner: str | None) -> str:
    """
    Combines two scope path components.
    
    Examples:
        join_scope_paths("/crew/test", "/market-trends") -> '/crew/test/market-trends'
        join_scope_paths("/crew/test", None) -> '/crew/test'
    """
```

资料来源：[lib/crewai/src/crewai/utilities/crew/crew_context.py]()

## Execution Flow

### Crew Kickoff

The main entry point for executing a crew is the `kickoff` method:

```python
from latest_ai_development.crew import LatestAiDevelopmentCrew

def run():
    inputs = {'topic': 'AI Agents'}
    LatestAiDevelopmentCrew().crew().kickoff(inputs=inputs)
```

### Step Execution

The `StepExecutor` handles the actual execution of agent steps within the crew context:

```mermaid
sequenceDiagram
    participant Crew
    participant StepExecutor
    participant Agent
    participant Task
    
    Crew->>StepExecutor: Execute Task
    StepExecutor->>Agent: Call Agent with Context
    Agent->>Task: Perform Action
    Task-->>Agent: Return Result
    Agent-->>StepExecutor: Step Output
    StepExecutor-->>Crew: Execution Complete
```

资料来源：[lib/crewai/src/crewai/agents/step_executor.py]()

### Verbose Mode

During development, enable verbose mode to see detailed execution logs:

```python
@crew
def crew(self) -> Crew:
    return Crew(
        agents=self.agents,
        tasks=self.tasks,
        verbose=True,  # Enable for development
    )
```

Disable verbose mode in production for cleaner outputs.

## Crew Execution Options

### Running a Crew

```bash
crewai run                  # Run crew or flow (auto-detects from pyproject.toml)
```

Or directly via Python:

```bash
python src/my_project/main.py
```

### Testing and Training

```bash
crewai test                           # Test crew (default: 2 iterations, gpt-4o-mini)
crewai test -n 5 -m gpt-4o           # Custom iterations and model
crewai train -n 5 -f training.json   # Train crew
```

### Debugging

```bash
crewai log-tasks-outputs              # Show latest task outputs
crewai replay -t <task_id>            # Replay from specific task
```

## Best Practices

### Configuration Guidelines

1. **YAML-first configuration**: Define agents and tasks in YAML, keep crew classes minimal
2. **Use structured output** (`output_pydantic`) for data that flows between tasks or crews
3. **Use guardrails** to validate task outputs programmatically
4. **Enable memory** for crews that benefit from cross-session learning

### Process Selection

| Workflow Type | Recommended Process |
|---------------|---------------------|
| Linear data pipeline | Sequential |
| Research and report | Sequential |
| Multi-agent collaboration | Hierarchical |
| Dynamic task delegation | Hierarchical |
| Complex multi-stage projects | Hierarchical with Flows |

### Performance Considerations

| Setting | Purpose |
|---------|---------|
| `max_rpm` | Rate limiting to avoid API throttling |
| `respect_context_window=True` | Auto-handle token limits |
| `verbose=False` | Reduce logging overhead in production |

资料来源：[lib/cli/src/crewai_cli/templates/AGENTS.md]()

## Common Patterns

### Multi-Crew Orchestration with Flows

For complex pipelines involving multiple crews:

```mermaid
graph TD
    A[Flow Start] --> B[Crew 1]
    B --> C{Condition?}
    C -->|Path A| D[Crew 2]
    C -->|Path B| E[Crew 3]
    D --> F[Output]
    E --> F
```

Use `@start`, `@listen`, and `@router` decorators for complex flow orchestration.

### Crew with Tools

```python
from crewai_tools import SerperDevTool

@agent
def researcher(self) -> Agent:
    return Agent(
        config=self.agents_config['researcher'],
        tools=[SerperDevTool()]  # Attach tools to agent
    )
```

## Summary

The Crew orchestration system in CrewAI provides a flexible framework for coordinating multiple AI agents. Key takeaways:

- **Crews** are the primary unit of multi-agent collaboration
- **Processes** (Sequential/Hierarchical) define how tasks are coordinated
- **Agents** are specialized roles with specific goals and tools
- **Tasks** represent units of work with dependencies and expected outputs
- **Memory** enables context preservation across executions
- **YAML configuration** keeps agent/task definitions separate from code

This architecture enables everything from simple sequential pipelines to complex hierarchical multi-agent systems with dynamic task delegation.

---

<a id='flows'></a>

## Flows - Event-Driven Workflows

### 相关页面

相关主题：[Crews and Crew Orchestration](#crews), [Agents Architecture](#agents)

<details>
<summary>Related Source Files</summary>

The following source files and documentation were used to generate this page:

- [lib/cli/src/crewai_cli/templates/AGENTS.md](https://github.com/crewAIInc/crewAI/blob/main/lib/cli/src/crewai_cli/templates/AGENTS.md)
- [lib/crewai/src/crewai/flow/flow_serializer.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/flow/flow_serializer.py)
- [lib/cli/src/crewai_cli/templates/flow/README.md](https://github.com/crewAIInc/crewAI/blob/main/lib/cli/src/crewai_cli/templates/flow/README.md)
- [lib/crewai/README.md](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/README.md)
- [lib/crewai-tools/src/crewai_tools/tools/invoke_crewai_automation_tool/invoke_crewai_automation_tool.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai-tools/src/crewai_tools/tools/invoke_crewai_automation_tool/invoke_crewai_automation_tool.py)
</details>

# Flows - Event-Driven Workflows

## Overview

Flows in CrewAI provide an event-driven architecture for orchestrating complex, multi-step AI workflows. They enable precise control over execution order, conditional branching, and state management—offering a perfect balance alongside Crew-based autonomous agent orchestration.

Flows are designed for scenarios requiring **sequential execution**, **conditional logic**, **state persistence**, and **event-based triggers**. Unlike Crews that operate autonomously with agents collaborating freely, Flows provide deterministic workflow patterns where execution follows explicit routing rules.

资料来源：[lib/crewai/README.md](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/README.md)

## Core Concepts

### Flow Architecture

A Flow is a Python class that extends the `Flow` base class, decorated with methods that define the workflow graph:

```mermaid
graph TD
    A[Start] --> B[Method A]
    B --> C{Decision}
    C -->|Path 1| D[Method B]
    C -->|Path 2| E[Method C]
    D --> F[End]
    E --> F
```

### Key Components

| Component | Purpose |
|-----------|---------|
| `Flow` | Base class for all flows |
| `@start()` | Marks methods as entry points |
| `@listen()` | Triggers method execution after another completes |
| `@router()` | Implements conditional branching logic |
| `@human_feedback()` | Pauses execution for user input |

资料来源：[lib/cli/src/crewai_cli/templates/AGENTS.md](https://github.com/crewAIInc/crewAI/blob/main/lib/cli/src/crewai_cli/templates/AGENTS.md)

## Flow Execution Model

### Start Methods

Methods decorated with `@start()` execute immediately when the flow begins. Multiple `@start()` decorators can be defined, causing parallel execution:

```python
from crewai.flow.flow import Flow, start, listen

class MyFlow(Flow):
    @start()
    def begin(self):
        return "initial data"

    @start()
    def begin_parallel(self):
        return "parallel data"
```

### Listen Decorators

The `@listen()` decorator binds a method to the completion of another method. The decorated method receives the output of the triggering method as its argument:

```python
from crewai.flow.flow import Flow, start, listen

class ResearchFlow(Flow):
    @start()
    def set_topic(self):
        return "AI Agents"

    @listen(set_topic)
    def do_research(self, topic):
        # self.state.topic is available
        result = ResearchCrew().crew().kickoff(
            inputs={"topic": topic}
        )
        return result.raw
```

资料来源：[lib/cli/src/crewai_cli/templates/AGENTS.md](https://github.com/crewAIInc/crewAI/blob/main/lib/cli/src/crewai_cli/templates/AGENTS.md)

## State Management

### Structured State with Pydantic

Flows support type-safe state management using Pydantic models. Define a state class that inherits from `BaseModel`:

```python
from crewai.flow.flow import Flow, start, listen
from pydantic import BaseModel

class ResearchState(BaseModel):
    topic: str = ""
    research: str = ""
    report: str = ""

class ResearchFlow(Flow[ResearchState]):
    @start()
    def set_topic(self):
        self.state.topic = "AI Agents"

    @listen(set_topic)
    def do_research(self):
        result = ResearchCrew().crew().kickoff(
            inputs={"topic": self.state.topic}
        )
        self.state.research = result.raw
        return self.state.research

    @listen(do_research)
    def write_report(self, research_data):
        self.state.report = f"# Report on {self.state.topic}\n\n{research_data}"
        return self.state.report
```

Benefits of structured state:
- **Type safety** across method boundaries
- **IDE autocompletion** for state fields
- **Validation** of state transitions
- **Persistence** of state between executions

资料来源：[lib/cli/src/crewai_cli/templates/AGENTS.md](https://github.com/crewAIInc/crewAI/blob/main/lib/cli/src/crewai_cli/templates/AGENTS.md)

### State Flow Diagram

```mermaid
graph LR
    A[set_topic] --> B[State Update<br/>topic: "AI Agents"]
    B --> C[do_research]
    C --> D[State Update<br/>research: data]
    D --> E[write_report]
    E --> F[State Update<br/>report: content]
```

## Conditional Routing

### Router Decorator

The `@router()` decorator enables conditional branching based on method output. Routers return string labels that determine which `@listen()` methods execute:

```python
from crewai.flow.flow import Flow, start, listen, router

class DocumentProcessingFlow(Flow):
    @start()
    def receive_document(self):
        return {"type": "image", "path": "/path/to/image.png"}

    @router(receive_document)
    def classify_document(self, doc):
        if doc["type"] == "image":
            return "image_processing"
        elif doc["type"] == "text":
            return "text_processing"
        return "unsupported"

    @listen("image_processing")
    def process_image(self, doc):
        return f"Processed image: {doc['path']}"

    @listen("text_processing")
    def process_text(self, doc):
        return f"Processed text: {doc['path']}"

    @listen("unsupported")
    def handle_unsupported(self, doc):
        return f"Unsupported document type: {doc['type']}"
```

### Routing Flow Diagram

```mermaid
graph TD
    A[receive_document] --> B{classify_document}
    B -->|image_processing| C[process_image]
    B -->|text_processing| D[process_text]
    B -->|unsupported| E[handle_unsupported]
```

资料来源：[lib/cli/src/crewai_cli/templates/AGENTS.md](https://github.com/crewAIInc/crewAI/blob/main/lib/cli/src/crewai_cli/templates/AGENTS.md)

## Event System Integration

### Event-Driven Architecture

Flows integrate with CrewAI's event system to enable reactive execution patterns. The `flow_serializer.py` module provides introspection capabilities for visualizing flow structures:

```python
from crewai.flow.flow_serializer import flow_structure

structure = flow_structure(MyFlow)
print(structure["name"])  # Flow class name
print(structure["methods"])  # All decorated methods
print(structure["edges"])  # Connections between methods
```

### Event Categories

Flows support integration with multiple event categories:

| Category | Description |
|----------|-------------|
| Flow execution | Start, completion, and error events |
| Agent execution | Individual agent state changes |
| Task management | Task lifecycle events |
| Tool usage | Tool invocation events |
| Safety guardrails | Validation and compliance events |

资料来源：[lib/cli/src/crewai_cli/templates/AGENTS.md](https://github.com/crewAIInc/crewAI/blob/main/lib/cli/src/crewai_cli/templates/AGENTS.md)

## Flow API Reference

### Flow Base Class

```python
class Flow[StateType]:
    """Base class for all flows."""
    
    state: StateType  # Typed state instance
    
    def kickoff(self, inputs: dict = None) -> Any:
        """Execute the flow from start methods."""
    
    def kickoff_async(self, inputs: dict = None) -> Any:
        """Execute the flow asynchronously."""
```

### Decorators

| Decorator | Parameters | Returns | Description |
|-----------|------------|---------|-------------|
| `@start()` | - | None | Marks entry point method |
| `@listen()` | method | None | Binds to method completion |
| `@router()` | method | str | Returns routing label |
| `@human_feedback()` | prompt | str | Requests user input |

### Method Information Types

The `flow_serializer.py` module defines `MethodInfo` for introspecting flow methods:

```python
class MethodInfo(TypedDict, total=False):
    name: str
    type: str  # start, listen, router, start_router
    trigger_methods: list[str]
    condition_type: str | None  # AND, OR
    router_paths: list[str]
    has_human_feedback: bool
```

资料来源：[lib/crewai/src/crewai/flow/flow_serializer.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/flow/flow_serializer.py)

## Flow Structure Serialization

### Introspection for UI Rendering

The `flow_structure()` function analyzes a Flow class and returns a JSON-serializable dictionary:

```python
from crewai.flow.flow_serializer import flow_structure

class MyFlow(Flow):
    @start()
    def begin(self):
        return "started"

    @listen(begin)
    def process(self):
        return "done"

structure = flow_structure(MyFlow)
# Returns:
# {
#     "name": "MyFlow",
#     "methods": [...],
#     "edges": [...],
#     "state_schema": {...}
# }
```

This serialization enables CrewAI Studio UI to render visual flow graphs.

资料来源：[lib/crewai/src/crewai/flow/flow_serializer.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/flow/flow_serializer.py)

## Integration with Crews

### Calling Crews from Flows

Flows can invoke Crews for agent-based task execution:

```python
class ResearchFlow(Flow[ResearchState]):
    @start()
    def set_topic(self):
        self.state.topic = "AI Agents"

    @listen(set_topic)
    def do_research(self):
        crew = ResearchCrew().crew()
        result = crew.kickoff(inputs={"topic": self.state.topic})
        self.state.research = result.raw
        return result.raw
```

### Flow-to-Crew Communication

```mermaid
graph TD
    A[Flow Start] --> B[Set Topic]
    B --> C[Crew Kickoff]
    C --> D[Agent 1]
    C --> E[Agent 2]
    D --> F[Task Complete]
    E --> G[Task Complete]
    F --> H[Flow Resume]
    G --> H
    H --> I[Process Results]
```

## Best Practices

### When to Use Flows

| Use Case | Recommendation |
|----------|----------------|
| Linear workflows with clear steps | Sequential Flow |
| Dynamic agent delegation | Hierarchical Crew |
| Multi-crew orchestration | Flow with Crew calls |
| Conditional branching | Router-based Flow |
| Human-in-the-loop | Flow with `@human_feedback()` |

### Design Guidelines

1. **Use structured state (Pydantic models)** over unstructured dicts for type safety
2. **Prefer Flows for multi-crew orchestration** when complex pipelines are needed
3. **Use `@start()` with multiple methods** only when parallel execution is required
4. **Keep router labels descriptive** for maintainable flow graphs
5. **Enable verbose mode during development**, disable in production

资料来源：[lib/cli/src/crewai_cli/templates/AGENTS.md](https://github.com/crewAIInc/crewAI/blob/main/lib/cli/src/crewai_cli/templates/AGENTS.md)

## Running Flows

### CLI Commands

```bash
# Run crew or flow (auto-detects from pyproject.toml)
crewai run

# Legacy flow execution
crewai flow kickoff
```

### Programmatic Execution

```python
from my_flow import ResearchFlow

flow = ResearchFlow()
result = flow.kickoff(inputs={"topic": "AI Agents"})
print(result)
```

资料来源：[lib/cli/src/crewai_cli/templates/flow/README.md](https://github.com/crewAIInc/crewAI/blob/main/lib/cli/src/crewai_cli/templates/flow/README.md)

## Advanced Patterns

### Multi-Crew Orchestration

```python
class OrchestrationFlow(Flow):
    @start()
    def initialize(self):
        return {"task": "complex_research"}

    @listen(initialize)
    def research_crew_execution(self, task):
        return ResearchCrew().crew().kickoff(inputs=task)

    @listen(research_crew_execution)
    def analysis_crew_execution(self, research_results):
        return AnalysisCrew().crew().kickoff(
            inputs={"data": research_results}
        )

    @listen(analysis_crew_execution)
    def reporting(self, analysis):
        return ReportCrew().crew().kickoff(
            inputs={"analysis": analysis}
        )
```

### Error Handling in Flows

```python
class ResilientFlow(Flow):
    @start()
    def begin(self):
        try:
            return risky_operation()
        except Exception as e:
            self.state.error = str(e)
            return "error_state"

    @router(begin)
    def handle_result(self, result):
        if result == "error_state":
            return "error_handler"
        return "success_path"

    @listen("error_handler")
    def handle_error(self, _):
        return "Recovery action completed"
```

## Summary

Flows provide a powerful event-driven workflow system for CrewAI that complements the autonomous agent orchestration of Crews. Key takeaways:

- **Decorators** (`@start`, `@listen`, `@router`, `@human_feedback`) define the workflow graph
- **Structured state** with Pydantic ensures type safety and validation
- **Event serialization** enables visual flow editing in CrewAI Studio
- **Crews integration** allows delegating complex tasks to agent teams
- **Conditional routing** provides flexible decision-making capabilities

Flows are ideal for precise, deterministic workflows where execution order and branching logic are critical, while Crews excel at autonomous multi-agent collaboration.

---

<a id='llm-providers'></a>

## LLM Providers and Configuration

### 相关页面

相关主题：[Agents Architecture](#agents)

<details>
<summary>Relevant Source Files</summary>

以下源码文件用于生成本页说明：

- [lib/crewai/src/crewai/llm.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/llm.py)
- [lib/crewai/src/crewai/llms/__init__.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/llms/__init__.py)
- [lib/crewai/src/crewai/llms/base_llm.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/llms/base_llm.py)
- [lib/crewai/src/crewai/llms/providers/openai/completion.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/llms/providers/openai/completion.py)
- [lib/crewai/src/crewai/llms/providers/anthropic/completion.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/llms/providers/anthropic/completion.py)
- [lib/crewai-tools/src/crewai_tools/tools/code_docs_search_tool/README.md](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai-tools/src/crewai_tools/tools/code_docs_search_tool/README.md)
- [lib/crewai-tools/src/crewai_tools/tools/pdf_search_tool/README.md](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai-tools/src/crewai_tools/tools/pdf_search_tool/README.md)
- [lib/crewai/src/crewai/tasks/hallucination_guardrail.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/tasks/hallucination_guardrail.py)
</details>

# LLM Providers and Configuration

## Overview

The LLM (Large Language Model) Providers and Configuration system in CrewAI provides a flexible, extensible architecture for integrating multiple AI model providers into the agent execution pipeline. This system allows developers to configure, customize, and switch between different LLM backends while maintaining a consistent interface for agent operations.

The configuration system supports multiple providers including OpenAI, Anthropic, Google, Ollama, and Llama2, enabling both embedding and summarization capabilities through a unified config dictionary approach.

资料来源：[lib/crewai-tools/src/crewai_tools/tools/code_docs_search_tool/README.md]()

## Architecture

The LLM provider system follows a modular architecture with the following components:

```mermaid
graph TD
    A[Agent] --> B[LLM Configuration]
    B --> C[Provider Selection]
    C --> D[OpenAI Provider]
    C --> E[Anthropic Provider]
    C --> F[Google Provider]
    C --> G[Ollama Provider]
    C --> H[Llama2 Provider]
    D --> I[Model Execution]
    E --> I
    F --> I
    G --> I
    H --> I
    I --> J[Response Processing]
    J --> K[Agent Output]
```

### Core Components

| Component | Purpose | Location |
|-----------|---------|----------|
| `LLM` | Main LLM interface class | `lib/crewai/src/crewai/llm.py` |
| `BaseLLM` | Abstract base for all providers | `lib/crewai/src/crewai/llms/base_llm.py` |
| `Providers` | Provider-specific implementations | `lib/crewai/src/crewai/llms/providers/` |
| Config Dictionary | Runtime configuration | User-defined |

资料来源：[lib/crewai/src/crewai/llm.py](), [lib/crewai/src/crewai/llms/base_llm.py]()

## Configuration Pattern

### Standard Configuration Structure

All tools and agents using LLM configuration follow a standardized config dictionary pattern:

```python
config=dict(
    llm=dict(
        provider="provider_name",
        config=dict(
            model="model_name",
            # Optional parameters
            temperature=0.5,
            top_p=1,
            stream=True,
        ),
    ),
    embedder=dict(
        provider="embedder_provider",
        config=dict(
            model="embedding_model",
            task_type="retrieval_document",
        ),
    ),
)
```

资料来源：[lib/crewai-tools/src/crewai_tools/tools/code_docs_search_tool/README.md](), [lib/crewai-tools/src/crewai_tools/tools/pdf_search_tool/README.md]()

### Supported Providers

| Provider | Provider ID | Example Model |
|----------|-------------|---------------|
| OpenAI | `openai` | `gpt-4`, `gpt-4o-mini` |
| Anthropic | `anthropic` | `claude-3`, `claude-3.5-sonnet` |
| Google | `google` | `models/embedding-001` |
| Ollama | `ollama` | `llama2`, `mistral` |
| Llama2 | `llama2` | `meta/llama2` |

资料来源：[lib/crewai-tools/src/crewai_tools/tools/code_docs_search_tool/README.md]()

## LLM Class Integration

### Initialization Parameters

The primary `LLM` class serves as the main interface for language model operations:

```python
from crewai import LLM

llm = LLM(
    model="gpt-4",
    api_key="your-api-key",
    temperature=0.7,
)
```

### Guardrail Integration

LLMs are used as dependencies in guardrail implementations such as the `HallucinationGuardrail`:

```python
from crewai.tasks.hallucination_guardrail import HallucinationGuardrail

guardrail = HallucinationGuardrail(
    llm=agent.llm,
    threshold=8.0,
    context="Reference context for validation",
)
```

资料来源：[lib/crewai/src/crewai/tasks/hallucination_guardrail.py:1-70]()

## Provider-Specific Configuration

### OpenAI Configuration

```python
tool = SomeTool(
    config=dict(
        llm=dict(
            provider="openai",
            config=dict(
                model="gpt-4o-mini",
                temperature=0.5,
                # streaming support available
            ),
        ),
    )
)
```

资料来源：[lib/crewai/src/crewai/llms/providers/openai/completion.py]()

### Anthropic Configuration

```python
tool = SomeTool(
    config=dict(
        llm=dict(
            provider="anthropic",
            config=dict(
                model="claude-3-sonnet-20240229",
            ),
        ),
    )
)
```

资料来源：[lib/crewai/src/crewai/llms/providers/anthropic/completion.py]()

### Google Embeddings Configuration

```python
embedder=dict(
    provider="google",
    config=dict(
        model="models/embedding-001",
        task_type="retrieval_document",
    ),
)
```

资料来源：[lib/crewai-tools/src/crewai_tools/tools/code_docs_search_tool/README.md]()

### Ollama Configuration

```python
llm=dict(
    provider="ollama",
    config=dict(
        model="llama2",
        temperature=0.5,
        top_p=1,
        stream=True,
    ),
)
```

资料来源：[lib/crewai-tools/src/crewai_tools/tools/code_docs_search_tool/README.md]()

## Embedder Configuration

Embedders handle vector embedding generation for retrieval-augmented generation (RAG) workflows:

| Parameter | Type | Description | Default |
|-----------|------|-------------|---------|
| `provider` | string | Embedding provider name | `openai` |
| `model` | string | Model identifier | Provider-specific |
| `task_type` | string | Embedding use case | `retrieval_document` |
| `title` | string | Optional title for embeddings | None |

资料来源：[lib/crewai-tools/src/crewai_tools/tools/code_docs_search_tool/README.md]()

## Default Behavior

By default, tools use OpenAI for both embeddings and summarization:

> By default, the tool uses OpenAI for both embeddings and summarization.

资料来源：[lib/crewai-tools/src/crewai_tools/tools/code_docs_search_tool/README.md](), [lib/crewai-tools/src/crewai_tools/tools/pdf_search_tool/README.md]()

## Configuration Workflow

```mermaid
graph LR
    A[Define Config Dict] --> B[Select Provider]
    B --> C[Specify Model]
    C --> D[Set Optional Params]
    D --> E[Initialize Tool/Agent]
    E --> F[LLM Loaded at Runtime]
    F --> G[Execution with Provider]
```

## Environment Variables

API keys should be configured via environment variables for security:

```bash
export OPENAI_API_KEY="sk-..."
export ANTHROPIC_API_KEY="sk-ant-..."
export GOOGLE_API_KEY="..."
export LINKUP_API_KEY="..."
```

资料来源：[lib/crewai-tools/src/crewai_tools/tools/linkup/README.md]()

## Best Practices

1. **Environment Security**: Store API keys in environment variables rather than hardcoding
2. **Provider Selection**: Choose providers based on task requirements (cost, latency, capabilities)
3. **Temperature Tuning**: Adjust temperature based on task creativity needs (lower for factual, higher for creative)
4. **Model Selection**: Use smaller/faster models for simple tasks to reduce costs
5. **Embedder Consistency**: Use compatible embedders for your vector store

## Related Documentation

- [CrewAI Agents Configuration](agents)
- [CrewAI Tasks Configuration](tasks)
- [Tools Integration Guide](tools)
- [Guardrails System](guardrails)

---

<a id='agent-to-agent'></a>

## Agent-to-Agent (A2A) Communication

### 相关页面

相关主题：[Agents Architecture](#agents), [Crews and Crew Orchestration](#crews)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this documentation:

- [lib/crewai/src/crewai/a2a/__init__.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/a2a/__init__.py)
- [lib/crewai/src/crewai/a2a/types.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/a2a/types.py)
- [lib/crewai/src/crewai/a2a/wrapper.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/a2a/wrapper.py)
- [lib/crewai/src/crewai/a2a/extensions/a2ui/__init__.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/a2a/extensions/a2ui/__init__.py)
- [lib/crewai/src/crewai/a2a/utils/delegation.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/a2a/utils/delegation.py)
- [lib/crewai/src/crewai/a2a/extensions/a2ui/schema/v0_8/server_to_client_with_standard_catalog.json](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/a2a/extensions/a2ui/schema/v0_8/server_to_client_with_standard_catalog.json)
</details>

# Agent-to-Agent (A2A) Communication

Agent-to-Agent (A2A) Communication is a core architectural layer in CrewAI that enables autonomous agents to exchange messages, delegate tasks, and collaborate within multi-agent workflows. This module provides the infrastructure for agents to interact, share context, and coordinate their activities seamlessly.

## Overview

The A2A subsystem in CrewAI implements a standardized communication protocol that allows agents to:

- Exchange structured messages with rich content types
- Delegate tasks to other agents with appropriate context
- Share execution results and artifacts
- Coordinate through hierarchical or collaborative processes

The implementation follows modern agent communication patterns and provides both a programmatic API and extension points for UI integration. 资料来源：[lib/crewai/src/crewai/a2a/__init__.py]()

## Architecture

### High-Level Architecture

```mermaid
graph TD
    subgraph "Agent Layer"
        A1[Agent 1]
        A2[Agent 2]
        A3[Agent N]
    end
    
    subgraph "A2A Core"
        TW[A2A Wrapper]
        TT[A2A Types]
        UD[Utils: Delegation]
    end
    
    subgraph "Extension Layer"
        A2UI[A2UI Extensions]
        SCH[Schema v0.8]
    end
    
    A1 <--> TW
    A2 <--> TW
    A3 <--> TW
    TW <--> TT
    TW <--> UD
    TW <--> A2UI
    A2UI <--> SCH
```

### Component Responsibilities

| Component | Purpose | Key Responsibilities |
|-----------|---------|---------------------|
| `wrapper.py` | A2A Communication Handler | Manages message routing, task delegation, and response handling |
| `types.py` | Data Models | Defines message structures, content types, and protocol elements |
| `delegation.py` | Task Delegation Utility | Provides helper functions for agent delegation patterns |
| `a2ui/` | UI Extensions | Schema definitions for Agent-to-User Interface communication |
| `schema/v0_8/` | Protocol Schemas | JSON schemas for message validation and serialization |

资料来源：[lib/crewai/src/crewai/a2a/wrapper.py]()

## Core Types and Data Models

The A2A module defines comprehensive data models for structured communication between agents. These types ensure type safety and consistent message formats across the system.

### Content Types

The A2A protocol supports multiple content types for flexible message composition:

```mermaid
graph LR
    M[Message] --> T[TextContent]
    M --> A[ArtifactContent]
    M --> T2[TaskContent]
    M --> S[StatusContent]
    M --> P[Part]
    
    T --> TT[Text]
    A --> DT[Document]
    A --> C[Code]
    A --> D[Data]
```

### Message Structure

Messages in A2A communication follow a standardized structure defined in the schema:

```json
{
  "message": {
    "role": "string",
    "content": {
      "parts": []
    },
    "agent": "string",
    "taskId": "string"
  }
}
```

资料来源：[lib/crewai/src/crewai/a2a/types.py]()

## A2A Wrapper

The `A2AWrapper` class serves as the primary interface for agent communication:

```python
class A2AWrapper:
    """Handles Agent-to-Agent communication and delegation."""
    
    def __init__(self, config: A2AConfig):
        self.config = config
        
    def send_message(self, agent_id: str, message: A2AMessage) -> A2AResponse:
        """Send a message to another agent."""
        
    def delegate_task(self, target_agent: str, task: Task) -> DelegationResult:
        """Delegate a task to another agent."""
        
    def receive_message(self, message: A2AMessage) -> None:
        """Process an incoming message from another agent."""
```

### Key Methods

| Method | Parameters | Return Type | Description |
|--------|------------|-------------|-------------|
| `send_message` | `agent_id`, `message` | `A2AResponse` | Send a message to a specific agent |
| `delegate_task` | `target_agent`, `task` | `DelegationResult` | Delegate a task with full context |
| `receive_message` | `message` | `None` | Process incoming messages |
| `get_status` | `task_id` | `TaskStatus` | Get the status of a delegated task |

资料来源：[lib/crewai/src/crewai/a2a/wrapper.py]()

## Task Delegation

The delegation utility provides specialized functions for distributing work across agents:

```python
def delegate_to_agent(
    source_agent: str,
    target_agent: str,
    task: Task,
    context: Dict[str, Any]
) -> DelegationResult:
    """Delegate a task from one agent to another."""
    
def create_delegation_context(
    source: Agent,
    target: Agent,
    task: Task
) -> DelegationContext:
    """Create a context object for delegation."""
```

### Delegation Flow

```mermaid
graph TD
    S[Source Agent] -->|Identifies Task| D1{Delegation Decision}
    D1 -->|Can Delegate| C1[Create Context]
    D1 -->|Cannot Delegate| R1[Reject Task]
    C1 -->|Prepare Message| M1[Build A2A Message]
    M1 -->|Send via Wrapper| TW[A2A Wrapper]
    TW -->|Route Message| T[Target Agent]
    T -->|Execute Task| TR[Task Result]
    TR -->|Send Response| TW2[A2A Wrapper]
    TW2 -->|Route Response| S2[Source Agent]
```

### Delegation Context

The `DelegationContext` object captures all necessary information for proper task delegation:

| Field | Type | Description |
|-------|------|-------------|
| `source_agent` | `str` | Identifier of the delegating agent |
| `target_agent` | `str` | Identifier of the receiving agent |
| `task_id` | `str` | Unique identifier for the task |
| `priority` | `int` | Delegation priority (1-10) |
| `timeout` | `int` | Maximum execution time in seconds |
| `retry_count` | `int` | Number of retry attempts |

资料来源：[lib/crewai/src/crewai/a2a/utils/delegation.py]()

## A2UI Extensions

The A2UI (Agent-to-User Interface) module provides schema definitions for rendering agent outputs in user interfaces:

```python
# Extension initialization
from crewai.a2a.extensions.a2ui import A2UIExtension

extension = A2UIExtension()
extension.register_handlers()
```

### Supported Content Rendering

| Content Type | Description | Schema Reference |
|--------------|-------------|------------------|
| `text` | Plain text with optional hints | `server_to_client_with_standard_catalog.json` |
| `image` | Image content with sizing options | `server_to_client_with_standard_catalog.json` |
| `url` | Web links with metadata | `server_to_client_with_standard_catalog.json` |

### Text Styling Hints

The schema supports the following text style hints for UI rendering:

| Style Hint | Description | Use Case |
|------------|-------------|----------|
| `h1` | Largest heading | Main section titles |
| `h2` | Second largest heading | Subsection titles |
| `h3` | Third largest heading | Minor headings |
| `h4` | Fourth largest heading | Component labels |
| `h5` | Fifth largest heading | Detailed labels |
| `caption` | Small text | Figure captions, footnotes |
| `body` | Standard body text | Regular content |

### Image Rendering Options

Images in A2A messages support the following fit modes:

| Fit Mode | CSS Equivalent | Description |
|----------|----------------|-------------|
| `contain` | `object-fit: contain` | Scale to fit within bounds |
| `cover` | `object-fit: cover` | Scale to fill bounds, crop if needed |
| `fill` | `object-fit: fill` | Stretch to fill bounds |

资料来源：[lib/crewai/src/crewai/a2a/extensions/a2ui/__init__.py]()
资料来源：[lib/crewai/src/crewai/a2a/extensions/a2ui/schema/v0_8/server_to_client_with_standard_catalog.json]()

## Protocol Versioning

The A2A protocol uses semantic versioning with the current implementation supporting **v0.8**:

```mermaid
graph LR
    V08[v0.8] -->|Current| C[Current Schema]
    V08 -->|Features| T[Text Hints]
    V08 -->|Features| I[Image Fit Options]
    V08 -->|Features| U[URL References]
    
    C -->|Evolution| F[Future Versions]
```

Schema files are organized by version in the `schema/` directory, allowing for backward compatibility and gradual migration:

```
lib/crewai/src/crewai/a2a/extensions/a2ui/schema/
└── v0_8/
    └── server_to_client_with_standard_catalog.json
```

## Usage Examples

### Basic Agent Communication

```python
from crewai.a2a import A2AWrapper, A2AMessage, A2AConfig

# Initialize the A2A wrapper
config = A2AConfig(
    agent_id="researcher_01",
    capabilities=["delegate", "respond"]
)
wrapper = A2AWrapper(config)

# Create and send a message
message = A2AMessage(
    role="agent",
    content={
        "parts": [
            {"text": "Please analyze the provided data and return insights"}
        ]
    },
    agent="researcher_01"
)

response = wrapper.send_message(
    agent_id="analyst_01",
    message=message
)
```

### Task Delegation Pattern

```python
from crewai.a2a.utils.delegation import delegate_to_agent, create_delegation_context

# Create delegation context
context = create_delegation_context(
    source=researcher_agent,
    target=analyst_agent,
    task=analysis_task
)

# Execute delegation
result = delegate_to_agent(
    source_agent="researcher_01",
    target_agent="analyst_01",
    task=analysis_task,
    context={"priority": "high", "deadline": "2024-01-15"}
)
```

### UI-Ready Response Structure

```python
from crewai.a2a.extensions.a2ui import create_ui_response

# Create a response optimized for UI rendering
ui_response = create_ui_response(
    content_type="text",
    text="Research findings have been compiled",
    style_hint="body"
)

# Or include rich content
ui_response = create_ui_response(
    content_type="image",
    url={"literalString": "https://example.com/chart.png"},
    fit="contain"
)
```

## Integration with CrewAI

The A2A module integrates with CrewAI's core components:

```mermaid
graph TD
    subgraph "CrewAI Core"
        C[Crew]
        P[Process]
        A[Agents]
        T[Tasks]
    end
    
    subgraph "A2A Layer"
        W[Wrapper]
        D[Delegation Utils]
        U[A2UI]
    end
    
    C -->|Orchestrates| A
    A -->|Communicates via| W
    W -->|Delegates via| D
    W -->|Renders via| U
    A -->|Execute| T
    P -->|Manages Flow| C
```

### Integration Points

| Component | Integration | Description |
|-----------|-------------|-------------|
| `Crew` | Automatic initialization | Creates A2A wrapper for each agent |
| `Agent` | Message handling | Uses A2A for inter-agent communication |
| `Task` | Delegation support | Can be delegated via A2A protocol |
| `Process` | Coordination | Uses A2A for process-level messaging |

## Configuration Options

### A2AConfig Parameters

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `agent_id` | `str` | Required | Unique identifier for the agent |
| `capabilities` | `List[str]` | `[]` | Supported capabilities |
| `timeout` | `int` | `300` | Default timeout in seconds |
| `retry_attempts` | `int` | `3` | Number of retry attempts |
| `enable_ui_extension` | `bool` | `True` | Enable A2UI rendering |

### Environment Variables

| Variable | Description |
|----------|-------------|
| `A2A_TIMEOUT` | Global A2A operation timeout |
| `A2A_MAX_RETRIES` | Maximum retry attempts |
| `A2A_LOG_LEVEL` | Logging verbosity |

## Best Practices

1. **Message Design**: Keep messages focused and atomic for better error handling
2. **Context Preservation**: Always include sufficient context when delegating tasks
3. **Error Handling**: Implement proper exception handling for network failures
4. **Schema Validation**: Validate messages against the A2UI schema before sending
5. **Timeout Management**: Set appropriate timeouts based on task complexity

## Summary

The Agent-to-Agent (A2A) Communication module in CrewAI provides a robust foundation for multi-agent collaboration. Key features include:

- **Standardized messaging** with support for multiple content types
- **Task delegation** with full context preservation
- **UI extensions** for rich content rendering
- **Versioned schemas** ensuring backward compatibility
- **Deep integration** with CrewAI's agent and task systems

The modular architecture allows for flexible extension and customization while maintaining a consistent communication protocol across all agents in a crew.

---

<a id='knowledge'></a>

## Knowledge Management

### 相关页面

相关主题：[Memory and Storage System](#memory)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [lib/crewai/src/crewai/knowledge/knowledge.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/knowledge/knowledge.py)
- [lib/crewai/src/crewai/knowledge/source/pdf_knowledge_source.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/knowledge/source/pdf_knowledge_source.py)
- [lib/crewai/src/crewai/knowledge/source/csv_knowledge_source.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/knowledge/source/csv_knowledge_source.py)
- [lib/crewai/src/crewai/knowledge/storage/knowledge_storage.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/knowledge/storage/knowledge_storage.py)
</details>

# Knowledge Management

## Overview

Knowledge Management in crewAI provides a structured framework for agents to store, retrieve, and utilize contextual information during task execution. This system enables crews to maintain persistent knowledge that can be referenced across multiple agent interactions, enhancing the contextual awareness and accuracy of agent responses.

## Architecture

The Knowledge Management system consists of three primary components working in coordination:

```mermaid
graph TD
    A[Agent] --> B[Knowledge Source]
    B --> C[Knowledge Storage]
    C --> D[Vector Store]
    B --> E[PDF Files]
    B --> F[CSV Files]
    B --> G[Text Data]
    C --> H[Query Engine]
    H --> A
```

### Core Components

| Component | Purpose | Location |
|-----------|---------|----------|
| `Knowledge` | Main class orchestrating knowledge operations | `lib/crewai/src/crewai/knowledge/knowledge.py` |
| `KnowledgeSource` | Abstract base for data ingestion | `lib/crewai/src/crewai/knowledge/source/` |
| `KnowledgeStorage` | Handles persistence and retrieval | `lib/crewai/src/crewai/knowledge/storage/knowledge_storage.py` |

## Knowledge Sources

Knowledge Sources represent the input layer where data is ingested into the system. The framework supports multiple source types to accommodate various data formats.

### PDF Knowledge Source

The PDF Knowledge Source processes PDF documents and extracts textual content for vector storage. It handles multi-page documents and preserves structural information where possible.

**Key Features:**

- Automatic text extraction from PDF pages
- Metadata preservation (page numbers, document titles)
- Chunk-based processing for large documents

### CSV Knowledge Source

The CSV Knowledge Source handles tabular data, converting rows and columns into searchable knowledge entries. It maintains the relationship between column headers and values during ingestion.

**Key Features:**

- Header-aware parsing
- Row-level chunking
- Delimiter detection

## Storage Layer

The Knowledge Storage component manages the persistence of processed knowledge using vector embeddings. It interfaces with the underlying vector database to enable semantic search capabilities.

```mermaid
sequenceDiagram
    participant Source as Knowledge Source
    participant Storage as Knowledge Storage
    participant VectorDB as Vector Database
    participant Query as Query Engine
    
    Source->>Storage: Ingest document chunks
    Storage->>Storage: Generate embeddings
    Storage->>VectorDB: Store vectors + metadata
    Query->>VectorDB: Semantic search
    VectorDB->>Query: Relevant chunks
    Query->>Storage: Format results
```

### Storage Configuration

| Parameter | Type | Description | Default |
|-----------|------|-------------|---------|
| `chunk_size` | int | Size of text chunks in characters | 1000 |
| `chunk_overlap` | int | Overlap between consecutive chunks | 200 |
| `embedding_model` | str | Model used for vectorization | Configured at crew level |

## Integration with Agents

Knowledge Management integrates with the crewAI agent system through the Agent class. Agents can be configured to automatically query relevant knowledge during task execution.

**Basic Integration Pattern:**

```python
from crewai import Agent, Crew
from crewai.knowledge import Knowledge, PDFKnowledgeSource

# Initialize knowledge base
knowledge = Knowledge()

# Add sources
knowledge.add_source(PDFKnowledgeSource(file_path="document.pdf"))
knowledge.add_source(CSVKnowledgeSource(file_path="data.csv"))

# Create agent with knowledge access
agent = Agent(
    role="Research Analyst",
    goal="Answer questions using company knowledge",
    backstory="Expert at analyzing documents",
    knowledge=knowledge
)
```

## Query Mechanism

The query mechanism enables agents to retrieve relevant knowledge based on semantic similarity. When an agent processes a task, the system automatically retrieves chunks that are contextually relevant to the query.

| Query Parameter | Description |
|----------------|-------------|
| `query_text` | The search query string |
| `top_k` | Maximum number of results to return |
| `similarity_threshold` | Minimum similarity score for inclusion |

## Data Flow

```mermaid
graph LR
    A[Document Files] --> B[Knowledge Sources]
    B --> C[Text Chunking]
    C --> D[Embedding Generation]
    D --> E[Vector Storage]
    F[Agent Query] --> G[Similarity Search]
    G --> E
    E --> H[Retrieved Chunks]
    H --> I[Agent Context]
```

## Usage with Crews

For multi-agent crews, knowledge can be shared across all agents or restricted to specific agents:

```python
from crewai import Crew
from crewai.knowledge import Knowledge

# Shared knowledge across crew
crew_knowledge = Knowledge()
crew_knowledge.add_source(company_docs_source)

crew = Crew(
    agents=[researcher, analyst, writer],
    tasks=[research_task, analysis_task, report_task],
    knowledge=crew_knowledge  # Available to all agents
)
```

## Best Practices

1. **Chunk Sizing**: Use appropriate chunk sizes based on document structure. Smaller chunks (500-1000 chars) work well for Q&A, larger chunks for document summarization.
2. **Source Organization**: Group related documents into separate knowledge sources for more targeted retrieval.
3. **Metadata**: Include relevant metadata with knowledge sources to improve result filtering.
4. **Update Strategy**: Implement regular synchronization for knowledge sources that change frequently.

## Related Components

| Component | Purpose |
|-----------|---------|
| `crewai_tools` | External tool integrations including PDF search, CSV search |
| `Agent Memory` | Short-term contextual memory for agent sessions |
| `Task Context` | Task-specific information passing between agents |

---

## References

- Main Knowledge class implementation: `lib/crewai/src/crewai/knowledge/knowledge.py`
- PDF source handler: `lib/crewai/src/crewai/knowledge/source/pdf_knowledge_source.py`
- CSV source handler: `lib/crewai/src/crewai/knowledge/source/csv_knowledge_source.py`
- Storage implementation: `lib/crewai/src/crewai/knowledge/storage/knowledge_storage.py`

---

<a id='memory'></a>

## Memory and Storage System

### 相关页面

相关主题：[Knowledge Management](#knowledge)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [lib/crewai/src/crewai/memory/unified_memory.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/memory/unified_memory.py)
- [lib/crewai/src/crewai/memory/memory_scope.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/memory/memory_scope.py)
- [lib/crewai/src/crewai/memory/recall_flow.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/memory/recall_flow.py)
- [lib/crewai/src/crewai/memory/storage/lancedb_storage.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/memory/storage/lancedb_storage.py)
- [lib/crewai/src/crewai/memory/types.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/memory/types.py)
- [lib/crewai/src/crewai/memory/utils.py](https://github.com/crewAIInc/crewAI/blob/main/lib/crewai/src/crewai/memory/utils.py)
</details>

# Memory and Storage System

## Overview

The crewAI Memory and Storage System provides persistent, searchable memory capabilities for AI agents and crews. It enables cross-session learning, semantic recall of past interactions, and structured storage of agent experiences. The system is designed to handle various types of memory including short-term, long-term, entity, and knowledge-based memories.

```mermaid
graph TD
    A[Agent Request] --> B[UnifiedMemory]
    B --> C[MemoryScope]
    C --> D{Memory Type}
    D --> E[Short-term Memory]
    D --> F[Long-term Memory]
    D --> G[Entity Memory]
    D --> H[Knowledge Memory]
    E --> I[Vector Storage]
    F --> I
    G --> I
    H --> I
    I --> J[Recall Flow]
    J --> K[MemoryMatch Results]
    K --> A
```

## Memory Architecture

### Core Components

| Component | Purpose | Location |
|-----------|---------|----------|
| `UnifiedMemory` | Central interface for all memory operations | `unified_memory.py` |
| `MemoryScope` | Defines isolation boundaries for memory contexts | `memory_scope.py` |
| `RecallFlow` | Handles semantic search and retrieval of memories | `recall_flow.py` |
| `LanceDBStorage` | Vector database backend for persistent storage | `lancedb_storage.py` |

### Data Models

#### MemoryRecord

The fundamental unit of stored information in the memory system:

```python
class MemoryRecord(BaseModel):
    data: Any                           # The actual memory content
    metadata: dict[str, Any]            # Associated metadata
    importance: float = Field(         # Relevance score 0.0-1.0
        default=0.5, ge=0.0, le=1.0
    )
    created_at: datetime                # Creation timestamp
    last_accessed: datetime             # Last retrieval timestamp
    embedding: list[float] | None       # Vector embedding for semantic search
    source: str | None                  # Origin tracking (user ID, session ID)
    private: bool = Field(             # Privacy flag for access control
        default=False
    )
```

资料来源：[lib/crewai/src/crewai/memory/types.py:1-50]()

#### MemoryMatch

Returned by recall operations with relevance scoring:

```python
class MemoryMatch(BaseModel):
    record: MemoryRecord               # The matched memory
    score: float                       # Combined relevance score
    match_reasons: list[str]           # Why this matched (semantic, recency, importance)
    evidence_gaps: list[str]          # Missing context flags
```

资料来源：[lib/crewai/src/crewai/memory/types.py:55-70]()

## Memory Scoping System

The `MemoryScope` class manages hierarchical isolation of memory contexts, allowing different crews, agents, or sessions to maintain separate memory stores while supporting controlled cross-context access.

### Scope Path Operations

| Function | Description |
|----------|-------------|
| `join_scope_paths(root, inner)` | Combines two scope paths with normalization |
| `normalize_scope_path(path)` | Standardizes scope path format |

### Scope Path Format

Scope paths follow a hierarchical structure:

```
/crew/{crew-name}/{memory-type}
/crew/research-crew/short-term
/crew/research-crew/long-term
/crew/research-crew/entity
/crew/research-crew/knowledge
```

### Scope Path Join Behavior

```python
join_scope_paths("/crew/test", "/market-trends")
# Returns: '/crew/test/market-trends'

join_scope_paths("/crew/test", "market-trends")
# Returns: '/crew/test/market-trends'

join_scope_paths("/crew/test", "/")
# Returns: '/crew/test'

join_scope_paths("/crew/test", None)
# Returns: '/crew/test'
```

资料来源：[lib/crewai/src/crewai/memory/utils.py:1-50]()

```mermaid
graph LR
    A["root: '/crew/test'"] --> B[join_scope_paths]
    C["inner: '/market-trends'"] --> B
    B --> D["Result: '/crew/test/market-trends'"]
    
    E["root: '/crew/test'"] --> F[normalize]
    F --> G["Result: '/crew/test'"]
```

## Storage Backends

### LanceDB Storage

LanceDB is the primary vector storage backend, providing efficient similarity search capabilities:

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `db_path` | str | Required | Path to the LanceDB database |
| `table_name` | str | Required | Name of the storage table |
| `vector_dimension` | int | Auto | Embedding vector size |
| `reset_db` | bool | False | Whether to reset on initialization |

资料来源：[lib/crewai/src/crewai/memory/storage/lancedb_storage.py]()

### Storage Operations

| Operation | Description |
|-----------|-------------|
| `write` | Store a new memory record |
| `read` | Retrieve by ID |
| `search` | Semantic similarity search |
| `delete` | Remove by ID |
| `reset` | Clear all records |

## Recall and Retrieval

The `RecallFlow` manages how memories are retrieved based on queries. It combines semantic similarity with recency and importance scoring.

```mermaid
sequenceDiagram
    participant Agent
    participant UnifiedMemory
    participant RecallFlow
    participant LanceDBStorage
    
    Agent->>UnifiedMemory: Query with context
    UnifiedMemory->>RecallFlow: Execute recall(query, scope)
    RecallFlow->>LanceDBStorage: Semantic search
    LanceDBStorage-->>RecallFlow: Candidate memories
    RecallFlow->>RecallFlow: Score by relevance
    RecallFlow-->>UnifiedMemory: Ranked MemoryMatch[]
    UnifiedMemory-->>Agent: Filtered results
```

### Recall Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `query` | str | Yes | Search query text |
| `scope` | str | Yes | Memory scope path |
| `limit` | int | No | Max results (default: 5) |
| `include_private` | bool | No | Include private memories |

## Memory Types

| Type | Purpose | Persistence |
|------|---------|-------------|
| **Short-term** | Current session context | Ephemeral, cleared on reset |
| **Long-term** | Cross-session learning | Persistent until explicitly reset |
| **Entity** | Shared entity information | Persistent, shared across agents |
| **Knowledge** | Domain-specific grounding | Persistent, used for RAG |

## Configuration Options

### Crew-Level Configuration

```yaml
memory:
  enabled: true
  type: "short_term" | "long_term" | "entity" | "knowledge" | "all"
  scope: "/crew/{crew_name}"
```

### CLI Memory Management

```bash
# Reset all memories
crewai reset-memories -a

# Reset specific memory types
crewai reset-memories -s    # Short-term only
crewai reset-memories -l    # Long-term only
crewai reset-memories -e    # Entity only
crewai reset-memories -kn   # Knowledge only
crewai reset-memories -akn  # Agent knowledge only
```

资料来源：[lib/cli/src/crewai_cli/templates/AGENTS.md]()

## Privacy and Access Control

The memory system supports private memories that are only accessible under specific conditions:

- **Private flag**: When `private=True`, a memory is only visible to recall requests from the same source
- **include_private parameter**: Set to `True` to include private memories in cross-source queries
- **Source tracking**: Each memory records its origin via the `source` field for provenance and filtering

## Embedding Configuration

Memories are stored with vector embeddings for semantic search:

| Provider | Model Example | Configuration |
|----------|---------------|---------------|
| OpenAI | `text-embedding-3-small` | `OPENAI_API_KEY` |
| Google | `models/embedding-001` | `GOOGLE_API_KEY` |
| Ollama | `nomic-embed-text` | Local endpoint |
| Azure | `text-embedding-3` | Azure OpenAI config |

资料来源：[lib/crewai-tools/src/crewai_tools/tools/directory_search_tool/README.md]()

## Best Practices

1. **Scope Organization**: Use consistent naming conventions for scope paths to enable efficient cross-crew memory sharing
2. **Importance Scoring**: Set appropriate importance values (0.0-1.0) to influence retrieval ranking
3. **Privacy Handling**: Mark sensitive information with `private=True` to prevent unintended access
4. **Memory Pruning**: Regularly reset short-term memory for clean session boundaries
5. **Embedding Selection**: Choose embedding models appropriate for your content domain

---

---

## Doramagic 踩坑日志

项目：crewAIInc/crewAI

摘要：发现 23 个潜在踩坑项，其中 4 个为 high/blocking；最高优先级：安装坑 - 来源证据：[FEATURE] Implement Process.consensual with a pluggable ConsensusEngine。

## 1. 安装坑 · 来源证据：[FEATURE] Implement Process.consensual with a pluggable ConsensusEngine

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[FEATURE] Implement Process.consensual with a pluggable ConsensusEngine
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_a7c38215ebb04a4fbc6e7c6d2fdb2469 | https://github.com/crewAIInc/crewAI/issues/5708 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 2. 运行坑 · 来源证据：[BUG] Wrong code in document

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：[BUG] Wrong code in document
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_390380af45524e959d558b160597b38b | https://github.com/crewAIInc/crewAI/issues/5378 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 3. 运行坑 · 来源证据：[FEATURE] Enhance the document about @persisit

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：[FEATURE] Enhance the document about @persisit
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_effef000d4cf47a892f17850aa033610 | https://github.com/crewAIInc/crewAI/issues/5372 | 来源类型 github_issue 暴露的待验证使用条件。

## 4. 安全/权限坑 · 来源证据：[FEATURE] GuardrailProvider interface for pre-tool-call authorization

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[FEATURE] GuardrailProvider interface for pre-tool-call authorization
- 对用户的影响：可能阻塞安装或首次运行。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_858a1a8bead2456289d686ec0d2d802c | https://github.com/crewAIInc/crewAI/issues/4877 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 5. 身份坑 · 仓库名和安装名不一致

- 严重度：medium
- 证据强度：runtime_trace
- 发现：仓库名 `crewai` 与安装入口 `skills` 不完全一致。
- 对用户的影响：用户照着仓库名搜索包或照着包名找仓库时容易走错入口。
- 建议检查：在 npm/PyPI/GitHub 上确认包名映射和官方 README 说明。
- 复现命令：`npx skills`
- 防护动作：页面必须同时展示 repo 名和真实安装入口，避免用户搜索错包。
- 证据：identity.distribution | github_repo:710601088 | https://github.com/crewAIInc/crewAI | repo=crewai; install=skills

## 6. 安装坑 · 来源证据：1.14.4

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：1.14.4
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_dcfa2a852812414a82683392c2888795 | https://github.com/crewAIInc/crewAI/releases/tag/1.14.4 | 来源类型 github_release 暴露的待验证使用条件。

## 7. 安装坑 · 来源证据：1.14.4a1

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：1.14.4a1
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_0de86b993ffa4d9298726daa189abf49 | https://github.com/crewAIInc/crewAI/releases/tag/1.14.4a1 | 来源类型 github_release 暴露的待验证使用条件。

## 8. 安装坑 · 来源证据：1.14.5a4

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：1.14.5a4
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_6db6cd94b6ef4bffa23da215458565b4 | https://github.com/crewAIInc/crewAI/releases/tag/1.14.5a4 | 来源类型 github_release 暴露的待验证使用条件。

## 9. 配置坑 · 来源证据：Scans the client database to extract existing policy details.

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Scans the client database to extract existing policy details.
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_8201c73155314e67801bd0b81ea9820d | https://github.com/crewAIInc/crewAI/issues/5760 | 来源类型 github_issue 暴露的待验证使用条件。

## 10. 能力坑 · 能力判断依赖假设

- 严重度：medium
- 证据强度：source_linked
- 发现：README/documentation is current enough for a first validation pass.
- 对用户的影响：假设不成立时，用户拿不到承诺的能力。
- 建议检查：将假设转成下游验证清单。
- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。
- 证据：capability.assumptions | github_repo:710601088 | https://github.com/crewAIInc/crewAI | README/documentation is current enough for a first validation pass.

## 11. 维护坑 · 来源证据：1.14.5a1

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：1.14.5a1
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_c4094bb55c234f1581b9879efd4994c6 | https://github.com/crewAIInc/crewAI/releases/tag/1.14.5a1 | 来源类型 github_release 暴露的待验证使用条件。

## 12. 维护坑 · 维护活跃度未知

- 严重度：medium
- 证据强度：source_linked
- 发现：未记录 last_activity_observed。
- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。
- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。
- 证据：evidence.maintainer_signals | github_repo:710601088 | https://github.com/crewAIInc/crewAI | last_activity_observed missing

## 13. 安全/权限坑 · 下游验证发现风险项

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：下游已经要求复核，不能在页面中弱化。
- 建议检查：进入安全/权限治理复核队列。
- 防护动作：下游风险存在时必须保持 review/recommendation 降级。
- 证据：downstream_validation.risk_items | github_repo:710601088 | https://github.com/crewAIInc/crewAI | no_demo; severity=medium

## 14. 安全/权限坑 · 存在评分风险

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：风险会影响是否适合普通用户安装。
- 建议检查：把风险写入边界卡，并确认是否需要人工复核。
- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。
- 证据：risks.scoring_risks | github_repo:710601088 | https://github.com/crewAIInc/crewAI | no_demo; severity=medium

## 15. 安全/权限坑 · 来源证据：1.14.3

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：1.14.3
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_ff4d292bd8984a039527502ef51aed98 | https://github.com/crewAIInc/crewAI/releases/tag/1.14.3 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 16. 安全/权限坑 · 来源证据：1.14.5a2

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：1.14.5a2
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_0e5616e4bf1f47f59e10e83c1849c86a | https://github.com/crewAIInc/crewAI/releases/tag/1.14.5a2 | 来源类型 github_release 暴露的待验证使用条件。

## 17. 安全/权限坑 · 来源证据：1.14.5a3

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：1.14.5a3
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_ba25d089d674407d83a29ec4caff6284 | https://github.com/crewAIInc/crewAI/releases/tag/1.14.5a3 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 18. 安全/权限坑 · 来源证据：Question: integration path for Agent Threat Rules detection in crewai/security

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Question: integration path for Agent Threat Rules detection in crewai/security
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_05e39d8c109f4ed0a2974d448468229f | https://github.com/crewAIInc/crewAI/issues/5763 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 19. 安全/权限坑 · 来源证据：Security: OWASP Agent Memory Guard – protect CrewAI agents from memory poisoning

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Security: OWASP Agent Memory Guard – protect CrewAI agents from memory poisoning
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_028fe9ebbcc943f5a7134e08d0ed9450 | https://github.com/crewAIInc/crewAI/issues/5762 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 20. 安全/权限坑 · 来源证据：Security: Request to enable Private Vulnerability Reporting / coordinate channel

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Security: Request to enable Private Vulnerability Reporting / coordinate channel
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_e6b9a787eb544f098525817b61476c11 | https://github.com/crewAIInc/crewAI/issues/5728 | 来源类型 github_issue 暴露的待验证使用条件。

## 21. 安全/权限坑 · 来源证据：[FEATURE] Tool to add input_files

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[FEATURE] Tool to add input_files
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_5ca4885df9ee49459ce8502e94d11f50 | https://github.com/crewAIInc/crewAI/issues/5758 | 来源类型 github_issue 暴露的待验证使用条件。

## 22. 维护坑 · issue/PR 响应质量未知

- 严重度：low
- 证据强度：source_linked
- 发现：issue_or_pr_quality=unknown。
- 对用户的影响：用户无法判断遇到问题后是否有人维护。
- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。
- 防护动作：issue/PR 响应未知时，必须提示维护风险。
- 证据：evidence.maintainer_signals | github_repo:710601088 | https://github.com/crewAIInc/crewAI | issue_or_pr_quality=unknown

## 23. 维护坑 · 发布节奏不明确

- 严重度：low
- 证据强度：source_linked
- 发现：release_recency=unknown。
- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。
- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。
- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。
- 证据：evidence.maintainer_signals | github_repo:710601088 | https://github.com/crewAIInc/crewAI | release_recency=unknown

<!-- canonical_name: crewAIInc/crewAI; human_manual_source: deepwiki_human_wiki -->
