Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 82 additions & 0 deletions examples/code/home/crewai/custom_auth_flow.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
from typing import Any

from crewai import Agent, Crew, Task
from crewai.llm import LLM
from crewai_arcade import ArcadeToolManager

USER_ID = "[email protected]"

def custom_auth_flow(
manager: ArcadeToolManager, tool_name: str, **tool_input: dict[str, Any]
) -> Any:
"""Custom auth flow for the ArcadeToolManager

This function is called when CrewAI needs to call a tool that requires authorization.
Authorization is handled before executing the tool.
This function overrides the ArcadeToolManager's default auth flow performed by ArcadeToolManager.authorize_tool
"""
# Get authorization status
auth_response = manager.authorize(tool_name, USER_ID)

# If the user is not authorized for the tool,
# then we need to handle the authorization before executing the tool
if not manager.is_authorized(auth_response.id):
print(f"Authorization required for tool: '{tool_name}' with inputs:")
for input_name, input_value in tool_input.items():
print(f" {input_name}: {input_value}")
# Handle authorization
print(f"\nTo authorize, visit: {auth_response.url}")
# Block until the user has completed the authorization
auth_response = manager.wait_for_auth(auth_response)

# Ensure authorization completed successfully
if not manager.is_authorized(auth_response.id):
raise ValueError(f"Authorization failed for {tool_name}. URL: {auth_response.url}")
else:
print(f"Authorization already granted for tool: '{tool_name}' with inputs:")
for input_name, input_value in tool_input.items():
print(f" {input_name}: {input_value}")


def tool_manager_callback(tool_manager: ArcadeToolManager, tool_name: str, **tool_input: dict[str, Any]) -> Any:
"""Tool executor callback with custom auth flow for the ArcadeToolManager

ArcadeToolManager's default executor handles authorization and tool execution.
This function overrides the default executor to handle authorization in a custom way and then executes the tool.
"""
custom_auth_flow(tool_manager, tool_name, **tool_input)
return tool_manager.execute_tool(USER_ID, tool_name, **tool_input)


manager = ArcadeToolManager(executor=tool_manager_callback)

tools = manager.get_tools(tools=["Google.ListEmails"], toolkits=["Slack"])

crew_agent = Agent(
role="Main Agent",
backstory="You are a helpful assistant",
goal="Help the user with their requests",
tools=tools,
allow_delegation=False,
verbose=True,
llm=LLM(model="gpt-4o"),
)

task = Task(
description="Get the 5 most recent emails from the user's inbox and summarize them and recommend a response for each.",
expected_output="A bulleted list with a one sentence summary of each email and a recommended response to the email.",
agent=crew_agent,
tools=crew_agent.tools,
)

crew = Crew(
agents=[crew_agent],
tasks=[task],
verbose=True,
memory=True,
)

result = crew.kickoff()

print("\n\n\n ------------ Result ------------ \n\n\n")
print(result)
46 changes: 46 additions & 0 deletions examples/code/home/crewai/custom_auth_flow_callback_section.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
from typing import Any

from crewai_arcade import ArcadeToolManager

USER_ID = "[email protected]"

def custom_auth_flow(
manager: ArcadeToolManager, tool_name: str, **tool_input: dict[str, Any]
) -> Any:
"""Custom auth flow for the ArcadeToolManager

This function is called when CrewAI needs to call a tool that requires authorization.
Authorization is handled before executing the tool.
This function overrides the ArcadeToolManager's default auth flow performed by ArcadeToolManager.authorize_tool
"""
# Get authorization status
auth_response = manager.authorize(tool_name, USER_ID)

# If the user is not authorized for the tool,
# then we need to handle the authorization before executing the tool
if not manager.is_authorized(auth_response.id):
print(f"Authorization required for tool: '{tool_name}' with inputs:")
for input_name, input_value in tool_input.items():
print(f" {input_name}: {input_value}")
# Handle authorization
print(f"\nTo authorize, visit: {auth_response.url}")
# Block until the user has completed the authorization
auth_response = manager.wait_for_auth(auth_response)

