跳转到内容

使用工具进行身份验证

在 ADK 中得到支持。Python v0.1.0

在 ADK 代理中使用的工具和服务可能需要访问受保护的资源,例如电子邮件或日历应用程序中的用户数据,或数据库中的销售记录。要访问这些资源,通常需要经过身份验证流程;该流程会要求提供相应的凭据和访问密钥,这些凭据和密钥必须得到妥善管理和保护。如果您是在本地运行代理,还是将其部署到托管服务中,身份验证数据的管理要求也可能发生变化。如果有多个用户(他们可能具有不同的访问权限)与代理进行交互,那么身份验证管理的工作量就会进一步增加。

警告:凭证存储存在安全风险

将敏感的凭据(如访问令牌,尤其是刷新令牌)直接存储在会话状态中,可能会带来安全风险。这些风险的大小取决于您所使用的会话存储后端技术。 SessionService 实施细节,以及整个应用程序的安全性状况。在将 ADK 代理部署到实际使用环境中之前,请仔细考虑如何管理其中的凭据(即用于身份验证的信息)。

身份验证与凭证管理

在 ADK 代理中,有几种方法可以用来管理身份验证和凭据。每种方法都存在一定的风险,因此您应该仔细考虑哪种方法最适合您的应用程序和客户的需求。

推荐:身份验证管理服务(Authentication Manager Services)

在将代理程序部署到生产环境(即由外部组织或服务器托管的环境)时,代理程序能否正确地身份验证并访问那些受限制的工具和服务,就变得更具挑战性;同时,如何妥善管理这一身份验证过程也变得更加重要。当使用该代理程序的用户对受限制的工具和数据的访问权限各不同时,这一身份验证问题会更加复杂。

与其为代理使用的各种工具编写代码来处理身份验证过程和凭证管理,不如使用一个专门的工具或服务来完成任务。 身份验证管理器(Authentication Manager) 用于管理(某些资源或流程)的服务 两者;双方 这项服务专门用于存储密钥和敏感信息,同时负责获取、管理以及存储 OAuth 访问令牌或刷新令牌。欲了解更多相关信息,请…… 代理身份(Agent Identity)集成 使用 ADK(Adobe Digital Kit)。

自我管理的身份验证(即用户自行控制自己的身份验证过程)

如果您决定使用 ADK 辅助函数和自己的代码来管理身份验证过程,请考虑以下建议:

  • API 密钥和客户端密钥: 对于在 ADK 代码中使用的任何 API 密钥和客户端密钥,在本地计算环境中运行时,请使用本地的(即非远程的)密钥/凭据。 .env 该文件已被排除在版本控制之外。当您的代理程序托管在或处于生产环境中时,请使用“秘密管理器”(secret manager)来存储敏感信息。有关“秘密管理器”的更多详细信息,请参阅相关文档。 下一节.
  • 交互式身份验证: 在使用交互式的三方认证(3LO)机制(如 OAuth 或 OpenID Connect (OIDC))对工具进行身份验证时,应在客户端应用程序中编写相应的服务代码,用于获取、管理访问权限以及刷新访问令牌。请确保将这些令牌与经过身份验证的用户标识符一起存储在加密数据库中。

秘密管理器服务(Secrets Manager Services)

对于生产环境来说,如果您没有使用特定的工具或技术(此处“if you are not using an”后应补充具体内容),那么您可能需要采取其他措施来确保系统的稳定性和安全性。 身份验证管理器(Authentication Manager) 对于这些服务,您应该将凭据存储在专门的“秘密管理器”(secret manager)服务中,以保护这些数据的安全。通过这种方式,“秘密管理器”可以安全地存储代理程序所需使用的任何工具或服务的凭据;这些凭据不会存储在代理程序的运行内存中。例如,使用这种方法的自定义 ADK 工具仅会在会话内存中持有有效期较短的访问令牌或安全引用,并在需要时从“秘密管理器”中获取有效期较长的刷新令牌。在选择“秘密管理器”时,建议选择来自知名供应商的产品。 Google Cloud Secret Manager 或其他秘密管理服务。

本地加密密钥存储

对于对安全性要求不高的代理应用程序来说,将凭据存储在本地加密存储空间中是一个可行的选择。可以考虑使用专门的本地秘密存储系统,或者使用可靠的加密库对本地数据库中的数据进行加密;同时,通过密钥管理服务来安全地管理这些加密密钥。需要注意的是:仅将短期有效的访问令牌保留在操作内存中,而长期有效的凭据及刷新令牌则应仅在需要时从本地加密存储空间中获取。

内存中的密钥(即存储在内存中的敏感信息)

这个方法 仅应在项目的早期开发阶段使用。 以及对你所使用的代理程序(agent)的测试。采用这种方法,凭据(credentials)会被存储在当前的环境中。 InMemorySessionService 该数据仅存在于会话内存中(即仅在当前会话期间有效),并不会被持久化存储。不过,在使用这种方法时,您需要仔细考虑以下风险:代理会话的持续时间、哪些用户可以访问该代理,以及代理运行所在环境的安全性。

框架组件(Framework components)

在 ADK 框架内, AuthScheme, AuthCredential,以及 BaseCredentialService 这些是处理身份验证(authentication)方法和管理凭证数据(credential data)的关键组件。

  • AuthScheme:定义 如何;怎样 一个 API 需要身份验证凭据,例如请求头中的 API 密钥(API Key)或 OAuth 2.0 的承载令牌(Bearer token)。ADK 支持与 OpenAPI 3.0 相同的身份验证方案,并为各种类型的凭据使用了专门的类来进行处理。 APIKey, HTTPBearer, OAuth2,以及 OpenIdConnectWithConfig前三个是从其他地方导入的 OpenAPI 模型。 fastapi.openapi.models; 只有 OpenIdConnectWithConfig 该功能由 ADK(Android Development Kit)定义。 google.adk.auth有关每种 OpenAPI 凭据类型的更多详细信息,请参阅…… OpenAPI 文档:身份验证(Authentication).

  • AuthCredential:用于存储(或容纳)某些内容。 initial 所需的信息: 开始 认证过程所需的参数,例如您的应用程序的 OAuth 客户端 ID(Client ID)或密钥(Secret),或者 API 密钥(API Key)。该类的一个实例包含了这些认证所需的信息。 auth_type例如: API_KEY, OAUTH2, SERVICE_ACCOUNT需要指定凭证的类型。

  • BaseCredentialService:控件 where ADK 会在凭证交换完成后将其存储起来。随后,需要将相应的实现代码传递给运行器(runner)。 Runner(credential_service=...)ADK 提供了…… InMemoryCredentialService 在……里面;处于……状态 google.adk.auth.credential_service.in_memory_credential_service 和 SessionStateCredentialService 在……里面;处于……状态 google.adk.auth.credential_service.session_state_credential_service如果您将凭据存储在会话状态(session state)中,请确保会话存储数据在静止状态下(即未使用时)已被加密,并且不会被不可信的客户端访问。该组件目前仍处于实验阶段,未来版本中可能会发生变化。

一般的身份验证流程包括在配置工具时提供这些详细信息。随后,ADK 会尝试在工具发起 API 调用之前自动交换初始凭证(例如访问令牌)。对于需要用户交互的流程(包括获取 OAuth 同意的过程),ADK 会触发特定的交互式流程。 代理客户端(Agent Client) application.

