跳到主要内容
代理授权处于 Beta 阶段,正在积极开发中。如需提供反馈或使用此功能,请联系 LangChain 团队

安装

从 PyPI 安装代理授权客户端库
pip install langchain-auth

快速入门

1. 初始化客户端

from langchain_auth import Client

client = Client(api_key="your-langsmith-api-key")

2. 设置 OAuth 提供商

在代理可以进行身份验证之前,您需要使用以下过程配置 OAuth 提供商
  1. 为您的 OAuth 提供商选择一个在 LangChain 平台中使用的唯一标识符(例如,“github-local-dev”,“google-workspace-prod”)。
  2. 前往您的 OAuth 提供商的开发者控制台并创建一个新的 OAuth 应用程序。
  3. 使用此结构将 LangChain 的 API 设置为可用的回调 URL
    https://api.host.langchain.com/v2/auth/callback/{provider_id}
    
    例如,如果您的 provider_id 是“github-local-dev”,请使用
    https://api.host.langchain.com/v2/auth/callback/github-local-dev
    
  4. 使用您的 OAuth 应用程序的凭据调用 client.create_oauth_provider()
new_provider = await client.create_oauth_provider(
    provider_id="{provider_id}", # Provide any unique ID. Not formally tied to the provider.
    name="{provider_display_name}", # Provide any display name
    client_id="{your_client_id}",
    client_secret="{your_client_secret}",
    auth_url="{auth_url_of_your_provider}",
    token_url="{token_url_of_your_provider}",
)

3. 从代理进行身份验证

客户端 authenticate() API 用于从预配置的提供商获取 OAuth 令牌。首次调用时,它会引导调用者完成 OAuth 2.0 身份验证流程。

在 LangGraph 上下文中

默认情况下,令牌的范围限定为使用助理 ID 参数的调用代理。
auth_result = await client.authenticate(
    provider="{provider_id}",
    scopes=["scopeA"],
    user_id="your_user_id" # Any unique identifier to scope this token to the human caller
)

# Or if you'd like a token that can be used by any agent, set agent_scoped=False
auth_result = await client.authenticate(
    provider="{provider_id}",
    scopes=["scopeA"],
    user_id="your_user_id",
    agent_scoped=False
)
在执行过程中,如果需要身份验证,SDK 将抛出 中断。代理执行暂停并向用户显示 OAuth URL: 显示 OAuth URL 的 Studio 中断 用户完成 OAuth 身份验证并收到提供商的回调后,他们将看到身份验证成功页面。 GitHub OAuth 成功页面 然后,代理从中断的地方恢复执行,令牌可用于任何 API 调用。我们存储并刷新 OAuth 令牌,以便用户或代理将来使用该服务时无需再次进行 OAuth 流程。
token = auth_result.token

在 LangGraph 上下文之外

为带外 OAuth 流程向用户提供 auth_url
# Default: user-scoped token (works for any agent under this user)
auth_result = await client.authenticate(
    provider="{provider_id}",
    scopes=["scopeA"],
    user_id="your_user_id"
)

if auth_result.needs_auth:
    print(f"Complete OAuth at: {auth_result.auth_url}")
    # Wait for completion
    completed_auth = await client.wait_for_completion(auth_result.auth_id)
    token = completed_auth.token
else:
    token = auth_result.token

以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.