# Ensure authorization completed successfully
if not manager.is_authorized(auth_response.id):
raise ValueError(f"Authorization failed for {tool_name}. URL: {auth_response.url}")
else:
print(f"Authorization already granted for tool: '{tool_name}' with inputs:")
for input_name, input_value in tool_input.items():
print(f" {input_name}: {input_value}")


def tool_manager_callback(tool_manager: ArcadeToolManager, tool_name: str, **tool_input: dict[str, Any]) -> Any:
"""Tool executor callback with custom auth flow for the ArcadeToolManager

ArcadeToolManager's default executor handles authorization and tool execution.
This function overrides the default executor to handle authorization in a custom way and then executes the tool.
"""
custom_auth_flow(tool_manager, tool_name, **tool_input)
return tool_manager.execute_tool(USER_ID, tool_name, **tool_input)
37 changes: 37 additions & 0 deletions examples/code/home/crewai/use_arcade_tools.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
from crewai import Agent, Crew, Task
from crewai.llm import LLM
from crewai_arcade import ArcadeToolManager

manager = ArcadeToolManager(default_user_id="[email protected]")

tools = manager.get_tools(tools=["Google.ListEmails"])


crew_agent = Agent(
role="Main Agent",
backstory="You are a helpful assistant",
goal="Help the user with their requests",
tools=tools,
allow_delegation=False,
verbose=True,
llm=LLM(model="gpt-4o"),
)

task = Task(
description="Get the 5 most recent emails from the user's inbox and summarize them and recommend a response for each.",
expected_output="A bulleted list with a one sentence summary of each email and a recommended response to the email.",
agent=crew_agent,
tools=crew_agent.tools,
)

crew = Crew(
agents=[crew_agent],
tasks=[task],
verbose=True,
memory=True,
)

result = crew.kickoff()

print("\n\n\n ------------ Result ------------ \n\n\n")
print(result)
1 change: 0 additions & 1 deletion pages/home/crewai.mdx

This file was deleted.

4 changes: 4 additions & 0 deletions pages/home/crewai/_meta.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export default {
"use-arcade-tools": "Using Arcade tools",
"custom-auth-flow": "Custom auth flow",
};
105 changes: 105 additions & 0 deletions pages/home/crewai/custom-auth-flow.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
---
title: "Custom Auth Flow with CrewAI"
description: "Learn how to create a custom auth flow with CrewAI"
---

import { Steps } from "nextra/components";

## Custom Auth Flow with CrewAI

In this guide, we will explore how to create a custom auth flow that will be performed before executing Arcade tools within your CrewAI agent team.

The `ArcadeToolManager`'s built-in authorization and tool execution flows work well for many typical use cases. However, some scenarios call for a tailored approach. By implementing a custom auth flow, you gain flexibility in handling tool authorization. If your use case calls for a unique interface, additional approval steps, or specialized error handling, then this guide is for you.

Comment on lines +12 to +13
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Super clear 👍

<Steps>

### Prerequisites

- [Obtain an Arcade API key](/home/api-key)

### Set up your environment

Install the required package, and ensure your environment variables are set with your Arcade and OpenAI API keys:

```bash
pip install crewai-arcade
```

### Configure API keys

Provide your Arcade and OpenAI API keys. You can store them in environment variables like so:

```bash
export ARCADE_API_KEY="your_arcade_api_key"
export OPENAI_API_KEY="your_openai_api_key"
```

### Define your custom auth flow

The custom auth flow defined in the following code snippet is a function that will be called whenever CrewAI needs to call a tool.

```python file=<rootDir>/examples/code/home/crewai/custom_auth_flow_callback_section.py
```

### Get Arcade tools

You can now provide the tool manager callback to the `ArcadeToolManager` upon initialization:

```python
# Provide the tool manager callback to the ArcadeToolManager
manager = ArcadeToolManager(executor=tool_manager_callback)

# Retrieve the provided tools and/or toolkits as CrewAI StructuredTools.
tools = manager.get_tools(tools=["Google.ListEmails"], toolkits=["Slack"])
```

### Use tools in your CrewAI agent team

Create a Crew that uses your tools with the custom auth flow. When the tool is called, your tool manager callback will be called to handle the authorization and then the tool will be executed.

