mirror of
https://github.com/crewAIInc/crewAI.git
synced 2026-01-19 21:08:13 +00:00
Merge branch 'main' into lorenze/improve-docs-flows
This commit is contained in:
@@ -254,7 +254,8 @@
|
||||
"pages": [
|
||||
"en/tools/integration/overview",
|
||||
"en/tools/integration/bedrockinvokeagenttool",
|
||||
"en/tools/integration/crewaiautomationtool"
|
||||
"en/tools/integration/crewaiautomationtool",
|
||||
"en/tools/integration/mergeagenthandlertool"
|
||||
]
|
||||
},
|
||||
{
|
||||
|
||||
@@ -307,12 +307,27 @@ 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: `kickoff()`, `kickoff_for_each()`, `kickoff_async()`, and `kickoff_for_each_async()`.
|
||||
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.
|
||||
- `kickoff_async()`: Initiates the workflow asynchronously.
|
||||
- `kickoff_for_each_async()`: Executes tasks concurrently for each provided input event or item, leveraging asynchronous processing.
|
||||
|
||||
#### 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
|
||||
@@ -325,19 +340,30 @@ results = my_crew.kickoff_for_each(inputs=inputs_array)
|
||||
for result in results:
|
||||
print(result)
|
||||
|
||||
# Example of using kickoff_async
|
||||
# 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 kickoff_for_each_async
|
||||
# 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.
|
||||
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
|
||||
|
||||
|
||||
@@ -283,11 +283,54 @@ In this section, you'll find detailed examples that help you select, configure,
|
||||
)
|
||||
```
|
||||
|
||||
**Extended Thinking (Claude Sonnet 4 and Beyond):**
|
||||
|
||||
CrewAI supports Anthropic's Extended Thinking feature, which allows Claude to think through problems in a more human-like way before responding. This is particularly useful for complex reasoning, analysis, and problem-solving tasks.
|
||||
|
||||
```python Code
|
||||
from crewai import LLM
|
||||
|
||||
# Enable extended thinking with default settings
|
||||
llm = LLM(
|
||||
model="anthropic/claude-sonnet-4",
|
||||
thinking={"type": "enabled"},
|
||||
max_tokens=10000
|
||||
)
|
||||
|
||||
# Configure thinking with budget control
|
||||
llm = LLM(
|
||||
model="anthropic/claude-sonnet-4",
|
||||
thinking={
|
||||
"type": "enabled",
|
||||
"budget_tokens": 5000 # Limit thinking tokens
|
||||
},
|
||||
max_tokens=10000
|
||||
)
|
||||
```
|
||||
|
||||
**Thinking Configuration Options:**
|
||||
- `type`: Set to `"enabled"` to activate extended thinking mode
|
||||
- `budget_tokens` (optional): Maximum tokens to use for thinking (helps control costs)
|
||||
|
||||
**Models Supporting Extended Thinking:**
|
||||
- `claude-sonnet-4` and newer models
|
||||
- `claude-3-7-sonnet` (with extended thinking capabilities)
|
||||
|
||||
**When to Use Extended Thinking:**
|
||||
- Complex reasoning and multi-step problem solving
|
||||
- Mathematical calculations and proofs
|
||||
- Code analysis and debugging
|
||||
- Strategic planning and decision making
|
||||
- Research and analytical tasks
|
||||
|
||||
**Note:** Extended thinking consumes additional tokens but can significantly improve response quality for complex tasks.
|
||||
|
||||
**Supported Environment Variables:**
|
||||
- `ANTHROPIC_API_KEY`: Your Anthropic API key (required)
|
||||
|
||||
**Features:**
|
||||
- Native tool use support for Claude 3+ models
|
||||
- Extended Thinking support for Claude Sonnet 4+
|
||||
- Streaming support for real-time responses
|
||||
- Automatic system message handling
|
||||
- Stop sequences for controlled output
|
||||
@@ -305,6 +348,7 @@ In this section, you'll find detailed examples that help you select, configure,
|
||||
|
||||
| Model | Context Window | Best For |
|
||||
|------------------------------|----------------|-----------------------------------------------|
|
||||
| claude-sonnet-4 | 200,000 tokens | Latest with extended thinking capabilities |
|
||||
| claude-3-7-sonnet | 200,000 tokens | Advanced reasoning and agentic tasks |
|
||||
| claude-3-5-sonnet-20241022 | 200,000 tokens | Latest Sonnet with best performance |
|
||||
| claude-3-5-haiku | 200,000 tokens | Fast, compact model for quick responses |
|
||||
@@ -1089,6 +1133,50 @@ CrewAI supports streaming responses from LLMs, allowing your application to rece
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Async LLM Calls
|
||||
|
||||
CrewAI supports asynchronous LLM calls for improved performance and concurrency in your AI workflows. Async calls allow you to run multiple LLM requests concurrently without blocking, making them ideal for high-throughput applications and parallel agent operations.
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Basic Usage">
|
||||
Use the `acall` method for asynchronous LLM requests:
|
||||
|
||||
```python
|
||||
import asyncio
|
||||
from crewai import LLM
|
||||
|
||||
async def main():
|
||||
llm = LLM(model="openai/gpt-4o")
|
||||
|
||||
# Single async call
|
||||
response = await llm.acall("What is the capital of France?")
|
||||
print(response)
|
||||
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
The `acall` method supports all the same parameters as the synchronous `call` method, including messages, tools, and callbacks.
|
||||
</Tab>
|
||||
|
||||
<Tab title="With Streaming">
|
||||
Combine async calls with streaming for real-time concurrent responses:
|
||||
|
||||
```python
|
||||
import asyncio
|
||||
from crewai import LLM
|
||||
|
||||
async def stream_async():
|
||||
llm = LLM(model="openai/gpt-4o", stream=True)
|
||||
|
||||
response = await llm.acall("Write a short story about AI")
|
||||
|
||||
print(response)
|
||||
|
||||
asyncio.run(stream_async())
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Structured LLM Calls
|
||||
|
||||
CrewAI supports structured responses from LLM calls by allowing you to define a `response_format` using a Pydantic model. This enables the framework to automatically parse and validate the output, making it easier to integrate the response into your application without manual post-processing.
|
||||
|
||||
@@ -515,8 +515,7 @@ crew = Crew(
|
||||
"provider": "huggingface",
|
||||
"config": {
|
||||
"api_key": "your-hf-token", # Optional for public models
|
||||
"model": "sentence-transformers/all-MiniLM-L6-v2",
|
||||
"api_url": "https://api-inference.huggingface.co" # or your custom endpoint
|
||||
"model": "sentence-transformers/all-MiniLM-L6-v2"
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
@@ -66,5 +66,55 @@ def my_cache_strategy(arguments: dict, result: str) -> bool:
|
||||
cached_tool.cache_function = my_cache_strategy
|
||||
```
|
||||
|
||||
### Creating Async Tools
|
||||
|
||||
CrewAI supports async tools for non-blocking I/O operations. This is useful when your tool needs to make HTTP requests, database queries, or other I/O-bound operations.
|
||||
|
||||
#### Using the `@tool` Decorator with Async Functions
|
||||
|
||||
The simplest way to create an async tool is using the `@tool` decorator with an async function:
|
||||
|
||||
```python Code
|
||||
import aiohttp
|
||||
from crewai.tools import tool
|
||||
|
||||
@tool("Async Web Fetcher")
|
||||
async def fetch_webpage(url: str) -> str:
|
||||
"""Fetch content from a webpage asynchronously."""
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(url) as response:
|
||||
return await response.text()
|
||||
```
|
||||
|
||||
#### Subclassing `BaseTool` with Async Support
|
||||
|
||||
For more control, subclass `BaseTool` and implement both `_run` (sync) and `_arun` (async) methods:
|
||||
|
||||
```python Code
|
||||
import requests
|
||||
import aiohttp
|
||||
from crewai.tools import BaseTool
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
class WebFetcherInput(BaseModel):
|
||||
"""Input schema for WebFetcher."""
|
||||
url: str = Field(..., description="The URL to fetch")
|
||||
|
||||
class WebFetcherTool(BaseTool):
|
||||
name: str = "Web Fetcher"
|
||||
description: str = "Fetches content from a URL"
|
||||
args_schema: type[BaseModel] = WebFetcherInput
|
||||
|
||||
def _run(self, url: str) -> str:
|
||||
"""Synchronous implementation."""
|
||||
return requests.get(url).text
|
||||
|
||||
async def _arun(self, url: str) -> str:
|
||||
"""Asynchronous implementation for non-blocking I/O."""
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(url) as response:
|
||||
return await response.text()
|
||||
```
|
||||
|
||||
By adhering to these guidelines and incorporating new functionalities and collaboration tools into your tool creation and management processes,
|
||||
you can leverage the full capabilities of the CrewAI framework, enhancing both the development experience and the efficiency of your AI agents.
|
||||
|
||||
@@ -7,17 +7,28 @@ mode: "wide"
|
||||
|
||||
## Introduction
|
||||
|
||||
CrewAI provides the ability to kickoff a crew asynchronously, allowing you to start the crew execution in a non-blocking manner.
|
||||
CrewAI provides the ability to kickoff a crew asynchronously, allowing you to start the crew execution in a non-blocking manner.
|
||||
This feature is particularly useful when you want to run multiple crews concurrently or when you need to perform other tasks while the crew is executing.
|
||||
|
||||
## Asynchronous Crew Execution
|
||||
CrewAI offers two approaches for async execution:
|
||||
|
||||
To kickoff a crew asynchronously, use the `kickoff_async()` method. This method initiates the crew execution in a separate thread, allowing the main thread to continue executing other tasks.
|
||||
| Method | Type | Description |
|
||||
|--------|------|-------------|
|
||||
| `akickoff()` | Native async | True async/await throughout the entire execution chain |
|
||||
| `kickoff_async()` | Thread-based | Wraps synchronous execution in `asyncio.to_thread` |
|
||||
|
||||
<Note>
|
||||
For high-concurrency workloads, `akickoff()` is recommended as it uses native async for task execution, memory operations, and knowledge retrieval.
|
||||
</Note>
|
||||
|
||||
## Native Async Execution with `akickoff()`
|
||||
|
||||
The `akickoff()` method provides true native async execution, using async/await throughout the entire execution chain including task execution, memory operations, and knowledge queries.
|
||||
|
||||
### Method Signature
|
||||
|
||||
```python Code
|
||||
def kickoff_async(self, inputs: dict) -> CrewOutput:
|
||||
async def akickoff(self, inputs: dict) -> CrewOutput:
|
||||
```
|
||||
|
||||
### Parameters
|
||||
@@ -28,23 +39,13 @@ def kickoff_async(self, inputs: dict) -> CrewOutput:
|
||||
|
||||
- `CrewOutput`: An object representing the result of the crew execution.
|
||||
|
||||
## Potential Use Cases
|
||||
|
||||
- **Parallel Content Generation**: Kickoff multiple independent crews asynchronously, each responsible for generating content on different topics. For example, one crew might research and draft an article on AI trends, while another crew generates social media posts about a new product launch. Each crew operates independently, allowing content production to scale efficiently.
|
||||
|
||||
- **Concurrent Market Research Tasks**: Launch multiple crews asynchronously to conduct market research in parallel. One crew might analyze industry trends, while another examines competitor strategies, and yet another evaluates consumer sentiment. Each crew independently completes its task, enabling faster and more comprehensive insights.
|
||||
|
||||
- **Independent Travel Planning Modules**: Execute separate crews to independently plan different aspects of a trip. One crew might handle flight options, another handles accommodation, and a third plans activities. Each crew works asynchronously, allowing various components of the trip to be planned simultaneously and independently for faster results.
|
||||
|
||||
## Example: Single Asynchronous Crew Execution
|
||||
|
||||
Here's an example of how to kickoff a crew asynchronously using asyncio and awaiting the result:
|
||||
### Example: Native Async Crew Execution
|
||||
|
||||
```python Code
|
||||
import asyncio
|
||||
from crewai import Crew, Agent, Task
|
||||
|
||||
# Create an agent with code execution enabled
|
||||
# Create an agent
|
||||
coding_agent = Agent(
|
||||
role="Python Data Analyst",
|
||||
goal="Analyze data and provide insights using Python",
|
||||
@@ -52,37 +53,165 @@ coding_agent = Agent(
|
||||
allow_code_execution=True
|
||||
)
|
||||
|
||||
# Create a task that requires code execution
|
||||
# Create a task
|
||||
data_analysis_task = Task(
|
||||
description="Analyze the given dataset and calculate the average age of participants. Ages: {ages}",
|
||||
agent=coding_agent,
|
||||
expected_output="The average age of the participants."
|
||||
)
|
||||
|
||||
# Create a crew and add the task
|
||||
# Create a crew
|
||||
analysis_crew = Crew(
|
||||
agents=[coding_agent],
|
||||
tasks=[data_analysis_task]
|
||||
)
|
||||
|
||||
# Async function to kickoff the crew asynchronously
|
||||
async def async_crew_execution():
|
||||
result = await analysis_crew.kickoff_async(inputs={"ages": [25, 30, 35, 40, 45]})
|
||||
# Native async execution
|
||||
async def main():
|
||||
result = await analysis_crew.akickoff(inputs={"ages": [25, 30, 35, 40, 45]})
|
||||
print("Crew Result:", result)
|
||||
|
||||
# Run the async function
|
||||
asyncio.run(async_crew_execution())
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
## Example: Multiple Asynchronous Crew Executions
|
||||
### Example: Multiple Native Async Crews
|
||||
|
||||
In this example, we'll show how to kickoff multiple crews asynchronously and wait for all of them to complete using `asyncio.gather()`:
|
||||
Run multiple crews concurrently using `asyncio.gather()` with native async:
|
||||
|
||||
```python Code
|
||||
import asyncio
|
||||
from crewai import Crew, Agent, Task
|
||||
|
||||
coding_agent = Agent(
|
||||
role="Python Data Analyst",
|
||||
goal="Analyze data and provide insights using Python",
|
||||
backstory="You are an experienced data analyst with strong Python skills.",
|
||||
allow_code_execution=True
|
||||
)
|
||||
|
||||
task_1 = Task(
|
||||
description="Analyze the first dataset and calculate the average age. Ages: {ages}",
|
||||
agent=coding_agent,
|
||||
expected_output="The average age of the participants."
|
||||
)
|
||||
|
||||
task_2 = Task(
|
||||
description="Analyze the second dataset and calculate the average age. Ages: {ages}",
|
||||
agent=coding_agent,
|
||||
expected_output="The average age of the participants."
|
||||
)
|
||||
|
||||
crew_1 = Crew(agents=[coding_agent], tasks=[task_1])
|
||||
crew_2 = Crew(agents=[coding_agent], tasks=[task_2])
|
||||
|
||||
async def main():
|
||||
results = await asyncio.gather(
|
||||
crew_1.akickoff(inputs={"ages": [25, 30, 35, 40, 45]}),
|
||||
crew_2.akickoff(inputs={"ages": [20, 22, 24, 28, 30]})
|
||||
)
|
||||
|
||||
for i, result in enumerate(results, 1):
|
||||
print(f"Crew {i} Result:", result)
|
||||
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
### Example: Native Async for Multiple Inputs
|
||||
|
||||
Use `akickoff_for_each()` to execute your crew against multiple inputs concurrently with native async:
|
||||
|
||||
```python Code
|
||||
import asyncio
|
||||
from crewai import Crew, Agent, Task
|
||||
|
||||
coding_agent = Agent(
|
||||
role="Python Data Analyst",
|
||||
goal="Analyze data and provide insights using Python",
|
||||
backstory="You are an experienced data analyst with strong Python skills.",
|
||||
allow_code_execution=True
|
||||
)
|
||||
|
||||
data_analysis_task = Task(
|
||||
description="Analyze the dataset and calculate the average age. Ages: {ages}",
|
||||
agent=coding_agent,
|
||||
expected_output="The average age of the participants."
|
||||
)
|
||||
|
||||
analysis_crew = Crew(
|
||||
agents=[coding_agent],
|
||||
tasks=[data_analysis_task]
|
||||
)
|
||||
|
||||
async def main():
|
||||
datasets = [
|
||||
{"ages": [25, 30, 35, 40, 45]},
|
||||
{"ages": [20, 22, 24, 28, 30]},
|
||||
{"ages": [30, 35, 40, 45, 50]}
|
||||
]
|
||||
|
||||
results = await analysis_crew.akickoff_for_each(datasets)
|
||||
|
||||
for i, result in enumerate(results, 1):
|
||||
print(f"Dataset {i} Result:", result)
|
||||
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
## Thread-Based Async with `kickoff_async()`
|
||||
|
||||
The `kickoff_async()` method provides async execution by wrapping the synchronous `kickoff()` in a thread. This is useful for simpler async integration or backward compatibility.
|
||||
|
||||
### Method Signature
|
||||
|
||||
```python Code
|
||||
async def kickoff_async(self, inputs: dict) -> CrewOutput:
|
||||
```
|
||||
|
||||
### Parameters
|
||||
|
||||
- `inputs` (dict): A dictionary containing the input data required for the tasks.
|
||||
|
||||
### Returns
|
||||
|
||||
- `CrewOutput`: An object representing the result of the crew execution.
|
||||
|
||||
### Example: Thread-Based Async Execution
|
||||
|
||||
```python Code
|
||||
import asyncio
|
||||
from crewai import Crew, Agent, Task
|
||||
|
||||
coding_agent = Agent(
|
||||
role="Python Data Analyst",
|
||||
goal="Analyze data and provide insights using Python",
|
||||
backstory="You are an experienced data analyst with strong Python skills.",
|
||||
allow_code_execution=True
|
||||
)
|
||||
|
||||
data_analysis_task = Task(
|
||||
description="Analyze the given dataset and calculate the average age of participants. Ages: {ages}",
|
||||
agent=coding_agent,
|
||||
expected_output="The average age of the participants."
|
||||
)
|
||||
|
||||
analysis_crew = Crew(
|
||||
agents=[coding_agent],
|
||||
tasks=[data_analysis_task]
|
||||
)
|
||||
|
||||
async def async_crew_execution():
|
||||
result = await analysis_crew.kickoff_async(inputs={"ages": [25, 30, 35, 40, 45]})
|
||||
print("Crew Result:", result)
|
||||
|
||||
asyncio.run(async_crew_execution())
|
||||
```
|
||||
|
||||
### Example: Multiple Thread-Based Async Crews
|
||||
|
||||
```python Code
|
||||
import asyncio
|
||||
from crewai import Crew, Agent, Task
|
||||
|
||||
# Create an agent with code execution enabled
|
||||
coding_agent = Agent(
|
||||
role="Python Data Analyst",
|
||||
goal="Analyze data and provide insights using Python",
|
||||
@@ -90,7 +219,6 @@ coding_agent = Agent(
|
||||
allow_code_execution=True
|
||||
)
|
||||
|
||||
# Create tasks that require code execution
|
||||
task_1 = Task(
|
||||
description="Analyze the first dataset and calculate the average age of participants. Ages: {ages}",
|
||||
agent=coding_agent,
|
||||
@@ -103,22 +231,76 @@ task_2 = Task(
|
||||
expected_output="The average age of the participants."
|
||||
)
|
||||
|
||||
# Create two crews and add tasks
|
||||
crew_1 = Crew(agents=[coding_agent], tasks=[task_1])
|
||||
crew_2 = Crew(agents=[coding_agent], tasks=[task_2])
|
||||
|
||||
# Async function to kickoff multiple crews asynchronously and wait for all to finish
|
||||
async def async_multiple_crews():
|
||||
# Create coroutines for concurrent execution
|
||||
result_1 = crew_1.kickoff_async(inputs={"ages": [25, 30, 35, 40, 45]})
|
||||
result_2 = crew_2.kickoff_async(inputs={"ages": [20, 22, 24, 28, 30]})
|
||||
|
||||
# Wait for both crews to finish
|
||||
results = await asyncio.gather(result_1, result_2)
|
||||
|
||||
for i, result in enumerate(results, 1):
|
||||
print(f"Crew {i} Result:", result)
|
||||
|
||||
# Run the async function
|
||||
asyncio.run(async_multiple_crews())
|
||||
```
|
||||
|
||||
## Async Streaming
|
||||
|
||||
Both async methods support streaming when `stream=True` is set on the crew:
|
||||
|
||||
```python Code
|
||||
import asyncio
|
||||
from crewai import Crew, Agent, Task
|
||||
|
||||
agent = Agent(
|
||||
role="Researcher",
|
||||
goal="Research and summarize topics",
|
||||
backstory="You are an expert researcher."
|
||||
)
|
||||
|
||||
task = Task(
|
||||
description="Research the topic: {topic}",
|
||||
agent=agent,
|
||||
expected_output="A comprehensive summary of the topic."
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[agent],
|
||||
tasks=[task],
|
||||
stream=True # Enable streaming
|
||||
)
|
||||
|
||||
async def main():
|
||||
streaming_output = await crew.akickoff(inputs={"topic": "AI trends in 2024"})
|
||||
|
||||
# Async iteration over streaming chunks
|
||||
async for chunk in streaming_output:
|
||||
print(f"Chunk: {chunk.content}")
|
||||
|
||||
# Access final result after streaming completes
|
||||
result = streaming_output.result
|
||||
print(f"Final result: {result.raw}")
|
||||
|
||||
asyncio.run(main())
|
||||
```
|
||||
|
||||
## Potential Use Cases
|
||||
|
||||
- **Parallel Content Generation**: Kickoff multiple independent crews asynchronously, each responsible for generating content on different topics. For example, one crew might research and draft an article on AI trends, while another crew generates social media posts about a new product launch.
|
||||
|
||||
- **Concurrent Market Research Tasks**: Launch multiple crews asynchronously to conduct market research in parallel. One crew might analyze industry trends, while another examines competitor strategies, and yet another evaluates consumer sentiment.
|
||||
|
||||
- **Independent Travel Planning Modules**: Execute separate crews to independently plan different aspects of a trip. One crew might handle flight options, another handles accommodation, and a third plans activities.
|
||||
|
||||
## Choosing Between `akickoff()` and `kickoff_async()`
|
||||
|
||||
| Feature | `akickoff()` | `kickoff_async()` |
|
||||
|---------|--------------|-------------------|
|
||||
| Execution model | Native async/await | Thread-based wrapper |
|
||||
| Task execution | Async with `aexecute_sync()` | Sync in thread pool |
|
||||
| Memory operations | Async | Sync in thread pool |
|
||||
| Knowledge retrieval | Async | Sync in thread pool |
|
||||
| Best for | High-concurrency, I/O-bound workloads | Simple async integration |
|
||||
| Streaming support | Yes | Yes |
|
||||
|
||||
@@ -95,7 +95,11 @@ print(f"Final result: {streaming.result.raw}")
|
||||
|
||||
## Asynchronous Streaming
|
||||
|
||||
For async applications, use `kickoff_async()` with async iteration:
|
||||
For async applications, you can use either `akickoff()` (native async) or `kickoff_async()` (thread-based) with async iteration:
|
||||
|
||||
### Native Async with `akickoff()`
|
||||
|
||||
The `akickoff()` method provides true native async execution throughout the entire chain:
|
||||
|
||||
```python Code
|
||||
import asyncio
|
||||
@@ -107,7 +111,35 @@ async def stream_crew():
|
||||
stream=True
|
||||
)
|
||||
|
||||
# Start async streaming
|
||||
# Start native async streaming
|
||||
streaming = await crew.akickoff(inputs={"topic": "AI"})
|
||||
|
||||
# Async iteration over chunks
|
||||
async for chunk in streaming:
|
||||
print(chunk.content, end="", flush=True)
|
||||
|
||||
# Access final result
|
||||
result = streaming.result
|
||||
print(f"\n\nFinal output: {result.raw}")
|
||||
|
||||
asyncio.run(stream_crew())
|
||||
```
|
||||
|
||||
### Thread-Based Async with `kickoff_async()`
|
||||
|
||||
For simpler async integration or backward compatibility:
|
||||
|
||||
```python Code
|
||||
import asyncio
|
||||
|
||||
async def stream_crew():
|
||||
crew = Crew(
|
||||
agents=[researcher],
|
||||
tasks=[task],
|
||||
stream=True
|
||||
)
|
||||
|
||||
# Start thread-based async streaming
|
||||
streaming = await crew.kickoff_async(inputs={"topic": "AI"})
|
||||
|
||||
# Async iteration over chunks
|
||||
@@ -121,6 +153,10 @@ async def stream_crew():
|
||||
asyncio.run(stream_crew())
|
||||
```
|
||||
|
||||
<Note>
|
||||
For high-concurrency workloads, `akickoff()` is recommended as it uses native async for task execution, memory operations, and knowledge retrieval. See the [Kickoff Crew Asynchronously](/en/learn/kickoff-async) guide for more details.
|
||||
</Note>
|
||||
|
||||
## Streaming with kickoff_for_each
|
||||
|
||||
When executing a crew for multiple inputs with `kickoff_for_each()`, streaming works differently depending on whether you use sync or async:
|
||||
|
||||
367
docs/en/tools/integration/mergeagenthandlertool.mdx
Normal file
367
docs/en/tools/integration/mergeagenthandlertool.mdx
Normal file
@@ -0,0 +1,367 @@
|
||||
---
|
||||
title: Merge Agent Handler Tool
|
||||
description: Enables CrewAI agents to securely access third-party integrations like Linear, GitHub, Slack, and more through Merge's Agent Handler platform
|
||||
icon: diagram-project
|
||||
mode: "wide"
|
||||
---
|
||||
|
||||
# `MergeAgentHandlerTool`
|
||||
|
||||
The `MergeAgentHandlerTool` enables CrewAI agents to securely access third-party integrations through [Merge's Agent Handler](https://www.merge.dev/products/merge-agent-handler) platform. Agent Handler provides pre-built, secure connectors to popular tools like Linear, GitHub, Slack, Notion, and hundreds more—all with built-in authentication, permissions, and monitoring.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
uv pip install 'crewai[tools]'
|
||||
```
|
||||
|
||||
## Requirements
|
||||
|
||||
- Merge Agent Handler account with a configured Tool Pack
|
||||
- Agent Handler API key
|
||||
- At least one registered user linked to your Tool Pack
|
||||
- Third-party integrations configured in your Tool Pack
|
||||
|
||||
## Getting Started with Agent Handler
|
||||
|
||||
1. **Sign up** for a Merge Agent Handler account at [ah.merge.dev/signup](https://ah.merge.dev/signup)
|
||||
2. **Create a Tool Pack** and configure the integrations you need
|
||||
3. **Register users** who will authenticate with the third-party services
|
||||
4. **Get your API key** from the Agent Handler dashboard
|
||||
5. **Set environment variable**: `export AGENT_HANDLER_API_KEY='your-key-here'`
|
||||
6. **Start building** with the MergeAgentHandlerTool in CrewAI
|
||||
|
||||
## Notes
|
||||
|
||||
- Tool Pack IDs and Registered User IDs can be found in your Agent Handler dashboard or created via API
|
||||
- The tool uses the Model Context Protocol (MCP) for communication with Agent Handler
|
||||
- Session IDs are automatically generated but can be customized for context persistence
|
||||
- All tool calls are logged and auditable through the Agent Handler platform
|
||||
- Tool parameters are dynamically discovered from the Agent Handler API and validated automatically
|
||||
|
||||
## Usage
|
||||
|
||||
### Single Tool Usage
|
||||
|
||||
Here's how to use a specific tool from your Tool Pack:
|
||||
|
||||
```python {2, 4-9}
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import MergeAgentHandlerTool
|
||||
|
||||
# Create a tool for Linear issue creation
|
||||
linear_create_tool = MergeAgentHandlerTool.from_tool_name(
|
||||
tool_name="linear__create_issue",
|
||||
tool_pack_id="134e0111-0f67-44f6-98f0-597000290bb3",
|
||||
registered_user_id="91b2b905-e866-40c8-8be2-efe53827a0aa"
|
||||
)
|
||||
|
||||
# Create a CrewAI agent that uses the tool
|
||||
project_manager = Agent(
|
||||
role='Project Manager',
|
||||
goal='Manage project tasks and issues efficiently',
|
||||
backstory='I am an expert at tracking project work and creating actionable tasks.',
|
||||
tools=[linear_create_tool],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Create a task for the agent
|
||||
create_issue_task = Task(
|
||||
description="Create a new high-priority issue in Linear titled 'Implement user authentication' with a detailed description of the requirements.",
|
||||
agent=project_manager,
|
||||
expected_output="Confirmation that the issue was created with its ID"
|
||||
)
|
||||
|
||||
# Create a crew with the agent
|
||||
crew = Crew(
|
||||
agents=[project_manager],
|
||||
tasks=[create_issue_task],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
# Run the crew
|
||||
result = crew.kickoff()
|
||||
print(result)
|
||||
```
|
||||
|
||||
### Loading Multiple Tools from a Tool Pack
|
||||
|
||||
You can load all available tools from your Tool Pack at once:
|
||||
|
||||
```python {2, 4-8}
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import MergeAgentHandlerTool
|
||||
|
||||
# Load all tools from the Tool Pack
|
||||
tools = MergeAgentHandlerTool.from_tool_pack(
|
||||
tool_pack_id="134e0111-0f67-44f6-98f0-597000290bb3",
|
||||
registered_user_id="91b2b905-e866-40c8-8be2-efe53827a0aa"
|
||||
)
|
||||
|
||||
# Create an agent with access to all tools
|
||||
automation_expert = Agent(
|
||||
role='Automation Expert',
|
||||
goal='Automate workflows across multiple platforms',
|
||||
backstory='I can work with any tool in the toolbox to get things done.',
|
||||
tools=tools,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
automation_task = Task(
|
||||
description="Check for any high-priority issues in Linear and post a summary to Slack.",
|
||||
agent=automation_expert
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[automation_expert],
|
||||
tasks=[automation_task],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
result = crew.kickoff()
|
||||
```
|
||||
|
||||
### Loading Specific Tools Only
|
||||
|
||||
Load only the tools you need:
|
||||
|
||||
```python {2, 4-10}
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import MergeAgentHandlerTool
|
||||
|
||||
# Load specific tools from the Tool Pack
|
||||
selected_tools = MergeAgentHandlerTool.from_tool_pack(
|
||||
tool_pack_id="134e0111-0f67-44f6-98f0-597000290bb3",
|
||||
registered_user_id="91b2b905-e866-40c8-8be2-efe53827a0aa",
|
||||
tool_names=["linear__create_issue", "linear__get_issues", "slack__post_message"]
|
||||
)
|
||||
|
||||
developer_assistant = Agent(
|
||||
role='Developer Assistant',
|
||||
goal='Help developers track and communicate about their work',
|
||||
backstory='I help developers stay organized and keep the team informed.',
|
||||
tools=selected_tools,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
daily_update_task = Task(
|
||||
description="Get all issues assigned to the current user in Linear and post a summary to the #dev-updates Slack channel.",
|
||||
agent=developer_assistant
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[developer_assistant],
|
||||
tasks=[daily_update_task],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
result = crew.kickoff()
|
||||
```
|
||||
|
||||
## Tool Arguments
|
||||
|
||||
### `from_tool_name()` Method
|
||||
|
||||
| Argument | Type | Required | Default | Description |
|
||||
|:---------|:-----|:---------|:--------|:------------|
|
||||
| **tool_name** | `str` | Yes | None | Name of the specific tool to use (e.g., "linear__create_issue") |
|
||||
| **tool_pack_id** | `str` | Yes | None | UUID of your Agent Handler Tool Pack |
|
||||
| **registered_user_id** | `str` | Yes | None | UUID or origin_id of the registered user |
|
||||
| **base_url** | `str` | No | "https://ah-api.merge.dev" | Base URL for Agent Handler API |
|
||||
| **session_id** | `str` | No | Auto-generated | MCP session ID for maintaining context |
|
||||
|
||||
### `from_tool_pack()` Method
|
||||
|
||||
| Argument | Type | Required | Default | Description |
|
||||
|:---------|:-----|:---------|:--------|:------------|
|
||||
| **tool_pack_id** | `str` | Yes | None | UUID of your Agent Handler Tool Pack |
|
||||
| **registered_user_id** | `str` | Yes | None | UUID or origin_id of the registered user |
|
||||
| **tool_names** | `list[str]` | No | None | Specific tool names to load. If None, loads all available tools |
|
||||
| **base_url** | `str` | No | "https://ah-api.merge.dev" | Base URL for Agent Handler API |
|
||||
|
||||
## Environment Variables
|
||||
|
||||
```bash
|
||||
AGENT_HANDLER_API_KEY=your_api_key_here # Required for authentication
|
||||
```
|
||||
|
||||
## Advanced Usage
|
||||
|
||||
### Multi-Agent Workflow with Different Tool Access
|
||||
|
||||
```python {2, 4-20}
|
||||
from crewai import Agent, Task, Crew, Process
|
||||
from crewai_tools import MergeAgentHandlerTool
|
||||
|
||||
# Create specialized tools for different agents
|
||||
github_tools = MergeAgentHandlerTool.from_tool_pack(
|
||||
tool_pack_id="134e0111-0f67-44f6-98f0-597000290bb3",
|
||||
registered_user_id="91b2b905-e866-40c8-8be2-efe53827a0aa",
|
||||
tool_names=["github__create_pull_request", "github__get_pull_requests"]
|
||||
)
|
||||
|
||||
linear_tools = MergeAgentHandlerTool.from_tool_pack(
|
||||
tool_pack_id="134e0111-0f67-44f6-98f0-597000290bb3",
|
||||
registered_user_id="91b2b905-e866-40c8-8be2-efe53827a0aa",
|
||||
tool_names=["linear__create_issue", "linear__update_issue"]
|
||||
)
|
||||
|
||||
slack_tool = MergeAgentHandlerTool.from_tool_name(
|
||||
tool_name="slack__post_message",
|
||||
tool_pack_id="134e0111-0f67-44f6-98f0-597000290bb3",
|
||||
registered_user_id="91b2b905-e866-40c8-8be2-efe53827a0aa"
|
||||
)
|
||||
|
||||
# Create specialized agents
|
||||
code_reviewer = Agent(
|
||||
role='Code Reviewer',
|
||||
goal='Review pull requests and ensure code quality',
|
||||
backstory='I am an expert at reviewing code changes and providing constructive feedback.',
|
||||
tools=github_tools
|
||||
)
|
||||
|
||||
task_manager = Agent(
|
||||
role='Task Manager',
|
||||
goal='Track and update project tasks based on code changes',
|
||||
backstory='I keep the project board up to date with the latest development progress.',
|
||||
tools=linear_tools
|
||||
)
|
||||
|
||||
communicator = Agent(
|
||||
role='Team Communicator',
|
||||
goal='Keep the team informed about important updates',
|
||||
backstory='I make sure everyone knows what is happening in the project.',
|
||||
tools=[slack_tool]
|
||||
)
|
||||
|
||||
# Create sequential tasks
|
||||
review_task = Task(
|
||||
description="Review all open pull requests in the 'api-service' repository and identify any that need attention.",
|
||||
agent=code_reviewer,
|
||||
expected_output="List of pull requests that need review or have issues"
|
||||
)
|
||||
|
||||
update_task = Task(
|
||||
description="Update Linear issues based on the pull request review findings. Mark completed PRs as done.",
|
||||
agent=task_manager,
|
||||
expected_output="Summary of updated Linear issues"
|
||||
)
|
||||
|
||||
notify_task = Task(
|
||||
description="Post a summary of today's code review and task updates to the #engineering Slack channel.",
|
||||
agent=communicator,
|
||||
expected_output="Confirmation that the message was posted"
|
||||
)
|
||||
|
||||
# Create a crew with sequential processing
|
||||
crew = Crew(
|
||||
agents=[code_reviewer, task_manager, communicator],
|
||||
tasks=[review_task, update_task, notify_task],
|
||||
process=Process.sequential,
|
||||
verbose=True
|
||||
)
|
||||
|
||||
result = crew.kickoff()
|
||||
```
|
||||
|
||||
### Custom Session Management
|
||||
|
||||
Maintain context across multiple tool calls using session IDs:
|
||||
|
||||
```python {2, 4-17}
|
||||
from crewai import Agent, Task, Crew
|
||||
from crewai_tools import MergeAgentHandlerTool
|
||||
|
||||
# Create tools with the same session ID to maintain context
|
||||
session_id = "project-sprint-planning-2024"
|
||||
|
||||
create_tool = MergeAgentHandlerTool(
|
||||
name="linear_create_issue",
|
||||
description="Creates a new issue in Linear",
|
||||
tool_name="linear__create_issue",
|
||||
tool_pack_id="134e0111-0f67-44f6-98f0-597000290bb3",
|
||||
registered_user_id="91b2b905-e866-40c8-8be2-efe53827a0aa",
|
||||
session_id=session_id
|
||||
)
|
||||
|
||||
update_tool = MergeAgentHandlerTool(
|
||||
name="linear_update_issue",
|
||||
description="Updates an existing issue in Linear",
|
||||
tool_name="linear__update_issue",
|
||||
tool_pack_id="134e0111-0f67-44f6-98f0-597000290bb3",
|
||||
registered_user_id="91b2b905-e866-40c8-8be2-efe53827a0aa",
|
||||
session_id=session_id
|
||||
)
|
||||
|
||||
sprint_planner = Agent(
|
||||
role='Sprint Planner',
|
||||
goal='Plan and organize sprint tasks',
|
||||
backstory='I help teams plan effective sprints with well-defined tasks.',
|
||||
tools=[create_tool, update_tool],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
planning_task = Task(
|
||||
description="Create 5 sprint tasks for the authentication feature and set their priorities based on dependencies.",
|
||||
agent=sprint_planner
|
||||
)
|
||||
|
||||
crew = Crew(
|
||||
agents=[sprint_planner],
|
||||
tasks=[planning_task],
|
||||
verbose=True
|
||||
)
|
||||
|
||||
result = crew.kickoff()
|
||||
```
|
||||
|
||||
## Use Cases
|
||||
|
||||
### Unified Integration Access
|
||||
- Access hundreds of third-party tools through a single unified API without managing multiple SDKs
|
||||
- Enable agents to work with Linear, GitHub, Slack, Notion, Jira, Asana, and more from one integration point
|
||||
- Reduce integration complexity by letting Agent Handler manage authentication and API versioning
|
||||
|
||||
### Secure Enterprise Workflows
|
||||
- Leverage built-in authentication and permission management for all third-party integrations
|
||||
- Maintain enterprise security standards with centralized access control and audit logging
|
||||
- Enable agents to access company tools without exposing API keys or credentials in code
|
||||
|
||||
### Cross-Platform Automation
|
||||
- Build workflows that span multiple platforms (e.g., create GitHub issues from Linear tasks, sync Notion pages to Slack)
|
||||
- Enable seamless data flow between different tools in your tech stack
|
||||
- Create intelligent automation that understands context across different platforms
|
||||
|
||||
### Dynamic Tool Discovery
|
||||
- Load all available tools at runtime without hardcoding integration logic
|
||||
- Enable agents to discover and use new tools as they're added to your Tool Pack
|
||||
- Build flexible agents that can adapt to changing tool availability
|
||||
|
||||
### User-Specific Tool Access
|
||||
- Different users can have different tool permissions and access levels
|
||||
- Enable multi-tenant workflows where agents act on behalf of specific users
|
||||
- Maintain proper attribution and permissions for all tool actions
|
||||
|
||||
## Available Integrations
|
||||
|
||||
Merge Agent Handler supports hundreds of integrations across multiple categories:
|
||||
|
||||
- **Project Management**: Linear, Jira, Asana, Monday.com, ClickUp
|
||||
- **Code Management**: GitHub, GitLab, Bitbucket
|
||||
- **Communication**: Slack, Microsoft Teams, Discord
|
||||
- **Documentation**: Notion, Confluence, Google Docs
|
||||
- **CRM**: Salesforce, HubSpot, Pipedrive
|
||||
- **And many more...**
|
||||
|
||||
Visit the [Merge Agent Handler documentation](https://docs.ah.merge.dev/) for a complete list of available integrations.
|
||||
|
||||
## Error Handling
|
||||
|
||||
The tool provides comprehensive error handling:
|
||||
|
||||
- **Authentication Errors**: Invalid or missing API keys
|
||||
- **Permission Errors**: User lacks permission for the requested action
|
||||
- **API Errors**: Issues communicating with Agent Handler or third-party services
|
||||
- **Validation Errors**: Invalid parameters passed to tool methods
|
||||
|
||||
All errors are wrapped in `MergeAgentHandlerToolError` for consistent error handling.
|
||||
@@ -10,6 +10,10 @@ Integration tools let your agents hand off work to other automation platforms an
|
||||
## **Available Tools**
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Merge Agent Handler Tool" icon="diagram-project" href="/en/tools/integration/mergeagenthandlertool">
|
||||
Securely access hundreds of third-party tools like Linear, GitHub, Slack, and more through Merge's unified API.
|
||||
</Card>
|
||||
|
||||
<Card title="CrewAI Run Automation Tool" icon="robot" href="/en/tools/integration/crewaiautomationtool">
|
||||
Invoke live CrewAI Platform automations, pass custom inputs, and poll for results directly from your agent.
|
||||
</Card>
|
||||
|
||||
@@ -515,8 +515,7 @@ crew = Crew(
|
||||
"provider": "huggingface",
|
||||
"config": {
|
||||
"api_key": "your-hf-token", # Optional for public models
|
||||
"model": "sentence-transformers/all-MiniLM-L6-v2",
|
||||
"api_url": "https://api-inference.huggingface.co" # or your custom endpoint
|
||||
"model": "sentence-transformers/all-MiniLM-L6-v2"
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
@@ -63,5 +63,55 @@ def my_cache_strategy(arguments: dict, result: str) -> bool:
|
||||
cached_tool.cache_function = my_cache_strategy
|
||||
```
|
||||
|
||||
### 비동기 도구 생성하기
|
||||
|
||||
CrewAI는 논블로킹 I/O 작업을 위한 비동기 도구를 지원합니다. 이는 HTTP 요청, 데이터베이스 쿼리 또는 기타 I/O 바운드 작업이 필요한 경우에 유용합니다.
|
||||
|
||||
#### `@tool` 데코레이터와 비동기 함수 사용하기
|
||||
|
||||
비동기 도구를 만드는 가장 간단한 방법은 `@tool` 데코레이터와 async 함수를 사용하는 것입니다:
|
||||
|
||||
```python Code
|
||||
import aiohttp
|
||||
from crewai.tools import tool
|
||||
|
||||
@tool("Async Web Fetcher")
|
||||
async def fetch_webpage(url: str) -> str:
|
||||
"""Fetch content from a webpage asynchronously."""
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(url) as response:
|
||||
return await response.text()
|
||||
```
|
||||
|
||||
#### 비동기 지원으로 `BaseTool` 서브클래싱하기
|
||||
|
||||
더 많은 제어를 위해 `BaseTool`을 상속하고 `_run`(동기) 및 `_arun`(비동기) 메서드를 모두 구현할 수 있습니다:
|
||||
|
||||
```python Code
|
||||
import requests
|
||||
import aiohttp
|
||||
from crewai.tools import BaseTool
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
class WebFetcherInput(BaseModel):
|
||||
"""Input schema for WebFetcher."""
|
||||
url: str = Field(..., description="The URL to fetch")
|
||||
|
||||
class WebFetcherTool(BaseTool):
|
||||
name: str = "Web Fetcher"
|
||||
description: str = "Fetches content from a URL"
|
||||
args_schema: type[BaseModel] = WebFetcherInput
|
||||
|
||||
def _run(self, url: str) -> str:
|
||||
"""Synchronous implementation."""
|
||||
return requests.get(url).text
|
||||
|
||||
async def _arun(self, url: str) -> str:
|
||||
"""Asynchronous implementation for non-blocking I/O."""
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(url) as response:
|
||||
return await response.text()
|
||||
```
|
||||
|
||||
이 가이드라인을 준수하고 새로운 기능과 협업 도구를 도구 생성 및 관리 프로세스에 통합함으로써,
|
||||
CrewAI 프레임워크의 모든 기능을 활용할 수 있으며, AI agent의 개발 경험과 효율성을 모두 높일 수 있습니다.
|
||||
CrewAI 프레임워크의 모든 기능을 활용할 수 있으며, AI agent의 개발 경험과 효율성을 모두 높일 수 있습니다.
|
||||
|
||||
@@ -515,8 +515,7 @@ crew = Crew(
|
||||
"provider": "huggingface",
|
||||
"config": {
|
||||
"api_key": "your-hf-token", # Opcional para modelos públicos
|
||||
"model": "sentence-transformers/all-MiniLM-L6-v2",
|
||||
"api_url": "https://api-inference.huggingface.co" # ou seu endpoint customizado
|
||||
"model": "sentence-transformers/all-MiniLM-L6-v2"
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
@@ -66,5 +66,55 @@ def my_cache_strategy(arguments: dict, result: str) -> bool:
|
||||
cached_tool.cache_function = my_cache_strategy
|
||||
```
|
||||
|
||||
### Criando Ferramentas Assíncronas
|
||||
|
||||
O CrewAI suporta ferramentas assíncronas para operações de I/O não bloqueantes. Isso é útil quando sua ferramenta precisa fazer requisições HTTP, consultas a banco de dados ou outras operações de I/O.
|
||||
|
||||
#### Usando o Decorador `@tool` com Funções Assíncronas
|
||||
|
||||
A maneira mais simples de criar uma ferramenta assíncrona é usando o decorador `@tool` com uma função async:
|
||||
|
||||
```python Code
|
||||
import aiohttp
|
||||
from crewai.tools import tool
|
||||
|
||||
@tool("Async Web Fetcher")
|
||||
async def fetch_webpage(url: str) -> str:
|
||||
"""Fetch content from a webpage asynchronously."""
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(url) as response:
|
||||
return await response.text()
|
||||
```
|
||||
|
||||
#### Subclassificando `BaseTool` com Suporte Assíncrono
|
||||
|
||||
Para maior controle, herde de `BaseTool` e implemente os métodos `_run` (síncrono) e `_arun` (assíncrono):
|
||||
|
||||
```python Code
|
||||
import requests
|
||||
import aiohttp
|
||||
from crewai.tools import BaseTool
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
class WebFetcherInput(BaseModel):
|
||||
"""Input schema for WebFetcher."""
|
||||
url: str = Field(..., description="The URL to fetch")
|
||||
|
||||
class WebFetcherTool(BaseTool):
|
||||
name: str = "Web Fetcher"
|
||||
description: str = "Fetches content from a URL"
|
||||
args_schema: type[BaseModel] = WebFetcherInput
|
||||
|
||||
def _run(self, url: str) -> str:
|
||||
"""Synchronous implementation."""
|
||||
return requests.get(url).text
|
||||
|
||||
async def _arun(self, url: str) -> str:
|
||||
"""Asynchronous implementation for non-blocking I/O."""
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(url) as response:
|
||||
return await response.text()
|
||||
```
|
||||
|
||||
Seguindo essas orientações e incorporando novas funcionalidades e ferramentas de colaboração nos seus processos de criação e gerenciamento de ferramentas,
|
||||
você pode aproveitar ao máximo as capacidades do framework CrewAI, aprimorando tanto a experiência de desenvolvimento quanto a eficiência dos seus agentes de IA.
|
||||
você pode aproveitar ao máximo as capacidades do framework CrewAI, aprimorando tanto a experiência de desenvolvimento quanto a eficiência dos seus agentes de IA.
|
||||
|
||||
Reference in New Issue
Block a user