支持的初始凭证类型

  • API_KEY: 提供简单的键值认证机制,这种机制通常不需要进行任何认证信息的交换(即不需要双方互相传递认证数据)。
  • HTTP: 该功能提供了基本身份验证(Basic Auth)功能,但这种验证方式并不被推荐使用;此外,对于某些交换平台来说,可能不支持这种验证方式,或者这些平台已经使用了“Bearer Tokens”(无需身份验证的令牌)。使用“Bearer Tokens”时,根本不需要进行身份验证过程。
  • OAUTH2: 提供了标准的 OAuth 2.0 认证流程,并需要使用客户端 ID(client ID)、密钥(secret)以及权限范围(scopes)进行配置。该方法通常会触发一个交互式流程,以获取用户的同意。
  • OPEN_ID_CONNECT: 该服务基于 OpenID Connect 提供身份验证功能。 与 OAuth2 类似,这种身份验证方式通常需要用户进行相应的配置操作并参与交互过程。
  • SERVICE_ACCOUNT: 提供 Google Cloud 服务账户的凭据,形式可以是 JSON 格式的密钥,也可以是应用程序默认的凭据(Application Default Credentials)。这种类型的凭据通常使用“Bearer Token”(承载令牌)进行身份验证。

工具与集成快速指南

以下是关于 ADK(Adobe Digital Kit)工具集身份验证功能的快速指南:

  • RestApiTool: 设置 auth_scheme 和 auth_credential 在初始化过程中
  • OpenAPIToolset: 设置 auth_scheme 和 auth_credential 在初始化过程中
  • APIHubToolset: 设置 auth_scheme 和 auth_credential 在初始化过程中, if 该 API 需要身份验证。
  • ApplicationIntegrationToolset: 设置 auth_scheme 和 auth_credential 在初始化过程中, if 该 API 需要身份验证。
  • Google Apps Toolset使用该工具集提供的特定认证方法。

有关其他预构建工具和集成的更多身份验证详细信息,请参阅…… ADK集成 catalog.


使用经过身份验证的工具来构建具有代理功能的应用程序(即能够代表用户执行某些操作的应用程序)。

本节重点介绍如何使用现有的工具(例如那些来自……的工具)。 RestApiTool/ OpenAPIToolset, APIHubToolset, Google Apps Toolset这些功能需要在您的代理应用程序中进行身份验证。您的主要职责是配置相关工具,并处理交互式身份验证流程中的客户端部分(如果工具有此要求)。

配置具有身份验证功能的工具

在将经过身份验证的工具添加到您的代理程序中时,您需要提供该工具所需的所有信息。 AuthScheme 以及您的应用程序的初始状态(或配置信息等)。 AuthCredential.

您可以根据所使用的工具集类型(基于 OpenAPI 的工具集或 Google API 的工具集),以及被 Cloud IAM 保护的服务的具体需求,来配置不同的身份验证方式(例如:服务是否需要使用 ID Token 而不是 Access Token)。以下各小节将分别介绍这些情况。

使用基于 OpenAPI 的工具集

在工具集初始化过程中,需要传递相应的方案(scheme)和凭据(credential);工具集会将这些信息应用于所有生成的工具。以下是几种在 ADK 中创建具有身份验证功能的工具的方法。

创建一个工具,该工具需要使用 API 密钥进行简单身份验证,且无需进行令牌交换(即无需在客户端和服务器之间传递额外的令牌信息)。

from google.adk.tools.openapi_tool.auth.auth_helpers import token_to_scheme_credential
from google.adk.tools.openapi_tool.openapi_spec_parser.openapi_toolset import OpenAPIToolset

auth_scheme, auth_credential = token_to_scheme_credential(
    "apikey", "query", "apikey", "YOUR_API_KEY_STRING"
)
sample_api_toolset = OpenAPIToolset(
    spec_str="...",  # Fill this with an OpenAPI spec string
    spec_str_type="yaml",
    auth_scheme=auth_scheme,
    auth_credential=auth_credential,
)

需要创建一个工具,该工具必须使用 OAuth 2.0 授权码流程来代表人类用户进行交互式身份验证。

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

auth_scheme = OAuth2(
    flows=OAuthFlows(
        authorizationCode=OAuthFlowAuthorizationCode(
            authorizationUrl="https://accounts.google.com/o/oauth2/auth",
            tokenUrl="https://oauth2.googleapis.com/token",
            scopes={
                "https://www.googleapis.com/auth/calendar": "calendar scope"
            },
        )
    )
)
auth_credential = AuthCredential(
    auth_type=AuthCredentialTypes.OAUTH2,
    oauth2=OAuth2Auth(
        client_id=YOUR_OAUTH_CLIENT_ID,
        client_secret=YOUR_OAUTH_CLIENT_SECRET
    ),
)

calendar_api_toolset = OpenAPIToolset(
    spec_str=google_calendar_openapi_spec_str, # Fill this with an openapi spec
    spec_str_type='yaml',
    auth_scheme=auth_scheme,
    auth_credential=auth_credential,
)

创建一个工具,该工具使用 OAuth 2.0 客户端凭据授权类型(grant type)来实现非交互式的、机器对机器(machine-to-machine)身份验证。请提供相关的技术细节或资源以帮助完成开发。 client_id 和 client_secret 要获取访问令牌(access token):

from fastapi.openapi.models import (
    OAuth2,
    OAuthFlowClientCredentials,
    OAuthFlows,
)
from google.adk.auth import (
    AuthCredential,
    AuthCredentialTypes,
    OAuth2Auth,
)
from google.adk.tools.openapi_tool.openapi_spec_parser.openapi_toolset import (
    OpenAPIToolset,
)

# Define the OAuth2 scheme with the client credentials flow.
flows = OAuthFlows(
    clientCredentials=OAuthFlowClientCredentials(
        tokenUrl="https://example.com/token",  # Replace with your authorization server's token endpoint.
        scopes={"read:weather": "Read weather data"},
    )
)
auth_scheme = OAuth2(flows=flows)

# Define the AuthCredential with a client ID and client secret.
# Do not hardcode secrets: load them from a .env file locally or from a
# secrets manager in production. See "Self-managed authentication" above.
auth_credential = AuthCredential(
    auth_type=AuthCredentialTypes.OAUTH2,
    oauth2=OAuth2Auth(
        client_id="YOUR_CLIENT_ID",
        client_secret="YOUR_CLIENT_SECRET",
    ),
)

weather_toolset = OpenAPIToolset(
    spec_str="...",  # Pass your OpenAPI specification YAML string here.
    spec_str_type="yaml",
    auth_scheme=auth_scheme,
    auth_credential=auth_credential,
)

创建一个工具,该工具可以使用服务账户的 JSON 密钥或应用程序的默认凭据来以非人类身份进行身份验证。

from google.adk.tools.openapi_tool.auth.auth_helpers import service_account_dict_to_scheme_credential
from google.adk.tools.openapi_tool.openapi_spec_parser.openapi_toolset import OpenAPIToolset

service_account_cred = json.loads(service_account_json_str)
auth_scheme, auth_credential = service_account_dict_to_scheme_credential(
    config=service_account_cred,
    scopes=["https://www.googleapis.com/auth/cloud-platform"],
)
sample_toolset = OpenAPIToolset(
    spec_str=sa_openapi_spec_str, # Fill this with an openapi spec
    spec_str_type='json',
    auth_scheme=auth_scheme,
    auth_credential=auth_credential,
)

创建一个需要使用 OpenID Connect 的工具,通过授权服务器来验证用户身份。