```python
from crewai import Agent, Crew, Task
from crewai.llm import LLM

crew_agent = Agent(
role="Main Agent",
backstory="You are a helpful assistant",
goal="Help the user with their requests",
tools=tools,
allow_delegation=False,
verbose=True,
llm=LLM(model="gpt-4o"),
)

task = Task(
description="Get the 5 most recent emails from the user's inbox and summarize them and recommend a response for each.",
expected_output="A bulleted list with a one sentence summary of each email and a recommended response to the email.",
agent=crew_agent,
tools=crew_agent.tools,
)

crew = Crew(
agents=[crew_agent],
tasks=[task],
verbose=True,
memory=True,
)

result = crew.kickoff()

print("\n\n\n ------------ Result ------------ \n\n\n")
print(result)
```

</Steps>

<ToggleContent showText="Click to view a full example" hideText="Hide example">

```python file=<rootDir>/examples/code/home/crewai/custom_auth_flow.py
```

</ToggleContent>

## Next steps

Now you're ready to integrate Arcade tools with a custom auth flow into your own CrewAI agent team.
110 changes: 110 additions & 0 deletions pages/home/crewai/use-arcade-tools.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
---
title: "Use Arcade tools with CrewAI"
description: "Integrate Arcade tools into your CrewAI applications"
---

import { Steps } from "nextra/components";

## Use CrewAI with Arcade

In this guide, we will explore how to integrate Arcade tools into your CrewAI application. Follow the step-by-step instructions below. If a tool requires authorization, an authorization URL will appear in the console, waiting for your approval. This process ensures that only the tools you choose to authorize are executed.

To tailor the tool authorization flow to meet your application's specific needs, check out the [Custom Auth Flow with CrewAI](/home/crewai/custom-auth-flow) guide.

<Steps>

### Prerequisites

- [Obtain an Arcade API key](/home/api-key)

### Set up your environment

Install the required package, and ensure your environment variables are set with your Arcade and OpenAI API keys:

```bash
pip install crewai-arcade
```

### Configure API keys

Provide your Arcade and OpenAI API keys. You can store them in environment variables like so:

```bash
export ARCADE_API_KEY="your_arcade_api_key"
export OPENAI_API_KEY="your_openai_api_key"
```

### Get Arcade tools

Use the `ArcadeToolManager` to initialize, add, and get Arcade tools:

```python
from crewai_arcade import ArcadeToolManager

manager = ArcadeToolManager(default_user_id="[email protected]")

"""
Retrieves the provided tools and/or toolkits as CrewAI StructuredTools.
"""
tools = manager.get_tools(tools=["Google.ListEmails"], toolkits=["Slack"])
```

### Use tools in your CrewAI agent team

Create a Crew that uses your tools. When the tool is called, you will be prompted to go visit an authorization page to authorize the tool before it executes.

```python
from crewai import Agent, Crew, Task
from crewai.llm import LLM

crew_agent = Agent(
role="Main Agent",
backstory="You are a helpful assistant",
goal="Help the user with their requests",
tools=tools,
allow_delegation=False,
verbose=True,
llm=LLM(model="gpt-4o"),
)

task = Task(
description="Get the 5 most recent emails from the user's inbox and summarize them and recommend a response for each.",
expected_output="A bulleted list with a one sentence summary of each email and a recommended response to the email.",
agent=crew_agent,
tools=crew_agent.tools,
)

crew = Crew(
agents=[crew_agent],
tasks=[task],
verbose=True,
memory=True,
)

result = crew.kickoff()

print("\n\n\n ------------ Result ------------ \n\n\n")
print(result)
```

</Steps>

<ToggleContent showText="Click to view a full example" hideText="Hide example">

```python file=<rootDir>/examples/code/home/crewai/use_arcade_tools.py
```

</ToggleContent>

## Tips for selecting tools

- **Relevance**: Pick only the tools you need. Avoid using all tools at once.
- **Avoid conflicts**: Be mindful of duplicate or overlapping functionality.

## Next steps

Now that you have integrated Arcade tools into your CrewAI agent team, you can:

- Experiment with different toolkits, such as "Math" or "Search."
- Customize the agent's prompts for specific tasks.
- Customize the tool authorization and execution flow to meet your application's requirements.
Loading