# Building a Multi-Agent Application to Interact with Google Products

> In this article, I will provide a step-by-step introduction to Google's brand-new multi-agent orchestration framework, Google ADK, and explain how to use ADK to build multi-agent systems.

![The workflow that we are building](../../Images/google-adk-multi-agent/01-fig.png)

First of all, there are a few prerequisites for this project. We will need a Google Client ID and Client Secret, as we need to authorize users via OAuth.

## Prerequisites

> Creating google client id and client secret.

Head to the Google Cloud Console, select ***APIs & Services***, and then go to ***Credentials***.

![Step 1: Creating an OAuth client](../../Images/google-adk-multi-agent/02-fig.png)

![Step 1: Creating an OAuth client](../../Images/google-adk-multi-agent/03-fig.png)

**Step 2**

Click *Add URI* under ***Authorized Redirect URIs***. This is where you redirect users after they successfully authorize. Since this is a demo application, you can set this as your local endpoint. I set mine as `http://localhost:8000/callback`.

![Add the redirect URI and save the client details](../../Images/google-adk-multi-agent/04-fig.png)

Perfect, that's all. Now you are ready for the next step. Before proceeding, note down the Client ID, Client Secret, and Redirect URI.

## Building Agents

Okay, now it's time to orchestrate these agents to achieve the idea we are building. As a quick refresher, this is the idea we have.