from google.adk.auth.auth_schemes import OpenIdConnectWithConfig
from google.adk.auth.auth_credential import AuthCredential, AuthCredentialTypes, OAuth2Auth
from google.adk.tools.openapi_tool.openapi_spec_parser.openapi_toolset import OpenAPIToolset

auth_scheme = OpenIdConnectWithConfig(
    authorization_endpoint=OAUTH2_AUTH_ENDPOINT_URL,
    token_endpoint=OAUTH2_TOKEN_ENDPOINT_URL,
    scopes=['openid', 'YOUR_OAUTH_SCOPES']
)
auth_credential = AuthCredential(
    auth_type=AuthCredentialTypes.OPEN_ID_CONNECT,
    oauth2=OAuth2Auth(
        client_id="...",
        client_secret="...",
    )
)

userinfo_toolset = OpenAPIToolset(
    spec_str=content, # Fill in an actual spec
    spec_str_type='yaml',
    auth_scheme=auth_scheme,
    auth_credential=auth_credential,
)

使用 Google API 工具集

这些工具集通常具有专门的配置方法。

提示:有关如何创建 Google OAuth 客户端 ID 和密钥的信息,请参阅此指南: 获取您的 Google API 客户端 ID

# Example: Configuring Google Calendar Tools
from google.adk.tools.google_api_tool import CalendarToolset

client_id = "YOUR_GOOGLE_OAUTH_CLIENT_ID.apps.googleusercontent.com"
client_secret = "YOUR_GOOGLE_OAUTH_CLIENT_SECRET"

calendar_toolset = CalendarToolset()

# Use the specific configure method for this toolset type
calendar_toolset.configure_auth(
    client_id=client_id, client_secret=client_secret
)

# agent = LlmAgent(..., tools=[calendar_toolset])

使用 ID 令牌

如果您的代理程序尝试访问某些受限制的服务(例如私有的 Cloud Run 或 Cloud Function),那么该代理程序不仅需要验证您的权限,还需要证明您的身份。如果您正在调用通过 Cloud IAM 进行访问的服务,那么您应该使用 ID 令牌来进行身份验证。

  • 访问令牌(默认值)它会调用 Google 的 API(如 Drive 和 BigQuery)。你可以把它想象成自己的“门禁卡”——只有使用这张“门禁卡”,才能访问相应的服务或数据。

  • ID Token它会调用您自己通过 IAM(Identity and Access Management)进行身份验证的服务。可以把 IAM 想成是您的“护照”——它用于证明您的身份,从而让您能够安全地访问这些服务。

配置

要实现 ID 令牌认证,请使用以下参数配置您的 ServiceAccount,并确保指定了目标服务的 URL。 audience.

from google.adk.auth.auth_credential import ServiceAccount
from google.adk.tools.openapi_tool.auth.auth_helpers import service_account_scheme_credential
from google.adk.tools.openapi_tool.openapi_spec_parser.openapi_toolset import OpenAPIToolset

# Configure the ServiceAccount to use ID token authentication.
# Replace <YOUR_AUDIENCE_URL> with the URL of the service you are calling.
sa_config = ServiceAccount(
    use_default_credential=True,
    use_id_token=True,
    audience="<YOUR_AUDIENCE_URL>",
)

auth_scheme, auth_credential = service_account_scheme_credential(sa_config)

sample_toolset = OpenAPIToolset(
    spec_str=sa_openapi_spec_str, # Fill this with an OpenAPI spec
    spec_str_type="json",
    auth_scheme=auth_scheme,
    auth_credential=auth_credential,
)

排查身份验证错误

如果您收到身份验证错误,请确认您的服务账户在目标服务上具有“Cloud Run Invoker”或相应的权限角色。

(注:根据中文表达习惯,将 “Key takeaways” 翻译为 “核心要点” 或 “关键结论”;如果需要更正式的表述,也可以译为 “主要收获” 或 “重要成果”。)
  • 目标受众要求(Audience Requirements): The audience 这是一种安全机制,用于将令牌(token)绑定到特定的目标地址,从而防止该令牌被用于攻击其他服务。

  • 不自动刷新与标准 OAuth2 用户访问令牌不同,服务账户 ID 令牌是在请求时才被获取的。这些令牌不会通过后台定时器自动更新。

  • “流程”(The Flow)您需要定义应用程序的意图(intent),而 Android Development Kit (ADK) 负责处理与 Google 认证服务器之间的通信过程(包括身份验证等),从 Google 的认证服务器获取令牌(token),并将其添加到您的 HTTP 请求头中。

`ServiceAccount` 配置参数
  • service_account_credential 提供一个…… ServiceAccountCredential 该对象或字典(dict)包含了您的服务账户 JSON 配置文件中的所有信息。如果您在本地环境中运行程序,或者不在 Google Cloud 平台上运行程序,就需要使用这个配置文件。除非另有说明,否则这个设置是必须的。 use_default_credential 被设置为 True.

  • use_default_credential (可选):将此参数设置为 `True` 以使用应用程序的默认凭据(ADC)。如果您的代理已经在 Google Cloud 中运行(例如在 Cloud Run 或 Cloud Functions 上),则建议使用此方法,因为这样可以避免需要使用本地的密钥文件。

  • use_id_token (对于 IAM 来说这是必需的):将此值设置为 `True` 以启用基于 ID Token 的身份验证。这样,ADK 在请求 Google API 时将不再使用访问令牌(Access Token),而是使用 ID Token 来访问您自己通过 IAM 保护的服务。

  • audience (当 use_id_token=True 时为必填项):您正在调用的服务的 URL,例如: https://my-service.run.app这是一个安全机制,用于确保令牌仅对该特定目标有效。

  • scopes 在为 Google Cloud API(如 Drive 或 BigQuery)请求访问令牌时,请使用此设置。在需要使用访问令牌进行请求时,此设置是必需的。 service_account_credential如果您使用 ID 令牌来进行私有服务的身份验证,则无需设置此参数。 use_default_credential=True, scopes 默认值为“broad”(即范围较广的设置)。 cloud-platform **scope:** 对于生产环境的部署,只需设置您的工具所需的权限范围(scopes)即可。

Pair use_id_token 使用(with) audience

始终使用 use_id_token=True 和 audience “together”。如果你设置了…… use_id_token=True 没有…… audience如果设置了 ADK,将会出现错误。 audience 单独来看,ADK 会默默地忽略(某些信息或指令)。 audience 这种安全机制要求使用“访问令牌”(Access Token)来代替“身份令牌”(ID Token)。

使用外部访问令牌

The external_access_token_key 该功能允许您的代理使用运行时环境提供的现有访问令牌(例如前端应用程序提供的令牌),而无需启动新的身份验证流程。在配置完成后,凭证管理器会跳过标准的 OAuth 流程,直接从代理中获取所需的密钥。 tool_context.state 并且直接使用该令牌进行身份验证。 请在 Google 服务工具集的凭据配置(credentials config)中设置此字段。 BigQueryCredentialsConfig, SpannerCredentialsConfig, PubSubCredentialsConfig,或 GCSCredentialsConfig该配置参数的使用具有互斥性(即不能同时使用多个此类参数),且不能包含其他内容。 credentials, client_id, client_secret或者将这些参数(以及作用域参数)放在同一个配置块中。

请在您所使用的工具集的凭据配置中设置相应的密钥。以下示例以 BigQuery 为例进行说明:

from google.adk.integrations.bigquery import BigQueryCredentialsConfig
from google.adk.integrations.bigquery import BigQueryToolset

