mirror of
https://github.com/crewAIInc/crewAI.git
synced 2026-07-02 13:48:09 +00:00
* feat: adopt directory-based docs versioning with Edge channel Switch docs.crewai.com from navigation-only versioning (every version selector entry rendered the same docs/<lang>/* source files) to Mintlify's directory-based versioning so each version selector entry renders its own snapshot. Add an "Edge" channel under docs/edge/<lang>/* that always reflects main HEAD for unreleased work, eliminating pre-release leakage onto frozen release labels. External links to canonical /<lang>/* URLs are preserved via wildcard redirects that always land on the current default version. Layout: - docs/edge/<lang>/* rolling source (you edit here) - docs/edge/enterprise-api.*.yaml - docs/v<X.Y.Z>/<lang>/* frozen, immutable snapshots - docs/v<X.Y.Z>/enterprise-api.*.yaml - docs/images/ shared, append-only - docs/docs.json nav + redirects URLs follow the Mintlify-idiomatic shape: /edge/<lang>/<page> for Edge, /v<X.Y.Z>/<lang>/<page> for every frozen snapshot. The wildcard redirects /<lang>/:slug* -> /<default>/<lang>/:slug* keep stale links working, and every freeze rewrites them (plus all per-section/per-page redirects) so destinations always resolve to the current default without depending on a second redirect hop. Release flow integration (devtools release): - New module crewai_devtools.docs_versioning.freeze() materialises docs/v<X.Y.Z>/ from docs/edge/, rewrites openapi: refs inside the snapshot, inserts the version into every language block in docs.json, and refreshes all redirect destinations. - _update_docs_and_create_pr() in cli.py now calls that freeze during Phase 2 of devtools release. Edge changelogs are updated first (so the snapshot freeze picks them up), then the snapshot is staged alongside docs.json, branched as docs/freeze-v<X.Y.Z>, and the PR is titled [docs-freeze] docs: snapshot and changelog for v<X.Y.Z> — the title prefix the new CI guard reads. - The PR still gates tag, GitHub release, PyPI publish, and the enterprise release as before; no new PRs are added. - Pre-releases (1.X.YaN, 1.X.YbN, ...) skip the snapshot — they ride Edge — and the docs PR title omits the [docs-freeze] prefix. - docs_check (AI-generated docs scaffolding) writes to docs/edge/<lang>/* so newly-generated unreleased docs land in Edge and never accidentally touch a frozen snapshot. Migration scripts (one-shot): - scripts/docs/freeze_historical_versions.py reconstructs all 16 historical snapshots (v1.10.0 .. v1.14.7) from git tags via git archive | tar, rewriting openapi: MDX refs so each snapshot reads its own enterprise-api YAML rather than the live one. - scripts/docs/prefix_version_paths.py one-shot-migrates docs.json: rewrites every page path in 16 versioned blocks to point under docs/v<X.Y.Z>/, inserts a new Edge entry per language, tags v1.14.7 as Latest (default), prunes pages whose target file doesn't exist in the snapshot (e.g. docs/ar/ didn't exist before v1.12.0), and writes the wildcard + per-section redirects. - scripts/docs/freeze_current_edge.py is now a thin CLI wrapper around docs_versioning.freeze for manual one-off freezes (e.g. retroactively snapshotting a forgotten release). CI guards (.github/workflows/docs-snapshots.yml): - Frozen snapshots under docs/v[0-9]*/ are immutable; only PRs whose title contains [docs-freeze] (i.e. release-cut PRs generated by devtools release or the manual wrapper) may modify them. - Images under docs/images/ are append-only since snapshots share a single image directory. Deleting or renaming an image breaks every historical snapshot that still references it. Restored docs/images/crewai-otel-export.png from PR #3673; it was deleted in PR #4908 but v1.10.0 / v1.10.1 snapshots still reference it. Restoring instead of editing the snapshots preserves historical rendering fidelity and validates the new append-only rule retroactively. Tests: - lib/devtools/tests/test_docs_versioning.py covers the freeze: file copy, openapi rewrite, version insertion, default demotion, redirect upserts, per-section redirect rewriting, idempotency, and invalid inputs. Verified locally with mintlify broken-links: 0 broken links across the full site (Edge + 16 frozen versions, 4 locales). AGENTS.md (repo root) is the contributor guide for the new model; RELEASING.md is the release-cut runbook; README's Contribution section links to both. Co-authored-by: Cursor <cursoragent@cursor.com> * style: resolve linter issues --------- Co-authored-by: Cursor <cursoragent@cursor.com>
459 lines
27 KiB
Plaintext
459 lines
27 KiB
Plaintext
---
|
|
title: Crews
|
|
description: Understanding and utilizing crews in the crewAI framework with comprehensive attributes and functionalities.
|
|
icon: people-group
|
|
mode: "wide"
|
|
---
|
|
|
|
## Overview
|
|
|
|
A crew in crewAI represents a collaborative group of agents working together to achieve a set of tasks. Each crew defines the strategy for task execution, agent collaboration, and the overall workflow.
|
|
|
|
## Crew Attributes
|
|
|
|
| Attribute | Parameters | Description |
|
|
| :------------------------------------ | :--------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
| **Tasks** | `tasks` | A list of tasks assigned to the crew. |
|
|
| **Agents** | `agents` | A list of agents that are part of the crew. |
|
|
| **Process** _(optional)_ | `process` | The process flow (e.g., sequential, hierarchical) the crew follows. Default is `sequential`. |
|
|
| **Verbose** _(optional)_ | `verbose` | The verbosity level for logging during execution. Defaults to `False`. |
|
|
| **Manager LLM** _(optional)_ | `manager_llm` | The language model used by the manager agent in a hierarchical process. **Required when using a hierarchical process.** |
|
|
| **Function Calling LLM** _(optional)_ | `function_calling_llm` | If passed, the crew will use this LLM to do function calling for tools for all agents in the crew. Each agent can have its own LLM, which overrides the crew's LLM for function calling. |
|
|
| **Config** _(optional)_ | `config` | Optional configuration settings for the crew, in `Json` or `Dict[str, Any]` format. |
|
|
| **Max RPM** _(optional)_ | `max_rpm` | Maximum requests per minute the crew adheres to during execution. Defaults to `None`. |
|
|
| **Memory** _(optional)_ | `memory` | Utilized for storing execution memories (short-term, long-term, entity memory). | |
|
|
| **Cache** _(optional)_ | `cache` | Specifies whether to use a cache for storing the results of tools' execution. Defaults to `True`. |
|
|
| **Embedder** _(optional)_ | `embedder` | Configuration for the embedder to be used by the crew. Mostly used by memory for now. Default is `{"provider": "openai"}`. |
|
|
| **Step Callback** _(optional)_ | `step_callback` | A function that is called after each step of every agent. This can be used to log the agent's actions or to perform other operations; it won't override the agent-specific `step_callback`. |
|
|
| **Task Callback** _(optional)_ | `task_callback` | A function that is called after the completion of each task. Useful for monitoring or additional operations post-task execution. |
|
|
| **Share Crew** _(optional)_ | `share_crew` | Whether you want to share the complete crew information and execution with the crewAI team to make the library better, and allow us to train models. |
|
|
| **Output Log File** _(optional)_ | `output_log_file` | Set to True to save logs as logs.txt in the current directory or provide a file path. Logs will be in JSON format if the filename ends in .json, otherwise .txt. Defaults to `None`. |
|
|
| **Manager Agent** _(optional)_ | `manager_agent` | `manager` sets a custom agent that will be used as a manager. |
|
|
| **Prompt File** _(optional)_ | `prompt_file` | Path to the prompt JSON file to be used for the crew. |
|
|
| **Planning** *(optional)* | `planning` | Adds planning ability to the Crew. When activated before each Crew iteration, all Crew data is sent to an AgentPlanner that will plan the tasks and this plan will be added to each task description. |
|
|
| **Planning LLM** *(optional)* | `planning_llm` | The language model used by the AgentPlanner in a planning process. |
|
|
| **Knowledge Sources** _(optional)_ | `knowledge_sources` | Knowledge sources available at the crew level, accessible to all the agents. |
|
|
| **Stream** _(optional)_ | `stream` | Enable streaming output to receive real-time updates during crew execution. Returns a `CrewStreamingOutput` object that can be iterated for chunks. Defaults to `False`. |
|
|
| **Chat LLM** _(optional)_ | `chat_llm` | The language model used to orchestrate `crewai chat` CLI interactions with the crew. Accepts a model name string or `LLM` instance. Defaults to `None`. |
|
|
| **Before Kickoff Callbacks** _(optional)_ | `before_kickoff_callbacks` | A list of callable functions executed **before** the crew starts. Each callback receives and can modify the inputs dict. Distinct from the `@before_kickoff` decorator. Defaults to `[]`. |
|
|
| **After Kickoff Callbacks** _(optional)_ | `after_kickoff_callbacks` | A list of callable functions executed **after** the crew finishes. Each callback receives and can modify the `CrewOutput`. Distinct from the `@after_kickoff` decorator. Defaults to `[]`. |
|
|
| **Tracing** _(optional)_ | `tracing` | Controls OpenTelemetry tracing for the crew. `True` = always enable, `False` = always disable, `None` = inherit from environment / user settings. Defaults to `None`. |
|
|
| **Skills** _(optional)_ | `skills` | A list of `Path` objects (skill search directories) or pre-loaded `Skill` objects applied to all agents in the crew. Defaults to `None`. |
|
|
| **Security Config** _(optional)_ | `security_config` | A `SecurityConfig` instance managing crew fingerprinting and identity. Defaults to `SecurityConfig()`. |
|
|
| **Checkpoint** _(optional)_ | `checkpoint` | Enables automatic checkpointing. Pass `True` for sensible defaults, a `CheckpointConfig` for full control, `False` to opt out, or `None` to inherit. See the [Checkpointing](#checkpointing) section below. Defaults to `None`. |
|
|
|
|
<Tip>
|
|
**Crew Max RPM**: The `max_rpm` attribute sets the maximum number of requests per minute the crew can perform to avoid rate limits and will override individual agents' `max_rpm` settings if you set it.
|
|
</Tip>
|
|
|
|
## Creating Crews
|
|
|
|
There are two common ways to create crews in CrewAI: using **JSONC project configuration (recommended for new crews)** or defining them **directly in code**.
|
|
|
|
### JSONC Configuration (Recommended)
|
|
|
|
New projects created with `crewai create crew <name>` use `crew.jsonc` for crew-level settings and tasks, plus one file per agent in `agents/`.
|
|
|
|
`crewai run` automatically detects `crew.jsonc` or `crew.json`, loads the referenced agents, prompts for missing placeholders, and kicks off the crew.
|
|
|
|
#### Example `crew.jsonc`
|
|
|
|
```jsonc crew.jsonc
|
|
{
|
|
"name": "Market Research Crew",
|
|
"agents": ["researcher", "analyst"],
|
|
"tasks": [
|
|
{
|
|
"name": "research",
|
|
"description": "Research {topic} and collect the most relevant facts.",
|
|
"expected_output": "Structured research notes about {topic}.",
|
|
"agent": "researcher"
|
|
},
|
|
{
|
|
"name": "analysis",
|
|
"description": "Analyze the research and write a concise report.",
|
|
"expected_output": "A markdown report with findings and recommendations.",
|
|
"agent": "analyst",
|
|
"context": ["research"],
|
|
"output_file": "output/report.md"
|
|
}
|
|
],
|
|
"process": "sequential",
|
|
"verbose": true,
|
|
"memory": true,
|
|
"inputs": {
|
|
"topic": "AI Agents"
|
|
}
|
|
}
|
|
```
|
|
|
|
Each string in `agents` resolves to `agents/<name>.jsonc` first, then `agents/<name>.json`.
|
|
|
|
```jsonc agents/researcher.jsonc
|
|
{
|
|
"role": "{topic} Senior Researcher",
|
|
"goal": "Find accurate and current information about {topic}.",
|
|
"backstory": "You are a careful researcher who cites clear evidence.",
|
|
"llm": "openai/gpt-4o",
|
|
"tools": ["SerperDevTool"]
|
|
}
|
|
```
|
|
|
|
<Note>
|
|
Tasks run in the order they appear in `tasks` when `process` is `"sequential"`.
|
|
</Note>
|
|
|
|
For hierarchical crews, set `"process": "hierarchical"` and provide either `manager_llm` or `manager_agent`. A `manager_agent` can reference an `agents/<name>.jsonc` file that is not included in the top-level `agents` list.
|
|
|
|
JSON crew definitions support crew-level fields such as `process`, `verbose`, `memory`, `cache`, `max_rpm`, `planning`, `planning_llm`, `manager_llm`, `manager_agent`, `function_calling_llm`, `output_log_file`, `stream`, `tracing`, `before_kickoff_callbacks`, and `after_kickoff_callbacks`.
|
|
|
|
Python callbacks and custom classes use `{"python": "module.attribute"}`. Custom tools use `"custom:<name>"` and load `tools/<name>.py` at runtime.
|
|
|
|
<Warning>
|
|
Only run JSON crew projects from sources you trust. `custom:<name>` tools and `{"python": "module.attribute"}` references execute local Python code when the crew loads.
|
|
</Warning>
|
|
|
|
### Classic Python/YAML Configuration
|
|
|
|
Classic projects created with `crewai create crew <name> --classic` use `crew.py`, `config/agents.yaml`, `config/tasks.yaml`, and the `@CrewBase`, `@agent`, `@task`, and `@crew` decorators. That pattern remains supported and is documented in [Using Annotations](/en/learn/using-annotations).
|
|
|
|
### Direct Code Definition (Alternative)
|
|
|
|
Alternatively, you can define the crew directly in code without using YAML configuration files.
|
|
|
|
```python code
|
|
from crewai import Agent, Crew, Task, Process
|
|
from crewai_tools import YourCustomTool
|
|
|
|
class YourCrewName:
|
|
def agent_one(self) -> Agent:
|
|
return Agent(
|
|
role="Data Analyst",
|
|
goal="Analyze data trends in the market",
|
|
backstory="An experienced data analyst with a background in economics",
|
|
verbose=True,
|
|
tools=[YourCustomTool()]
|
|
)
|
|
|
|
def agent_two(self) -> Agent:
|
|
return Agent(
|
|
role="Market Researcher",
|
|
goal="Gather information on market dynamics",
|
|
backstory="A diligent researcher with a keen eye for detail",
|
|
verbose=True
|
|
)
|
|
|
|
def task_one(self) -> Task:
|
|
return Task(
|
|
description="Collect recent market data and identify trends.",
|
|
expected_output="A report summarizing key trends in the market.",
|
|
agent=self.agent_one()
|
|
)
|
|
|
|
def task_two(self) -> Task:
|
|
return Task(
|
|
description="Research factors affecting market dynamics.",
|
|
expected_output="An analysis of factors influencing the market.",
|
|
agent=self.agent_two()
|
|
)
|
|
|
|
def crew(self) -> Crew:
|
|
return Crew(
|
|
agents=[self.agent_one(), self.agent_two()],
|
|
tasks=[self.task_one(), self.task_two()],
|
|
process=Process.sequential,
|
|
verbose=True
|
|
)
|
|
```
|
|
How to run the above code:
|
|
|
|
```python code
|
|
YourCrewName().crew().kickoff(inputs={})
|
|
```
|
|
|
|
In this example:
|
|
|
|
- Agents and tasks are defined directly within the class without decorators.
|
|
- We manually create and manage the list of agents and tasks.
|
|
- This approach provides more control but can be less maintainable for larger projects.
|
|
|
|
## Crew Output
|
|
|
|
The output of a crew in the CrewAI framework is encapsulated within the `CrewOutput` class.
|
|
This class provides a structured way to access results of the crew's execution, including various formats such as raw strings, JSON, and Pydantic models.
|
|
The `CrewOutput` includes the results from the final task output, token usage, and individual task outputs.
|
|
|
|
### Crew Output Attributes
|
|
|
|
| Attribute | Parameters | Type | Description |
|
|
| :--------------- | :------------- | :------------------------- | :--------------------------------------------------------------------------------------------------- |
|
|
| **Raw** | `raw` | `str` | The raw output of the crew. This is the default format for the output. |
|
|
| **Pydantic** | `pydantic` | `Optional[BaseModel]` | A Pydantic model object representing the structured output of the crew. |
|
|
| **JSON Dict** | `json_dict` | `Optional[Dict[str, Any]]` | A dictionary representing the JSON output of the crew. |
|
|
| **Tasks Output** | `tasks_output` | `List[TaskOutput]` | A list of `TaskOutput` objects, each representing the output of a task in the crew. |
|
|
| **Token Usage** | `token_usage` | `Dict[str, Any]` | A summary of token usage, providing insights into the language model's performance during execution. |
|
|
|
|
### Crew Output Methods and Properties
|
|
|
|
| Method/Property | Description |
|
|
| :-------------- | :------------------------------------------------------------------------------------------------ |
|
|
| **json** | Returns the JSON string representation of the crew output if the output format is JSON. |
|
|
| **to_dict** | Converts the JSON and Pydantic outputs to a dictionary. |
|
|
| \***\*str\*\*** | Returns the string representation of the crew output, prioritizing Pydantic, then JSON, then raw. |
|
|
|
|
### Accessing Crew Outputs
|
|
|
|
Once a crew has been executed, its output can be accessed through the `output` attribute of the `Crew` object. The `CrewOutput` class provides various ways to interact with and present this output.
|
|
|
|
#### Example
|
|
|
|
```python Code
|
|
# Example crew execution
|
|
crew = Crew(
|
|
agents=[research_agent, writer_agent],
|
|
tasks=[research_task, write_article_task],
|
|
verbose=True
|
|
)
|
|
|
|
crew_output = crew.kickoff()
|
|
|
|
# Accessing the crew output
|
|
print(f"Raw Output: {crew_output.raw}")
|
|
if crew_output.json_dict:
|
|
print(f"JSON Output: {json.dumps(crew_output.json_dict, indent=2)}")
|
|
if crew_output.pydantic:
|
|
print(f"Pydantic Output: {crew_output.pydantic}")
|
|
print(f"Tasks Output: {crew_output.tasks_output}")
|
|
print(f"Token Usage: {crew_output.token_usage}")
|
|
```
|
|
|
|
## Accessing Crew Logs
|
|
|
|
You can see real time log of the crew execution, by setting `output_log_file` as a `True(Boolean)` or a `file_name(str)`. Supports logging of events as both `file_name.txt` and `file_name.json`.
|
|
In case of `True(Boolean)` will save as `logs.txt`.
|
|
|
|
In case of `output_log_file` is set as `False(Boolean)` or `None`, the logs will not be populated.
|
|
|
|
```python Code
|
|
# Save crew logs
|
|
crew = Crew(output_log_file = True) # Logs will be saved as logs.txt
|
|
crew = Crew(output_log_file = file_name) # Logs will be saved as file_name.txt
|
|
crew = Crew(output_log_file = file_name.txt) # Logs will be saved as file_name.txt
|
|
crew = Crew(output_log_file = file_name.json) # Logs will be saved as file_name.json
|
|
```
|
|
|
|
|
|
|
|
## Checkpointing
|
|
|
|
Checkpointing lets a crew automatically save its state after key events (e.g. task completion) so that long-running or interrupted runs can be resumed exactly where they left off without re-executing completed tasks.
|
|
|
|
### Quick Start
|
|
|
|
Pass `checkpoint=True` to enable checkpointing with sensible defaults (saves to `.checkpoints/` after every task):
|
|
|
|
```python Code
|
|
from crewai import Crew, Process
|
|
|
|
crew = Crew(
|
|
agents=[researcher, writer],
|
|
tasks=[research_task, write_task],
|
|
process=Process.sequential,
|
|
checkpoint=True, # saves to .checkpoints/ after every task
|
|
)
|
|
|
|
crew.kickoff(inputs={"topic": "AI trends"})
|
|
```
|
|
|
|
### Full Control with `CheckpointConfig`
|
|
|
|
Use `CheckpointConfig` for fine-grained control over location, trigger events, storage backend, and retention:
|
|
|
|
```python Code
|
|
from crewai import Crew, Process
|
|
from crewai.state.checkpoint_config import CheckpointConfig
|
|
|
|
crew = Crew(
|
|
agents=[researcher, writer],
|
|
tasks=[research_task, write_task],
|
|
process=Process.sequential,
|
|
checkpoint=CheckpointConfig(
|
|
location="./.checkpoints", # directory for JSON files (default)
|
|
on_events=["task_completed"], # trigger after each task (default)
|
|
max_checkpoints=5, # keep only the 5 most recent checkpoints
|
|
),
|
|
)
|
|
|
|
crew.kickoff(inputs={"topic": "AI trends"})
|
|
```
|
|
|
|
### Resuming from a Checkpoint
|
|
|
|
Use `Crew.from_checkpoint()` to restore a crew from a saved checkpoint file, then call `kickoff()` to resume:
|
|
|
|
```python Code
|
|
# Resume from the most recent checkpoint
|
|
crew = Crew.from_checkpoint(".checkpoints/latest.json")
|
|
crew.kickoff()
|
|
```
|
|
|
|
<Note>
|
|
When restoring from a checkpoint, `checkpoint_inputs`, `checkpoint_train`, and `checkpoint_kickoff_event_id` are automatically reconstructed — you do not need to set these manually.
|
|
</Note>
|
|
|
|
### `CheckpointConfig` Attributes
|
|
|
|
| Attribute | Type | Default | Description |
|
|
| :----------------- | :------------------------------------- | :------------------- | :-------------------------------------------------------------------------------------------- |
|
|
| `location` | `str` | `"./.checkpoints"` | Storage destination. For `JsonProvider` this is a directory path; for `SqliteProvider` a database file path. |
|
|
| `on_events` | `list[str]` | `["task_completed"]` | Event types that trigger a checkpoint write. Use `["*"]` to checkpoint on every event. |
|
|
| `provider` | `JsonProvider \| SqliteProvider` | `JsonProvider()` | Storage backend. Defaults to `JsonProvider` (plain JSON files). |
|
|
| `max_checkpoints` | `int \| None` | `None` | Maximum checkpoints to keep. Oldest are pruned after each write. `None` keeps all. |
|
|
|
|
## Memory Utilization
|
|
|
|
Crews can utilize memory (short-term, long-term, and entity memory) to enhance their execution and learning over time. This feature allows crews to store and recall execution memories, aiding in decision-making and task execution strategies.
|
|
|
|
## Cache Utilization
|
|
|
|
Caches can be employed to store the results of tools' execution, making the process more efficient by reducing the need to re-execute identical tasks.
|
|
|
|
## Crew Usage Metrics
|
|
|
|
After the crew execution, you can access the `usage_metrics` attribute to view the language model (LLM) usage metrics for all tasks executed by the crew. This provides insights into operational efficiency and areas for improvement.
|
|
|
|
```python Code
|
|
# Access the crew's usage metrics
|
|
crew = Crew(agents=[agent1, agent2], tasks=[task1, task2])
|
|
crew.kickoff()
|
|
print(crew.usage_metrics)
|
|
```
|
|
|
|
## Crew Execution Process
|
|
|
|
- **Sequential Process**: Tasks are executed one after another, allowing for a linear flow of work.
|
|
- **Hierarchical Process**: A manager agent coordinates the crew, delegating tasks and validating outcomes before proceeding. **Note**: A `manager_llm` or `manager_agent` is required for this process and it's essential for validating the process flow.
|
|
|
|
### Kicking Off a Crew
|
|
|
|
Once your crew is assembled, initiate the workflow with the `kickoff()` method. This starts the execution process according to the defined process flow.
|
|
|
|
```python Code
|
|
# Start the crew's task execution
|
|
result = my_crew.kickoff()
|
|
print(result)
|
|
```
|
|
|
|
### Different Ways to Kick Off a Crew
|
|
|
|
Once your crew is assembled, initiate the workflow with the appropriate kickoff method. CrewAI provides several methods for better control over the kickoff process.
|
|
|
|
#### Synchronous Methods
|
|
|
|
- `kickoff()`: Starts the execution process according to the defined process flow.
|
|
- `kickoff_for_each()`: Executes tasks sequentially for each provided input event or item in the collection.
|
|
|
|
#### Asynchronous Methods
|
|
|
|
CrewAI offers two approaches for async execution:
|
|
|
|
| Method | Type | Description |
|
|
|--------|------|-------------|
|
|
| `akickoff()` | Native async | True async/await throughout the entire execution chain |
|
|
| `akickoff_for_each()` | Native async | Native async execution for each input in a list |
|
|
| `kickoff_async()` | Thread-based | Wraps synchronous execution in `asyncio.to_thread` |
|
|
| `kickoff_for_each_async()` | Thread-based | Thread-based async for each input in a list |
|
|
|
|
<Note>
|
|
For high-concurrency workloads, `akickoff()` and `akickoff_for_each()` are recommended as they use native async for task execution, memory operations, and knowledge retrieval.
|
|
</Note>
|
|
|
|
```python Code
|
|
# Start the crew's task execution
|
|
result = my_crew.kickoff()
|
|
print(result)
|
|
|
|
# Example of using kickoff_for_each
|
|
inputs_array = [{'topic': 'AI in healthcare'}, {'topic': 'AI in finance'}]
|
|
results = my_crew.kickoff_for_each(inputs=inputs_array)
|
|
for result in results:
|
|
print(result)
|
|
|
|
# Example of using native async with akickoff
|
|
inputs = {'topic': 'AI in healthcare'}
|
|
async_result = await my_crew.akickoff(inputs=inputs)
|
|
print(async_result)
|
|
|
|
# Example of using native async with akickoff_for_each
|
|
inputs_array = [{'topic': 'AI in healthcare'}, {'topic': 'AI in finance'}]
|
|
async_results = await my_crew.akickoff_for_each(inputs=inputs_array)
|
|
for async_result in async_results:
|
|
print(async_result)
|
|
|
|
# Example of using thread-based kickoff_async
|
|
inputs = {'topic': 'AI in healthcare'}
|
|
async_result = await my_crew.kickoff_async(inputs=inputs)
|
|
print(async_result)
|
|
|
|
# Example of using thread-based kickoff_for_each_async
|
|
inputs_array = [{'topic': 'AI in healthcare'}, {'topic': 'AI in finance'}]
|
|
async_results = await my_crew.kickoff_for_each_async(inputs=inputs_array)
|
|
for async_result in async_results:
|
|
print(async_result)
|
|
```
|
|
|
|
These methods provide flexibility in how you manage and execute tasks within your crew, allowing for both synchronous and asynchronous workflows tailored to your needs. For detailed async examples, see the [Kickoff Crew Asynchronously](/en/learn/kickoff-async) guide.
|
|
|
|
### Streaming Crew Execution
|
|
|
|
For real-time visibility into crew execution, you can enable streaming to receive output as it's generated:
|
|
|
|
```python Code
|
|
# Enable streaming
|
|
crew = Crew(
|
|
agents=[researcher],
|
|
tasks=[task],
|
|
stream=True
|
|
)
|
|
|
|
# Iterate over streaming output
|
|
streaming = crew.kickoff(inputs={"topic": "AI"})
|
|
for chunk in streaming:
|
|
print(chunk.content, end="", flush=True)
|
|
|
|
# Access final result
|
|
result = streaming.result
|
|
```
|
|
|
|
Learn more about streaming in the [Streaming Crew Execution](/en/learn/streaming-crew-execution) guide.
|
|
|
|
### Replaying from a Specific Task
|
|
|
|
You can now replay from a specific task using our CLI command `replay`.
|
|
|
|
The replay feature in CrewAI allows you to replay from a specific task using the command-line interface (CLI). By running the command `crewai replay -t <task_id>`, you can specify the `task_id` for the replay process.
|
|
|
|
Kickoffs will now save the latest kickoffs returned task outputs locally for you to be able to replay from.
|
|
|
|
### Replaying from a Specific Task Using the CLI
|
|
|
|
To use the replay feature, follow these steps:
|
|
|
|
1. Open your terminal or command prompt.
|
|
2. Navigate to the directory where your CrewAI project is located.
|
|
3. Run the following command:
|
|
|
|
To view the latest kickoff task IDs, use:
|
|
|
|
```shell
|
|
crewai log-tasks-outputs
|
|
```
|
|
|
|
Then, to replay from a specific task, use:
|
|
|
|
```shell
|
|
crewai replay -t <task_id>
|
|
```
|
|
|
|
These commands let you replay from your latest kickoff tasks, still retaining context from previously executed tasks.
|