diff --git a/pages/home/oai-agents/overview.mdx b/pages/home/oai-agents/overview.mdx index e52153aa0..7f29b0c6e 100644 --- a/pages/home/oai-agents/overview.mdx +++ b/pages/home/oai-agents/overview.mdx @@ -2,21 +2,39 @@ title: "Arcade with OpenAI Agents overview" description: "Comprehensive guide to using Arcade with the OpenAI Agents library" --- +import { Steps, Tabs } from "nextra/components"; + # Arcade with OpenAI Agents -The `agents-arcade` package provides a seamless integration between [Arcade](https://arcade.dev) and the [OpenAI Agents Library](https://github.com/openai/openai-python). This integration allows you to enhance your AI agents with powerful Arcade tools including Google Mail, LinkedIn, GitHub, and many more. +Arcade provides seamless integration with the [OpenAI Agents Library](https://github.com/openai/openai-python) and [OpenAI Agents JS](https://openai.github.io/openai-agents-js/), allowing you to enhance your AI agents with powerful tools including Gmail, LinkedIn, GitHub, and many more. This integration is available through the `agents-arcade` package for Python and our [JavaScript client library](https://github.com/ArcadeAI/arcade-js). ## Installation Install the necessary packages to get started: + + + ```bash pip install agents-arcade arcadepy ``` + + + + +```bash +npm install @openai/agents @arcadeai/arcadejs +``` + + + + + Make sure you have your Arcade API key ready. [Get an API key](/home/api-keys) if you don't already have one. + ## Key features - **Easy integration** with the OpenAI Agents framework @@ -29,6 +47,9 @@ Make sure you have your Arcade API key ready. [Get an API key](/home/api-keys) i Here's a simple example of using Arcade tools with OpenAI Agents: + + + ```python from agents import Agent, Runner from arcadepy import AsyncArcade @@ -66,8 +87,65 @@ if __name__ == "__main__": asyncio.run(main()) ``` + + + + +Check out the complete working example in our [GitHub repository](https://github.com/ArcadeAI/arcade-ai/tree/main/examples/openai-agents-ts/src/index.ts). + +```javascript +import Arcade from '@arcadeai/arcadejs'; +import { executeOrAuthorizeZodTool, toZod } from "@arcadeai/arcadejs/lib"; +import { Agent, run, tool } from '@openai/agents'; + +// 1) Initialize Arcade client +const client = new Arcade(); + +// 2) Fetch Google toolkit from Arcade and prepare tools for OpenAI Agents +const googleToolkit = await client.tools.list({ toolkit: "google", limit: 30 }); +const arcadeTools = toZod({ + tools: googleToolkit.items, + client, + userId: "", // Replace this with your application's user ID (e.g. email address, UUID, etc.) + executeFactory: executeOrAuthorizeZodTool, +}) + +// 3) Convert the tools to a format that OpenAI Agents can use +const tools = arcadeTools.map(({ name, description, execute, parameters }) => + tool({ + name, + description: description ?? "", + parameters: parameters as any, + execute, + strict: true, + }), +); + +// 4) Create a new agent with the Google toolkit +const googleAgent = new Agent({ + name: "Google agent", + instructions: "You are a helpful assistant that can assist with Google API calls.", + model: "gpt-4o-mini", + tools +}); + +// 5) Run the agent +const result = await run(googleAgent, "What are my latest emails?"); + +// 6) Print the result +console.log(result.finalOutput); +``` + + + + + + ## Handling authorization + + + When a user needs to authorize access to a tool (like Google or GitHub), the agent will raise an `AuthorizationError` with a URL for the user to visit: ```python @@ -79,6 +157,20 @@ except AuthorizationError as e: print(f"Please visit this URL to authorize: {e}") ``` + + + + +When a user needs to authorize access to a tool (like Google or GitHub), the agent will show a message like this: + +```bash +[Authorize Gmail Access](https://accounts.google.com/o/oauth2/v2/auth?access_type=offline...) +Once you have authorized access, I can retrieve your latest emails. +``` + + + + After visiting the URL and authorizing access, the user can run the agent again with the same `user_id`, and it will work without requiring re-authorization. ## Available toolkits diff --git a/pages/home/oai-agents/use-arcade-tools.mdx b/pages/home/oai-agents/use-arcade-tools.mdx index 8dafc5c34..e86a941c0 100644 --- a/pages/home/oai-agents/use-arcade-tools.mdx +++ b/pages/home/oai-agents/use-arcade-tools.mdx @@ -2,8 +2,7 @@ title: "Use Arcade with OpenAI Agents" description: "Integrate Arcade tools into your OpenAI Agents applications" --- - -import { Steps } from "nextra/components"; +import { Steps, Tabs } from "nextra/components"; ## Use Arcade with OpenAI Agents @@ -19,16 +18,35 @@ In this guide, let's explore how to integrate Arcade tools into your OpenAI Agen Install the required packages, and ensure your environment variables are set with your Arcade API key: + + + + ```bash pip install agents-arcade arcadepy ``` + + + + +```bash +npm install @openai/agents @arcadeai/arcadejs +``` + + + + + ### Configure API keys Provide your Arcade API key. You can store it in environment variables or directly in your code: > Need an Arcade API key? Visit the [Get an API key](/home/api-keys) page to create one. + + + ```python import os @@ -36,8 +54,26 @@ os.environ["ARCADE_API_KEY"] = "YOUR_ARCADE_API_KEY" # Or set it directly when initializing the client ``` + + + + +```bash +# In your .env file +ARCADE_API_KEY=YOUR_ARCADE_API_KEY +``` + + + + + + + ### Create and manage Arcade tools + + + Use the `get_arcade_tools` function to retrieve tools from specific toolkits: ```python @@ -57,10 +93,71 @@ tools = await get_arcade_tools(client, toolkits=["google", "github", "linkedin"] tools = await get_arcade_tools(client, tools=["Google_ListEmails", "Slack_ListUsers", "Slack_SendDmToUser"]) ``` + + + + +```javascript +import Arcade from '@arcadeai/arcadejs'; +import { executeOrAuthorizeZodTool, toZod } from "@arcadeai/arcadejs/lib"; +import { tool } from '@openai/agents'; + +const client = new Arcade(); + +// Option 1: Get tools from a single toolkit +const googleTools = await client.tools.list({ toolkit: "google", limit: 30 }); +const toolsFromGoogle = googleTools.items; + +// Option 2: Get tools from multiple toolkits +const [google, github, linkedin] = await Promise.all([ + client.tools.list({ toolkit: "google", limit: 30 }), + client.tools.list({ toolkit: "github", limit: 30 }), + client.tools.list({ toolkit: "linkedin", limit: 30 }) +]); +const toolsFromMultiple = [...google.items, ...github.items, ...linkedin.items]; + +// Option 3: Get specific tools by name +const specificTools = await Promise.all([ + client.tools.get("Google_ListEmails"), + client.tools.get("Slack_ListUsers"), + client.tools.get("Slack_SendDmToUser"), +]); + +// Convert any of the above to OpenAI Agents format +const convertToAgents = (arcadeTools) => { + const zodTools = toZod({ + tools: arcadeTools, + client, + userId: "", // Replace this with your application's user ID (e.g. email address, UUID, etc.) + executeFactory: executeOrAuthorizeZodTool, + }); + + return zodTools.map(({ name, description, execute, parameters }) => + tool({ + name, + description: description ?? "", + parameters: parameters as any, + execute, + strict: true, + }) + ); +}; + +// Use with any of the options above +const tools = convertToAgents(toolsFromGoogle); // or toolsFromMultiple or specificTools +``` + + + + + ### Set up the agent with Arcade tools Create an agent and provide it with the Arcade tools: + + + ```python from agents import Agent, Runner @@ -73,7 +170,29 @@ google_agent = Agent( ) ``` -### Run the agent with user context + + + + +```javascript +import { Agent, Runner, tool } from '@openai/agents'; + +// Create an agent with Arcade tools +const googleAgent = new Agent({ + name: "Google agent", + instructions: "You are a helpful assistant that can assist with Google API calls.", + model: "gpt-4o-mini", + tools +}); +``` + + + + +### Run the agent + + + Run the agent, providing a user_id for tool authorization: @@ -89,7 +208,22 @@ except AuthorizationError as e: print("Please Login to Google:", e) ``` -### Handle authentication errors + + + +```javascript +const result = await run(googleAgent, "What are my latest emails?"); +``` + + + + + + +### Handle authentication + + + If a tool requires authorization, an `AuthorizationError` will be raised with an authorization URL: @@ -104,10 +238,28 @@ except AuthorizationError as e: # The URL contained in the error will take the user to the authorization page ``` + + + + +If a tool requires authorization, the agent will show a message like this: + +```bash +[Authorize Gmail Access](https://accounts.google.com/o/oauth2/v2/auth?access_type=offline...) +Once you have authorized access, I can retrieve your latest emails. +``` + + + + + ### Complete example Here's a complete example putting everything together: + + + ```python from agents import Agent, Runner from arcadepy import AsyncArcade @@ -144,6 +296,58 @@ if __name__ == "__main__": asyncio.run(main()) ``` + + + + +Check out the complete working example in our [GitHub repository](https://github.com/ArcadeAI/arcade-ai/tree/main/examples/openai-agents-ts/src/index.ts). + +```javascript +import Arcade from '@arcadeai/arcadejs'; +import { executeOrAuthorizeZodTool, toZod } from "@arcadeai/arcadejs/lib"; +import { Agent, run, tool } from '@openai/agents'; + +// 1) Initialize Arcade client +const client = new Arcade(); + +// 2) Fetch Google toolkit from Arcade and prepare tools for OpenAI Agents +const googleToolkit = await client.tools.list({ toolkit: "google", limit: 30 }); +const arcadeTools = toZod({ + tools: googleToolkit.items, + client, + userId: "", // Replace this with your application's user ID (e.g. email address, UUID, etc.) + executeFactory: executeOrAuthorizeZodTool, +}) + +// 3) Convert the tools to a format that OpenAI Agents can use +const tools = arcadeTools.map(({ name, description, execute, parameters }) => + tool({ + name, + description: description ?? "", + parameters: parameters as any, + execute, + strict: true, + }), +); + +// 4) Create a new agent with the Google toolkit +const googleAgent = new Agent({ + name: "Google agent", + instructions: "You are a helpful assistant that can assist with Google API calls.", + model: "gpt-4o-mini", + tools +}); + +// 5) Run the agent +const result = await run(googleAgent, "What are my latest emails?"); + +// 6) Print the result +console.log(result.finalOutput); +``` + + + + ## Tips for selecting tools diff --git a/pages/home/oai-agents/user-auth-interrupts.mdx b/pages/home/oai-agents/user-auth-interrupts.mdx index abc6fa27c..d05828391 100644 --- a/pages/home/oai-agents/user-auth-interrupts.mdx +++ b/pages/home/oai-agents/user-auth-interrupts.mdx @@ -3,7 +3,7 @@ title: "Managing user authorization" description: "Handle tool authorization with Arcade and OpenAI Agents" --- -import { Steps } from "nextra/components"; +import { Steps, Tabs } from "nextra/components"; ## User authorization with OpenAI Agents @@ -19,16 +19,34 @@ In this guide, you will learn how to handle user authorization for Arcade tools Set up your environment with the following installations: + + + ```bash pip install agents-arcade arcadepy ``` + + + + +```bash +npm install @openai/agents @arcadeai/agents-arcade +``` + + + + + ### Configure your Arcade environment Make sure you have set your Arcade API key in the environment, or assign it directly in the code: > Need an Arcade API key? Visit the [Get an API key](/home/api-keys) page to create one. + + + ```python import os from arcadepy import AsyncArcade @@ -43,10 +61,35 @@ os.environ["ARCADE_API_KEY"] = "YOUR_ARCADE_API_KEY" client = AsyncArcade() ``` + + + + +Add your API key to your environment variables: + +```bash +# In your .env file +ARCADE_API_KEY=YOUR_ARCADE_API_KEY +``` + +```javascript +import Arcade from '@arcadeai/arcadejs'; +import { isAuthorizationRequiredError, toZod } from "@arcadeai/arcadejs/lib"; +import { Agent, run, tool } from '@openai/agents'; + +const client = new Arcade(); +``` + + + + ### Fetch Arcade tools Get the tools you need for your agent. In this example, we'll use GitHub tools: + + + ```python # Get GitHub tools for this example tools = await get_arcade_tools(client, toolkits=["github"]) @@ -60,8 +103,29 @@ github_agent = Agent( ) ``` + + + + +```javascript +const githubToolkit = await client.tools.list({ toolkit: "github", limit: 30 }); +const arcadeTools = toZod({ + tools: githubToolkit.items, + client, + userId: "", // Replace this with your application's user ID (e.g. email address, UUID, etc.) +}) +``` + + + + + + ### Handle authorization errors + + + When a user needs to authorize access to a tool, the agent will raise an `AuthorizationError`. You can handle it like this: ```python @@ -79,10 +143,73 @@ except AuthorizationError as e: # The error contains the authorization URL that the user should visit ``` + + + + +Choose how to handle authorization errors based on your needs: + +**Default behavior (throws errors):** +```javascript +const arcadeTools = toZod({ + tools: githubToolkit.items, + client, + userId: "", // Replace with your user ID +}); +``` + +Use this when you want to handle authorization flow yourself with custom logic. + +**Auto-handle authorization (recommended):** +```javascript +import { executeOrAuthorizeZodTool } from "@arcadeai/arcadejs/lib"; + +const arcadeTools = toZod({ + tools: githubToolkit.items, + client, + userId: "", // Replace with your user ID + executeFactory: executeOrAuthorizeZodTool, +}); +``` + +This automatically returns authorization URLs instead of throwing errors. + +**Custom error handling:** + +```javascript +import { isAuthorizationRequiredError } from "@arcadeai/arcadejs/lib"; + +const tools = arcadeTools.map(({ name, description, execute, parameters }) => + tool({ + name, + description: description ?? "", + parameters: parameters as any, + execute, + errorFunction: async(_, error) => { + if (error instanceof Error && isAuthorizationRequiredError(error)) { + const response = await client.tools.authorize({ + tool_name: name, + user_id: "", + }); + return `Please login to Google: ${response.url}`; + } + return "Error executing tool" + } + }), +); +``` + + + + + ### Wait for authorization completion You can also wait for the user to complete the authorization before continuing: + + + ```python from arcadepy import AsyncArcade import asyncio @@ -121,11 +248,64 @@ except AuthorizationError as e: print("Final output:\n\n", result.final_output) ``` + + + + +To wait for authorization completion, follow this approach: + +1. Throw the error to the agent +2. Catch and handle the error while waiting for completion + + + +```javascript +const tools = arcadeTools.map(({ name, description, execute, parameters }) => + tool({ + name, + description: description ?? "", + parameters: parameters as any, + execute, + errorFunction: (_, error) => { throw error } // Throw the error to the agent for handling + }), +); + +while (true) { + try { + const result = await run(googleAgent, "What are my latest emails?"); + console.log(result.finalOutput); + } catch (error) { + // Catch the authorization error and wait for completion + if (error instanceof Error && isAuthorizationRequiredError(error)) { + const response = await client.tools.authorize({ + tool_name: "Google_ListEmails", + user_id: "", + }); + if (response.status !== "completed") { + console.log(`Please complete the authorization challenge in your browser: ${response.url}`); + } + + // Wait for the authorization to complete + await client.auth.waitForCompletion(response); + console.log("Authorization completed, retrying..."); + } + } + } +``` + + + + + + + ### Complete example Here's a full example that demonstrates the authorization flow with waiting for authentication: -```python + + + ```python from arcadepy.auth import wait_for_authorization_completion @@ -177,6 +357,75 @@ if __name__ == "__main__": asyncio.run(main()) ``` + + + + +Check out the complete working example in our [GitHub repository](https://github.com/ArcadeAI/arcade-ai/tree/main/examples/openai-agents-ts/src/waitForCompletion.ts). + +```javascript +import Arcade from '@arcadeai/arcadejs'; +import { isAuthorizationRequiredError, toZod } from "@arcadeai/arcadejs/lib"; +import { Agent, run, tool } from '@openai/agents'; + +async function main() { + // 1) Initialize Arcade client + const client = new Arcade(); + + // 2) Fetch Google toolkit from Arcade and prepare tools for OpenAI Agents + const googleToolkit = await client.tools.list({ toolkit: "google", limit: 30 }); + const arcadeTools = toZod({ + tools: googleToolkit.items, + client, + userId: "", // Replace this with your application's user ID (e.g. email address, UUID, etc.) + }) + + // 3) Convert the tools to a format that OpenAI Agents can use + const tools = arcadeTools.map(({ name, description, execute, parameters }) => + tool({ + name, + description: description ?? "", + parameters: parameters as any, + execute, + errorFunction: (_, error) => { throw error } + }), + ); + + // 4) Create a new agent with the Google toolkit + const googleAgent = new Agent({ + name: "Google agent", + instructions: "You are a helpful assistant that can assist with Google API calls.", + model: "gpt-4o-mini", + tools + }); + + while (true) { + try { + const result = await run(googleAgent, "What are my latest emails?"); + console.log(result.finalOutput); + break; // Exit the loop if the result is successful + } catch (error) { + if (error instanceof Error && isAuthorizationRequiredError(error)) { + const response = await client.tools.authorize({ + tool_name: "Google_ListEmails", + user_id: "", + }); + if (response.status !== "completed") { + console.log(`Please complete the authorization challenge in your browser: ${response.url}`); + } + + // Wait for the authorization to complete + await client.auth.waitForCompletion(response); + console.log("Authorization completed, retrying..."); + } + } + } +} + +main(); +``` + + This example handles the authentication flow by: 1. Attempting to run the agent @@ -184,7 +433,7 @@ This example handles the authentication flow by: 3. Open the authentication URL in a browser 4. Waiting for the user to complete authentication 5. Retrying the operation after a wait period - +