# Configure the toolset to look for "my_frontend_token" in the session state
credentials_config = BigQueryCredentialsConfig(
    # Do not hardcode authentication keys in production code
    external_access_token_key="my_frontend_token"
)
bigquery_toolset = BigQueryToolset(credentials_config=credentials_config)

身份验证请求流程

该图表展示了端到端的身份验证过程,详细记录了从用户发起请求开始,到 ADK(Active Directory Knowledge)捕获凭证请求、处理重定向流程,以及在获得授权后重新尝试执行相关操作的整个过程。

身份验证(Authentication)

在工具集层面进行身份验证

在 ADK 中得到支持。Python v1.24.0

您无需单独对每个工具进行身份验证,而可以在“工具集”(Toolset)层面一次性对整个工具集进行身份验证。 在底层实现机制中, BaseLlmFlow 会自动检查您的…… BaseToolset 出于身份验证(authentication)的要求 在……之前 它甚至会列出或执行任何可用的工具;它是通过检查工具集来完成这一操作的。 get_auth_config() `method` 如果你的工具集返回了一个……(此处应填写具体的返回值或结果类型) AuthConfig 如果对象或会话尚未具备所需的凭据(credentials),ADK框架会执行以下步骤:

  1. 暂停执行: 安全地停止当前的流程(或操作)。
  2. 请求凭据: 发布一个……(“Issues an” 是一个动词短语,后面通常需要跟具体的动作或对象,但在这里由于缺少相关信息,只能保留这个短语的结构。) adk_request_credential 该事件会发送给客户端,其交互流程与文档中详细描述的流程类似。 处理交互式的 OAuth/OIDC 流程.

这种方法为你提供了一个集中式的平台,用于为一组相关的工具定义身份验证(auth)要求。该框架负责处理身份验证流程,确保在代理程序访问工具集中的工具之前,所有必要的身份凭证(credentials)都已经准备好。

如何启用它?

要设置这个功能,需要覆盖(override)相应的代码或配置。 get_auth_config() 这是您自定义代码中的方法(method)。 BaseToolset `subclass:`

from google.adk.auth import AuthConfig
from google.adk.tools.base_toolset import BaseToolset


class MyAuthenticatedToolset(BaseToolset):
  async def get_tools(
      self, readonly_context: Optional[ReadonlyContext] = None
  ) -> list[BaseTool]:
    # ADK resolves the credential from get_auth_config() before calling this,
    # so the tools you return here can rely on it.
    return []  # Replace with the tools in your toolset.

    return AuthConfig(
        auth_scheme=auth_scheme,
        raw_auth_credential=auth_credential,
    )

处理交互式的 OAuth/OIDC 流程(客户端端)

如果某个工具需要用户登录或同意(通常使用 OAuth 2.0 或 OIDC),ADK 框架会暂停执行,并向您发送相应的通知。 代理客户端(Agent Client) 应用程序(Application):共有两种情况:

  • 代理客户端(Agent Client) 应用程序直接运行该代理程序(通过……方式)。 runner.run_async)在同一进程中运行。例如:UI 后端、CLI 应用程序或 Spark 作业等。
  • 代理客户端(Agent Client) 该应用程序通过某种方式与 ADK 的 fastapi 服务器进行交互。 /run 或者 /run_sse 虽然 ADK 的 FastAPI 服务器可以设置在同一台服务器上,也可以设置在不同的服务器上…… 代理客户端(Agent Client) 应用程序

第二种情况实际上是第一种情况的一种特殊情形(即:第二种情况可以被视为第一种情况在特定条件下的具体表现)。 /run 或者 /run_sse 该端点(endpoint)也会被调用(invokes)。 runner.run_async唯一的区别在于:

  • 是调用一个 Python 函数来运行代理(第一种情况),还是调用一个服务端点来运行代理(第二种情况)。
  • 结果事件是内存中的对象(第一种情况),还是以序列化后的 JSON 字符串的形式存在于 HTTP 响应中(第二种情况)。

以下部分主要讨论第一种情况,你应该能够很容易地将它与第二种情况对应起来。如果有必要,我们还会描述在第二种情况下需要处理的一些差异。

以下是您的客户端应用程序的详细步骤流程:

步骤 1:运行代理程序并检测身份验证请求。

  • 使用以下方法启动代理交互: runner.run_async.
  • 遍历这些被生成的(或产生的)事件。
  • 请查找一个特定的函数调用事件,该事件的函数调用具有一个特殊的名称。 adk_request_credential该事件表明需要用户的交互。你可以使用辅助函数来识别该事件并提取所需的信息。(对于第二种情况,逻辑也是类似的:你需要从 HTTP 响应中反序列化该事件数据。)
# runner = Runner(...)
# session = await session_service.create_session(...)
# content = types.Content(...) # User's initial query

print("\nRunning agent...")
events_async = runner.run_async(
    session_id=session.id, user_id='user', new_message=content
)

auth_request_function_call_id, auth_config = None, None

async for event in events_async:
    # Use helper to check for the specific auth request event
    if (auth_request_function_call := get_auth_request_function_call(event)):
        print("--> Authentication required by agent.")
        # Store the ID needed to respond later
        if not (auth_request_function_call_id := auth_request_function_call.id):
            raise ValueError(f'Cannot get function call id from function call: {auth_request_function_call}')
        # Get the AuthConfig containing the auth_uri etc.
        auth_config = get_auth_config(auth_request_function_call)
        break # Stop processing events for now, need user interaction

if not auth_request_function_call_id:
    print("\nAuth not required or agent finished.")
    # return # Or handle final response if received

辅助函数(Helper functions) helpers.py:

from google.adk.events import Event
from google.adk.auth import AuthConfig # Import necessary type
from google.genai import types

def get_auth_request_function_call(event: Event) -> types.FunctionCall:
    # Get the special auth request function call from the event
    if not event.content or not event.content.parts:
        return
    for part in event.content.parts:
        if (
            part
            and part.function_call
            and part.function_call.name == 'adk_request_credential'
            and event.long_running_tool_ids
            and part.function_call.id in event.long_running_tool_ids
        ):

            return part.function_call

def get_auth_config(auth_request_function_call: types.FunctionCall) -> AuthConfig:
    # Extracts the AuthConfig object from the arguments of the auth request function call
    if not auth_request_function_call.args or not (auth_config := auth_request_function_call.args.get('authConfig')):
        raise ValueError(f'Cannot get auth config from function call: {auth_request_function_call}')
    if isinstance(auth_config, dict):
        auth_config = AuthConfig.model_validate(auth_config)
    elif not isinstance(auth_config, AuthConfig):
        raise ValueError(f'Cannot get auth config {auth_config} is not an instance of AuthConfig.')
    return auth_config

步骤 2:将用户重定向以进行授权。

  • 获取授权 URL(Get the authorization URL)auth_uri) 来自于 auth_config 在之前的步骤中已经被提取出来了。
  • 至关重要的是,需要将您的应用程序的相关信息(或数据)添加到该列表中。 将 `redirect_uri` 作为查询参数传递给这个接口。 auth_uri. 这 redirect_uri 必须事先在您的 OAuth 提供商处进行注册(例如: Google Cloud Console, Okta 管理面板).
  • 将用户引导至这个完整的 URL(例如:在他们的浏览器中打开该页面)。
# (Continuing after detecting auth needed)