![It's really simple but ideal for getting started and exploring.](../../Images/google-adk-multi-agent/05-fig.png)

First things first, you will need to install the Google Agent Development Kit beforehand. Follow [*these steps*](https://google.github.io/adk-docs/get-started/quickstart/) to install it. I recommend installing it in a separate environment to avoid version conflicts.

### Understanding Google's ADK Agent Categories

![Image credit: google-adk-documentation](../../Images/google-adk-multi-agent/06-fig.png)

The Agent Development Kit offers flexibility to choose agents based on our requirements. Each agent has its reasons for being selected. Here, I will choose an LLM-based agent for my task. It allows flexibility to select available sub-agents for task delegation based on user queries.

![Our root agent](../../Images/google-adk-multi-agent/07-fig.png)

```python
from google.adk.agents import LlmAgent

router_agent = LlmAgent(
    model=MODEL_NAME,
    name="task_router_agent",
    description="Acts as the main interface, routing tasks to Gmail or Calendar agents or answering general questions.",
    instruction="""Understand the user's request.
                - If the request relates to Gmail (reading/sending email, user profile), delegate the task to the 'google_gmail_agent'.
                - If the request relates to Google Calendar (listing/creating events), delegate the task to the 'google_calendar_agent'.
                - If the user asks a general question not related to Gmail or Calendar tools, answer it using your own knowledge.
                - If you are unsure which agent to use or the request is ambiguous, ask the user for clarification.
                - If a sub-agent reports an error, relay the exact error message to the user.""", # debugging purposes
    sub_agents=[...]
)
```

Alright, it's clear and straightforward. However, notice the `sub_agents` argument we provided for the `LlmAgent` class. This is where we tell them about the available agents for task delegation. Next, we can start building sub-agents.

### Building Sub Agents

![Workflow, up to sub-agents](../../Images/google-adk-multi-agent/08-fig.png)

Perfect, now it's time to code our agents. It's no different from our `router_agent`.

```python
gmail_agent = LlmAgent(
    model=MODEL_NAME,
    name="google_gmail_agent",
    description="Handles Gmail tasks like reading emails, sending emails, and checking user profiles.",
    instruction="You handle queries related to Gmail. Do not ask any followup questions related to user ids, gmail ids etc. The special string `me` is used to refer to the authenticated user. You don't need to know the actual email address or user ID if you're making requests on behalf of the logged-in user. Use the available tools to fulfill the user's request. If you encounter an error, provide the *exact* error message so the user can debug.",
    tools=gmail_tools
)

calendar_agent = LlmAgent(
    model=MODEL_NAME,
    name="google_calendar_agent",
    description="Handles Calendar tasks like listing events, creating events, and getting event details.",
    instruction="You handle queries related to Google Calendar. Never ask user to provide the calendarId, users's main Google Calendar ID is usually just 'primary'. Use the available tools to fulfill the user's request. If you encounter an error, provide the *exact* error message so the user can debug.",
    tools=calendar_tools
)
```

There is an additional input called `tools`. These are the usual tools we provide to agents to enhance their capabilities. However, things are different here. To access Google product details like Calendar and Gmail, we need the user's consent, also known as authorization. Only then can these tools function. In this tutorial, I'm going to use the OAuth authorization protocol that Google offers, but you can use different authorization methods depending on the application you're integrating.

In this step, I assume you have the Google client ID, client secret, and redirect URI set up in the prerequisite section.

### Authorization and Defining Tools

Google's ADK offers very convenient building blocks to handle the authorization process smoothly. All we need to do is define the tools, their specifications, and authorization details.

For the tools' API specification, you can follow these steps. The purpose of the API specification is to give the LLM an understanding of how these tools should be used, which parameters to include, and so on.

![Example OpenAPI spec. for Calendar](../../Images/google-adk-multi-agent/09-fig.png)

Generating an [OpenAPI specification](https://en.wikipedia.org/wiki/OpenAPI_Specification) from the [Google Discovery API](https://cloud.google.com/docs/discovery) is relatively easy. I found the following tool more convenient. All you have to do is find the relevant Google Discovery API for your product of interest, head over to [https://lucybot-inc.github.io/api-spec-converter/](https://lucybot-inc.github.io/api-spec-converter/), select the source and destination formats, and download the results. Nevertheless, all API specifications related to this task are available in my [*GitHub repository*](https://github.com/Ransaka/google-service-agent/tree/main). Great! Now we can define the tools for sub-agents.

```python
from google.adk.tools.openapi_tool.openapi_spec_parser.openapi_toolset import OpenAPIToolset
from fastapi.openapi.models import OAuth2, OAuthFlowAuthorizationCode, OAuthFlows
from google.adk.auth import AuthConfig, AuthCredential, AuthCredentialTypes, OAuth2Auth

required_scopes = {
    "https://www.googleapis.com/auth/gmail.readonly": "gmail read scope",
    "https://www.googleapis.com/auth/gmail.send": "gmail send scope",
    "https://www.googleapis.com/auth/userinfo.profile": "user profile scope",
    "https://www.googleapis.com/auth/calendar.events": "calendar read/write events scope",
    "https://www.googleapis.com/auth/calendar.calendarlist": "calendar read scope"
}

auth_scheme = OAuth2(
    flows=OAuthFlows(
        authorizationCode=OAuthFlowAuthorizationCode(
            authorizationUrl="https://accounts.google.com/o/oauth2/auth",
            tokenUrl="https://oauth2.googleapis.com/token",
            scopes=required_scopes,
        )
    )
)

auth_credential = AuthCredential(
    auth_type=AuthCredentialTypes.OAUTH2,
    oauth2=OAuth2Auth(
        client_id=client_id,
        client_secret=client_secret
    ),
)

with open("api_specs/open_api_gmail_spec.txt", "r") as f:
    gmail_spec_str = f.read()

gmail_api_toolset = OpenAPIToolset(
    spec_str=gmail_spec_str,
    spec_str_type='yaml',
    auth_scheme=auth_scheme,
    auth_credential=auth_credential,
)

gmail_selected_tool_names = [
    'gmail_users_messages_list', 'gmail_users_messages_get',
    'gmail_users_messages_send', 'gmail_users_get_profile'
]
all_gmail_tool_names = {tool.name for tool in gmail_api_toolset.get_tools()}
gmail_tools = [tool for tool in gmail_api_toolset.get_tools() if tool.name in gmail_selected_tool_names]

with open("api_specs/open_api_calendar_spec.txt", "r") as f:
    calendar_spec_str = f.read()

calendar_api_toolset = OpenAPIToolset(
    spec_str=calendar_spec_str,
    spec_str_type='yaml',
    auth_scheme=auth_scheme,
    auth_credential=auth_credential,
)

calendar_selected_tool_names = [
    'calendar_events_list', 'calendar_events_insert', 'calendar_events_get', 'calendar_calendar_list_list'
]
all_calendar_tool_names = {tool.name for tool in calendar_api_toolset.get_tools()}
calendar_tools = [tool for tool in calendar_api_toolset.get_tools() if tool.name in calendar_selected_tool_names]
```

Now we have all the components related to tool use and authorization. It's time to wrap the Agent with a chat interface for the demo. First, let's revisit the workflow so far.

![Agents check for user consent and use tools.](../../Images/google-adk-multi-agent/10-fig.png)

Now it's time to test the application.

## Agent in Action

The simplest way to test ADK applications is by using the command `adk web`. This will open a web server on your local machine, allowing you to send messages, check the agent's internal states, and understand agent handoffs. However, I will continue this testing using the command-line version. Okay, let's start chatting!

Starting with a general question.

![Asking a general question](../../Images/google-adk-multi-agent/11-fig.png)

Looks good! Now, let's try a query related to a Google product, such as listing calendar events..

![Asking the agent to list upcoming events.](../../Images/google-adk-multi-agent/12-fig.png)

Since this is the very beginning of our conversation, the application triggered the authorization flow. This will ask the user to copy the URL populated in the interface and open it in a browser. This will redirect the user to a typical Google authorization page.

![Typical Google authorization page](../../Images/google-adk-multi-agent/13-fig.png)

Once you click *Allow*, this will navigate you to the redirect URI you specified during the OAuth client setup. Once you have successfully authenticated, it will respond to your queries promptly, as shown below.

![Agent responds after authentication.](../../Images/google-adk-multi-agent/14-fig.png)

Great, now we have completed our agent setup. This agent will be able to read emails for you, summarize them, send them to a given address, and schedule events based on email content. However, doing all of these in a single prompt is currently not feasible, but it's doable with minimal code changes. Code for this project can be accessed [here](https://github.com/Ransaka/google-service-agent/tree/main).

## Conclusion

This concludes the defined task of building a multi-agent system interacting with Google products. Based on my experiment, the Google ADK framework contains powerful agent orchestration tools and, most importantly, a massive ecosystem on GCP. For example, Google recently launched the Agent Garden, focusing on building multi-agent systems on top of Google products. This is a significant step toward organizations that need to adopt agent/multi-agent systems but hesitate due to privacy and security concerns. There's still a long way to go, but I believe this project will inspire you to build even more amazing projects.

Thank you so much for reading! Have feedback? Connect with me via [LinkedIn](https://www.linkedin.com/in/ransaka/?_l=en_US).

_All images, unless otherwise noted, are by the author._

*This article was originally published in [Google Cloud - Community](https://medium.com/google-cloud/building-a-multi-agent-application-to-interact-with-google-products-b7ff7eb2f17d) on Medium.*