if auth_request_function_call_id and auth_config:
    # Get the base authorization URL from the AuthConfig
    base_auth_uri = auth_config.exchanged_auth_credential.oauth2.auth_uri

    if base_auth_uri:
        redirect_uri = 'http://localhost:8000/callback' # MUST match your OAuth client app config
        # Append redirect_uri (use urlencode in production)
        auth_request_uri = base_auth_uri + f'&redirect_uri={redirect_uri}'
        # Now you need to redirect your end user to this auth_request_uri or ask them to open this auth_request_uri in their browser
        # This auth_request_uri should be served by the corresponding auth provider and the end user should login and authorize your application to access their data
        # And then the auth provider will redirect the end user to the redirect_uri you provided
        # Next step: Get this callback URL from the user (or your web server handler)
    else:
         print("ERROR: Auth URI not found in auth_config.")
         # Handle error

步骤 3:处理重定向回调(客户端):

  • 您的应用程序必须具备某种机制(例如,Web服务器上的某个路由),以便处理此类请求。 redirect_uri)以便在用户通过提供商授权该应用程序后接收他们的相关信息。
  • 该服务提供商会将用户重定向到您的网站/页面。 redirect_uri 然后追加一个(“an”)。 authorization_code (并且有可能……) state, scope将这些参数作为查询参数(query parameters)添加到 URL 中。
  • “Capture the” 的意思是“捕捉”或“获取”某物(例如数据、信息或图像)。这个短语可以用于各种上下文中,例如技术、科学或日常活动。 完整的回调 URL 从这个传入的请求中获取相关信息。
  • (此步骤在主代理执行循环之外进行,通常在您的 Web 服务器或相应的回调处理程序中完成。)

步骤 4:将身份验证结果发送回 ADK(客户端)。

  • 一旦你获得了完整的回调 URL(其中包含授权码),请立即获取该授权码。 auth_request_function_call_id 以及 auth_config 该对象已在第一步(Client Step 1)中被保存下来。
  • 将捕获到的回调 URL 设置在……中。 exchanged_auth_credential.oauth2.auth_response_uri 请确保(field)也被包含在内。 exchanged_auth_credential.oauth2.redirect_uri 其中包含了您使用的重定向 URI(即用户被引导到的新网址)。
  • 创建一个…… types.Content 一个包含……的对象 types.Part 使用(with a) types.FunctionResponse.
    • `Set` name 给……;发送到…… "adk_request_credential"(注意:这是 ADK 用于进行身份验证的特殊名称,请勿使用其他名称。)
    • `Set` id 到…… auth_request_function_call_id 你成功保存了文件。
    • `Set` response 到…… 已序列化(serialized) (e.g., .model_dump())已更新 AuthConfig `object.`
  • 调用 runner.run_async 再次;又一次 在同一会话中,传递这个值。 FunctionResponse 内容如下: new_message.
# (Continuing after user interaction)

    # Simulate getting the callback URL (e.g., from user paste or web handler)
    auth_response_uri = await get_user_input(
        f'Paste the full callback URL here:\n> '
    )
    auth_response_uri = auth_response_uri.strip() # Clean input

    if not auth_response_uri:
        print("Callback URL not provided. Aborting.")
        return

    # Update the received AuthConfig with the callback details
    auth_config.exchanged_auth_credential.oauth2.auth_response_uri = auth_response_uri
    # Also include the redirect_uri used, as the token exchange might need it
    auth_config.exchanged_auth_credential.oauth2.redirect_uri = redirect_uri

    # Construct the FunctionResponse Content object
    auth_content = types.Content(
        role='user', # Role can be 'user' when sending a FunctionResponse
        parts=[
            types.Part(
                function_response=types.FunctionResponse(
                    id=auth_request_function_call_id,       # Link to the original request
                    name='adk_request_credential', # Special framework function name
                    response=auth_config.model_dump() # Send back the *updated* AuthConfig
                )
            )
        ],
    )

    # --- Resume Execution ---
    print("\nSubmitting authentication details back to the agent...")
    events_async_after_auth = runner.run_async(
        session_id=session.id,
        user_id='user',
        new_message=auth_content, # Send the FunctionResponse back
    )

    # --- Process Final Agent Output ---
    print("\n--- Agent Response after Authentication ---")
    async for event in events_async_after_auth:
        # Process events normally, expecting the tool call to succeed now
        print(event) # Print the full event for inspection

注意:包含“Resume”功能的授权响应(Authorization response with Resume feature)

如果您的 ADK 代理工作流程已按照以下要求进行配置: 简历 除了该功能外,您还必须提供调用 ID(Invocation ID)。invocation_id) 参数中包含授权信息。您提供的调用 ID(Invocation ID)必须与生成授权请求的同一调用相对应;否则,系统会使用该授权响应来启动一个新的调用。如果您的代理使用了“恢复”(Resume)功能,请考虑将调用 ID 作为参数包含在授权请求中,以便该 ID 也能被包含在授权响应中。有关使用“恢复”功能的更多详细信息,请参阅…… 恢复那些已停止工作的代理(agents)。.

步骤 5:ADK 负责令牌交换(Token Exchange)以及工具的重试(Tool Retry)操作,并获取工具的执行结果(Tool Result)。

  • ADK 接收到了…… FunctionResponse for adk_request_credential.
  • 它使用了更新后的信息。 AuthConfig (包括包含该代码的回调 URL)以完成 OAuth 授权过程。 令牌交换(Token Exchange) 通过提供商提供的令牌端点(token endpoint),获取访问令牌(以及可能的刷新令牌,refresh token)。
  • ADK 通过将这些令牌存储在会话状态(session state)中,使其能够在系统内部被使用。
  • ADK 会自动重试。 原始的函数调用(即最初因缺少认证信息而失败的那个调用)。
  • 这一次,该工具找到了有效的令牌(通过……方式)。 tool_context.get_auth_response(auth_config))并成功执行了经过身份验证的 API 调用。
  • 代理从工具中获取实际结果,然后生成最终回复发送给用户。

身份验证响应流程的序列图(Sequence Diagram),其中…… 代理客户端(Agent Client) 系统会返回身份验证(auth)响应,随后 ADK 会重新尝试执行该工具。具体流程如下:

身份验证(Authentication)

开发自定义工具。)FunctionTool)需要身份验证

本节重点介绍如何实现身份验证逻辑。 inside 在创建新的 ADK 工具时,您需要使用自己编写的 Python 函数。我们将实现这个功能…… FunctionTool 例如。

自动凭证处理

这个实验性的(项目/产品)…… AuthenticatedFunctionTool 在……里面;处于……状态 google.adk.tools.authenticated_function_tool “takes an” 表示“需要一个”或“需要输入某个值”。 AuthConfig 并将这些“即用型”凭据作为参数传递给你的函数。 credential argument.

先决条件

你的函数签名(Function Signature) 必须;应当 `include` tool_context: ToolContextADK 会自动注入这个对象,从而提供对系统状态(state)和身份验证机制(auth mechanisms)的访问权限。

from google.adk.tools import FunctionTool, ToolContext
from typing import Dict

def my_authenticated_tool_function(param1: str, tool_context: ToolContext) -> dict:
    # ... your logic ...
    pass

my_tool = FunctionTool(func=my_authenticated_tool_function)

工具功能中的身份验证逻辑(Authentication Logic within the Tool Function)

在你的函数中执行以下步骤:

步骤 1:检查是否已缓存有效的凭据:

在你的工具函数内部,首先检查是否已经从上一次运行中将该会话的有效凭据(例如访问令牌或刷新令牌)存储了起来。将这些凭据存储在当前会话中。 tool_context.state这是一个包含各种状态的字典。请使用该字典来检查是否存在有效的凭据(credentials)。 tool_context.state.get(credential_name, None).

from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request

# Inside your tool function
TOKEN_CACHE_KEY = "my_tool_tokens" # Choose a unique key
SCOPES = ["scope1", "scope2"] # Define required scopes

creds = None
cached_token_info = tool_context.state.get(TOKEN_CACHE_KEY)
if cached_token_info:
    try:
        creds = Credentials.from_authorized_user_info(cached_token_info, SCOPES)
        if not creds.valid and creds.expired and creds.refresh_token:
            creds.refresh(Request())
            tool_context.state[TOKEN_CACHE_KEY] = json.loads(creds.to_json()) # Update cache
        elif not creds.valid:
            creds = None # Invalid, needs re-auth
            tool_context.state[TOKEN_CACHE_KEY] = None
    except Exception as e:
        print(f"Error loading/refreshing cached creds: {e}")
        creds = None
        tool_context.state[TOKEN_CACHE_KEY] = None

if creds and creds.valid:
    # Skip to Step 5: Make Authenticated API Call
    pass
else:
    # Proceed to Step 2...
    pass

步骤 2:检查客户端是否返回了身份验证(Auth)响应。

  • 如果第一步没有生成有效的凭据,请检查客户端是否已经完成了交互式流程(即是否已经完成了所有必要的操作)。 exchanged_credential = tool_context.get_auth_response(auth_config).
  • 这会返回更新后的内容。 exchanged_credential 客户端返回的对象(其中包含回调 URL): auth_response_uri).
# Use auth_scheme and auth_credential configured in the tool.
# exchanged_credential: AuthCredential | None

exchanged_credential = tool_context.get_auth_response(AuthConfig(
  auth_scheme=auth_scheme,
  raw_auth_credential=auth_credential,
))
# If exchanged_credential is not None, then there is already an exchanged credential from the auth response.
if exchanged_credential:
   # ADK exchanged the access token already for us
        access_token = exchanged_credential.oauth2.access_token
        refresh_token = exchanged_credential.oauth2.refresh_token
        creds = Credentials(
            token=access_token,
            refresh_token=refresh_token,
            token_uri=auth_scheme.flows.authorizationCode.tokenUrl,
            client_id=auth_credential.oauth2.client_id,
            client_secret=auth_credential.oauth2.client_secret,
            scopes=list(auth_scheme.flows.authorizationCode.scopes.keys()),
        )
    # Cache the token in session state and call the API, skip to step 5

步骤 3:发起身份验证请求

如果未找到有效的凭据(步骤 1)或身份验证响应(步骤 2),则该工具需要启动 OAuth 流程。请定义 `AuthScheme` 和初始的 `AuthCredential`,然后调用相应的函数。 tool_context.request_credential()返回一个响应,表明需要授权。

# Use auth_scheme and auth_credential configured in the tool.

def my_authenticated_tool_function(tool_context: ToolContext) -> dict:
    tool_context.request_credential(AuthConfig(
        auth_scheme=auth_scheme,
        raw_auth_credential=auth_credential,
    ))
    return {'pending': True, 'message': 'Awaiting user authentication.'}

# By setting request_credential, ADK detects a pending authentication event. It pauses execution and ask end user to login.

步骤 4:用授权码换取令牌(Exchange the Authorization Code for Tokens)

ADK 会自动生成 OAuth 授权 URL,并将其展示给您的用户。 代理客户端(Agent Client) application.your 代理客户端(Agent Client) 应用程序应遵循上述描述中的相同方法进行操作。 使用经过身份验证的工具来构建具有代理功能的应用程序(即能够代表用户执行某些操作的应用程序)。 将用户重定向到授权 URL(并附带相关参数)。 redirect_uri (已添加)。一旦用户完成登录流程,ADK 会从相关数据中提取身份验证回调 URL。 代理客户端(Agent Client) 应用程序会自动解析认证代码(auth code),并生成相应的认证令牌(auth token)。在下一次调用该工具时,系统会使用这个生成的认证令牌来进行身份验证。 tool_context.get_auth_response 在第二步中,会生成一个有效的凭据(credential),用于后续的 API 调用。

步骤 5:将获取到的凭据缓存起来

在成功从 ADK 获取令牌(步骤 2)之后,或者当令牌仍然有效时(步骤 1), 立即存储 新的 Credentials “object in” 是一个编程术语,通常用于描述某个对象被存储在另一个对象(或数据结构)中的情况。例如,在 JavaScript 中,你可以使用这样的代码来创建一个包含另一个对象的数组: ```javascript const parentObject = { childObject: { name: "John", age: 20 } }; ``` 在这个例子中,`childObject` 被存储在 `parentObject` 中。 tool_context.state (已序列化,例如以 JSON 格式存储),并使用您的缓存键进行存储。

# Inside your tool function, after obtaining 'creds' (either refreshed or newly exchanged)
# Cache the new/refreshed tokens
tool_context.state[TOKEN_CACHE_KEY] = json.loads(creds.to_json())
print(f"DEBUG: Cached/updated tokens under key: {TOKEN_CACHE_KEY}")
# Proceed to Step 6 (Make API Call)

步骤 6:发起经过身份验证的 API 调用

  • 一旦你获得了有效的……(此处“valid”后应补充具体内容,例如“许可证”、“证书”等) Credentials `object`(对象)creds 从第 1 步或第 4 步中获取该凭据),然后使用适当的客户端库(例如)通过该凭据实际调用受保护的 API。 googleapiclient, requests). 传递 credentials=creds argument.
  • 必须包含错误处理机制,尤其是针对……(请填写具体的错误类型或情况)。 HttpError 401/403 错误可能表示令牌已过期,或在两次请求之间被撤销。如果遇到此类错误,请考虑清除缓存中的令牌。tool_context.state.pop(...))并有可能返回该结果。 auth_required 再次设置状态(status),以强制用户重新进行身份验证(re-authentication)。
# Inside your tool function, using the valid 'creds' object
# Ensure creds is valid before proceeding
if not creds or not creds.valid:
   return {"status": "error", "error_message": "Cannot proceed without valid credentials."}

try:
   service = build("calendar", "v3", credentials=creds) # Example
   api_result = service.events().list(...).execute()
   # Proceed to Step 7
except Exception as e:
   # Handle API errors (e.g., check for 401/403, maybe clear cache and re-request auth)
   print(f"ERROR: API call failed: {e}")
   return {"status": "error", "error_message": f"API call failed: {e}"}

步骤 7:返回工具结果

  • 在成功执行 API 调用后,需要将返回的结果处理成字典格式,以便大型语言模型(LLM)能够使用这些数据。
  • 至关重要的是,必须包含以下内容: status 该字段会与数据一起被存储或传输。
# Inside your tool function, after successful API call
    processed_result = [...] # Process api_result for the LLM
    return {"status": "success", "data": processed_result}
完整代码
tools_and_agent.py
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os

from google.adk.auth.auth_schemes import OpenIdConnectWithConfig
from google.adk.auth.auth_credential import AuthCredential, AuthCredentialTypes, OAuth2Auth
from google.adk.tools.openapi_tool.openapi_spec_parser.openapi_toolset import OpenAPIToolset
from google.adk.agents.llm_agent import LlmAgent

# --- Authentication Configuration ---
# This section configures how the agent will handle authentication using OpenID Connect (OIDC),
# often layered on top of OAuth 2.0.

# Define the Authentication Scheme using OpenID Connect.
# This object tells the ADK *how* to perform the OIDC/OAuth2 flow.
# It requires details specific to your Identity Provider (IDP), like Google OAuth, Okta, Auth0, etc.
# Note: Replace the example Okta URLs and credentials with your actual IDP details.
# All following fields are required, and available from your IDP.
auth_scheme = OpenIdConnectWithConfig(
    # The URL of the IDP's authorization endpoint where the user is redirected to log in.
    authorization_endpoint="https://your-endpoint.okta.com/oauth2/v1/authorize",
    # The URL of the IDP's token endpoint where the authorization code is exchanged for tokens.
    token_endpoint="https://your-token-endpoint.okta.com/oauth2/v1/token",
    # The scopes (permissions) your application requests from the IDP.
    # 'openid' is standard for OIDC. 'profile' and 'email' request user profile info.
    scopes=['openid', 'profile', "email"]
)

# Define the Authentication Credentials for your specific application.
# This object holds the client identifier and secret that your application uses
# to identify itself to the IDP during the OAuth2 flow.
# !! SECURITY WARNING: Avoid hardcoding secrets in production code. !!
# !! Use environment variables or a secret management system instead. !!
auth_credential = AuthCredential(
  auth_type=AuthCredentialTypes.OPEN_ID_CONNECT,
  oauth2=OAuth2Auth(
    client_id="CLIENT_ID",
    client_secret="CLIENT_SECRET",
  )
)


# --- Toolset Configuration from OpenAPI Specification ---
# This section defines a sample set of tools the agent can use, configured with Authentication
# from steps above.
# This sample set of tools use endpoints protected by Okta and requires an OpenID Connect flow
# to acquire end user credentials.
with open(os.path.join(os.path.dirname(__file__), 'spec.yaml'), 'r') as f:
    spec_content = f.read()

userinfo_toolset = OpenAPIToolset(
   spec_str=spec_content,
   spec_str_type='yaml',
   # ** Crucially, associate the authentication scheme and credentials with these tools. **
   # This tells the ADK that the tools require the defined OIDC/OAuth2 flow.
   auth_scheme=auth_scheme,
   auth_credential=auth_credential,
)

# --- Agent Configuration ---
# Configure and create the main LLM Agent.
root_agent = LlmAgent(
    model='gemini-2.0-flash',
    name='enterprise_assistant',
    instruction='Help user integrate with multiple enterprise systems, including retrieving user information which may require authentication.',
    tools=[userinfo_toolset],
)

# --- Ready for Use ---
# The `root_agent` is now configured with tools protected by OIDC/OAuth2 authentication.
# When the agent attempts to use one of these tools, the ADK framework will automatically
# trigger the authentication flow defined by `auth_scheme` and `auth_credential`
# if valid credentials are not already available in the session.
# The subsequent interaction flow would guide the user through the login process and handle
# token exchanging, and automatically attach the exchanged token to the endpoint defined in
# the tool.
agent_cli.py
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import asyncio
from dotenv import load_dotenv
from google.adk.artifacts.in_memory_artifact_service import InMemoryArtifactService
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.genai import types

from .helpers import is_pending_auth_event, get_function_call_id, get_function_call_auth_config, get_user_input
from .tools_and_agent import root_agent

load_dotenv()

agent = root_agent

async def async_main():
  """
  Main asynchronous function orchestrating the agent interaction and authentication flow.
  """
  # --- Step 1: Service Initialization ---
  # Use in-memory services for session and artifact storage (suitable for demos/testing).
  session_service = InMemorySessionService()
  artifacts_service = InMemoryArtifactService()

  # Create a new user session to maintain conversation state.
  session = await session_service.create_session(
      state={},  # Optional state dictionary for session-specific data
      app_name='my_app', # Application identifier
      user_id='user' # User identifier
  )

  # --- Step 2: Initial User Query ---
  # Define the user's initial request.
  query = 'Show me my user info'
  print(f"user: {query}")

  # Format the query into the Content structure expected by the ADK Runner.
  content = types.Content(role='user', parts=[types.Part(text=query)])

  # Initialize the ADK Runner
  runner = Runner(
      app_name='my_app',
      agent=agent,
      artifact_service=artifacts_service,
      session_service=session_service,
  )

  # --- Step 3: Send Query and Handle Potential Auth Request ---
  print("\nRunning agent with initial query...")
  events_async = runner.run_async(
      session_id=session.id, user_id='user', new_message=content
  )

  # Variables to store details if an authentication request occurs.
  auth_request_event_id, auth_config = None, None

  # Iterate through the events generated by the first run.
  async for event in events_async:
    # Check if this event is the specific 'adk_request_credential' function call.
    if is_pending_auth_event(event):
      print("--> Authentication required by agent.")
      auth_request_event_id = get_function_call_id(event)
      auth_config = get_function_call_auth_config(event)
      # Once the auth request is found and processed, exit this loop.
      # We need to pause execution here to get user input for authentication.
      break


  # If no authentication request was detected after processing all events, exit.
  if not auth_request_event_id or not auth_config:
      print("\nAuthentication not required for this query or processing finished.")
      return # Exit the main function

  # --- Step 4: Manual Authentication Step (Simulated OAuth 2.0 Flow) ---
  # This section simulates the user interaction part of an OAuth 2.0 flow.
  # In a real web application, this would involve browser redirects.

  # Define the Redirect URI. This *must* match one of the URIs registered
  # with the OAuth provider for your application. The provider sends the user
  # back here after they approve the request.
  redirect_uri = 'http://localhost:8000/dev-ui' # Example for local development

  # Construct the Authorization URL that the user must visit.
  # This typically includes the provider's authorization endpoint URL,
  # client ID, requested scopes, response type (e.g., 'code'), and the redirect URI.
  # Here, we retrieve the base authorization URI from the AuthConfig provided by ADK
  # and append the redirect_uri.
  # NOTE: A robust implementation would use urlencode and potentially add state, scope, etc.
  auth_request_uri = (
      auth_config.exchanged_auth_credential.oauth2.auth_uri
      + f'&redirect_uri={redirect_uri}' # Simple concatenation; ensure correct query param format
  )

  print("\n--- User Action Required ---")
  # Prompt the user to visit the authorization URL, log in, grant permissions,
  # and then paste the *full* URL they are redirected back to (which contains the auth code).
  auth_response_uri = await get_user_input(
      f'1. Please open this URL in your browser to log in:\n   {auth_request_uri}\n\n'
      f'2. After successful login and authorization, your browser will be redirected.\n'
      f'   Copy the *entire* URL from the browser\'s address bar.\n\n'
      f'3. Paste the copied URL here and press Enter:\n\n> '
  )

  # --- Step 5: Prepare Authentication Response for the Agent ---
  # Update the AuthConfig object with the information gathered from the user.
  # The ADK framework needs the full response URI (containing the code)
  # and the original redirect URI to complete the OAuth token exchange process internally.
  auth_config.exchanged_auth_credential.oauth2.auth_response_uri = auth_response_uri
  auth_config.exchanged_auth_credential.oauth2.redirect_uri = redirect_uri

  # Construct a FunctionResponse Content object to send back to the agent/runner.
  # This response explicitly targets the 'adk_request_credential' function call
  # identified earlier by its ID.
  auth_content = types.Content(
      role='user',
      parts=[
          types.Part(
              function_response=types.FunctionResponse(
                  # Crucially, link this response to the original request using the saved ID.
                  id=auth_request_event_id,
                  # The special name of the function call we are responding to.
                  name='adk_request_credential',
                  # The payload containing all necessary authentication details.
                  response=auth_config.model_dump(),
              )
          )
      ],
  )

  # --- Step 6: Resume Execution with Authentication ---
  print("\nSubmitting authentication details back to the agent...")
  # Run the agent again, this time providing the `auth_content` (FunctionResponse).
  # The ADK Runner intercepts this, processes the 'adk_request_credential' response
  # (performs token exchange, stores credentials), and then allows the agent
  # to retry the original tool call that required authentication, now succeeding with
  # a valid access token embedded.
  events_async = runner.run_async(
      session_id=session.id,
      user_id='user',
      new_message=auth_content, # Provide the prepared auth response
  )

  # Process and print the final events from the agent after authentication is complete.
  # This stream now contain the actual result from the tool (e.g., the user info).
  print("\n--- Agent Response after Authentication ---")
  async for event in events_async:
    print(event)


if __name__ == '__main__':
  asyncio.run(async_main())
helpers.py
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from google.adk.auth import AuthConfig
from google.adk.events import Event
import asyncio

# --- Helper Functions ---
async def get_user_input(prompt: str) -> str:
  """
  Asynchronously prompts the user for input in the console.

  Uses asyncio's event loop and run_in_executor to avoid blocking the main
  asynchronous execution thread while waiting for synchronous `input()`.

  Args:
    prompt: The message to display to the user.

  Returns:
    The string entered by the user.
  """
  loop = asyncio.get_event_loop()
  # Run the blocking `input()` function in a separate thread managed by the executor.
  return await loop.run_in_executor(None, input, prompt)


def is_pending_auth_event(event: Event) -> bool:
  """
  Checks if an ADK Event represents a request for user authentication credentials.

  The ADK framework emits a specific function call ('adk_request_credential')
  when a tool requires authentication that hasn't been previously satisfied.

  Args:
    event: The ADK Event object to inspect.

  Returns:
    True if the event is an 'adk_request_credential' function call, False otherwise.
  """
  # Safely checks nested attributes to avoid errors if event structure is incomplete.
  return (
      event.content
      and event.content.parts
      and event.content.parts[0] # Assuming the function call is in the first part
      and event.content.parts[0].function_call
      # The specific function name indicating an auth request from the ADK framework.
      and event.content.parts[0].function_call.name == 'adk_request_credential'
  )


def get_function_call_id(event: Event) -> str:
  """
  Extracts the unique ID of the function call from an ADK Event.

  This ID is crucial for correlating a function *response* back to the specific
  function *call* that the agent initiated to request for auth credentials.

  Args:
    event: The ADK Event object containing the function call.

  Returns:
    The unique identifier string of the function call.

  Raises:
    ValueError: If the function call ID cannot be found in the event structure.
                (Corrected typo from `contents` to `content` below)
  """
  # Navigate through the event structure to find the function call ID.
  if (
      event
      and event.content
      and event.content.parts
      and event.content.parts[0] # Use content, not contents
      and event.content.parts[0].function_call
      and event.content.parts[0].function_call.id
  ):
    return event.content.parts[0].function_call.id
  # If the ID is missing, raise an error indicating an unexpected event format.
  raise ValueError(f'Cannot get function call id from event {event}')


def get_function_call_auth_config(event: Event) -> AuthConfig:
  """
  Extracts the authentication configuration details from an 'adk_request_credential' event.

  Client should use this AuthConfig to necessary authentication details (like OAuth codes and state)
  and sent it back to the ADK to continue OAuth token exchanging.

  Args:
    event: The ADK Event object containing the 'adk_request_credential' call.

  Returns:
    An AuthConfig object populated with details from the function call arguments.

  Raises:
    ValueError: If the 'authConfig' argument cannot be found in the event.
  """
  # ADK serializes the function call arguments with `by_alias=True`, so the
  # argument key is the camelCase alias `authConfig`, not `auth_config`.
  if (
      event
      and event.content
      and event.content.parts
      and event.content.parts[0] # Use content, not contents
      and event.content.parts[0].function_call
      and event.content.parts[0].function_call.args
      and event.content.parts[0].function_call.args.get('authConfig')
  ):
    # Reconstruct the AuthConfig object using the dictionary provided in the arguments.
    # The ** operator unpacks the dictionary into keyword arguments for the constructor.
    return AuthConfig(
          **event.content.parts[0].function_call.args.get('authConfig')
      )
  raise ValueError(f'Cannot get auth config from event {event}')
openapi: 3.0.1
info:
title: Okta User Info API
version: 1.0.0
description: |-
   API to retrieve user profile information based on a valid Okta OIDC Access Token.
   Authentication is handled via OpenID Connect with Okta.
contact:
   name: API Support
   email: [email protected] # Replace with actual contact if available
servers:
- url: <substitute with your server name>
   description: Production Environment
paths:
/okta-jwt-user-api:
   get:
      summary: Get Authenticated User Info
      description: |-
      Fetches profile details for the user
      operationId: getUserInfo
      tags:
      - User Profile
      security:
      - okta_oidc:
            - openid
            - email
            - profile
      responses:
      '200':
         description: Successfully retrieved user information.
         content:
            application/json:
            schema:
               type: object
               properties:
                  sub:
                  type: string
                  description: Subject identifier for the user.
                  example: "abcdefg"
                  name:
                  type: string
                  description: Full name of the user.
                  example: "Example LastName"
                  locale:
                  type: string
                  description: User's locale, e.g., en-US or en_US.
                  example: "en_US"
                  email:
                  type: string
                  format: email
                  description: User's primary email address.
                  example: "[email protected]"
                  preferred_username:
                  type: string
                  description: Preferred username of the user (often the email).
                  example: "[email protected]"
                  given_name:
                  type: string
                  description: Given name (first name) of the user.
                  example: "Example"
                  family_name:
                  type: string
                  description: Family name (last name) of the user.
                  example: "LastName"
                  zoneinfo:
                  type: string
                  description: User's timezone, e.g., America/Los_Angeles.
                  example: "America/Los_Angeles"
                  updated_at:
                  type: integer
                  format: int64 # Using int64 for Unix timestamp
                  description: Timestamp when the user's profile was last updated (Unix epoch time).
                  example: 1743617719
                  email_verified:
                  type: boolean
                  description: Indicates if the user's email address has been verified.
                  example: true
               required:
                  - sub
                  - name
                  - locale
                  - email
                  - preferred_username
                  - given_name
                  - family_name
                  - zoneinfo
                  - updated_at
                  - email_verified
      '401':
         description: Unauthorized. The provided Bearer token is missing, invalid, or expired.
         content:
            application/json:
            schema:
               $ref: '#/components/schemas/Error'
      '403':
         description: Forbidden. The provided token does not have the required scopes or permissions to access this resource.
         content:
            application/json:
            schema:
               $ref: '#/components/schemas/Error'
components:
securitySchemes:
   okta_oidc:
      type: openIdConnect
      description: Authentication via Okta using OpenID Connect. Requires a Bearer Access Token.
      openIdConnectUrl: https://your-endpoint.okta.com/.well-known/openid-configuration
schemas:
   Error:
      type: object
      properties:
      code:
         type: string
         description: An error code.
      message:
         type: string
         description: A human-readable error message.
      required:
         - code
         - message