主题
设置 Agent Auth
使用 Agent Auth 通过 OAuth 2.0 凭据,让智能体安全访问任何系统。
NOTE
Agent Auth 处于 beta 阶段,正在积极开发中。如需提供反馈或使用此功能,请联系 LangChain 团队。
安装
bash
pip install langchain-authbash
uv add langchain-auth快速开始
1. 初始化客户端
python
from langchain_auth import Client
client = Client(api_key="your-langsmith-api-key")自托管配置
对于自托管 LangSmith 实例,请使用实例上的 /api-host 路径指定 API URL。
bash
export LANGSMITH_API_URL="https://your-langsmith-instance.com/api-host"然后正常初始化客户端:
python
client = Client(api_key="your-langsmith-api-key")2. 设置 OAuth 服务商
在智能体能够进行身份认证之前,你需要按以下流程配置 OAuth 服务商:
为你的 OAuth 服务商选择一个唯一标识符,以便在 LangChain 平台中使用(例如 "github-local-dev"、"google-workspace-prod")。
转到你的 OAuth 服务商的开发者控制台,并创建一个新的 OAuth 应用。
在你的 OAuth 服务商中设置回调 URL:
https://smith.langchain.com/host-oauth-callback/{provider_id}例如,如果你的 provider_id 是 "github-local-dev",请使用:
https://smith.langchain.com/host-oauth-callback/github-local-dev- 使用来自你的 OAuth 应用的凭据调用
client.create_oauth_provider():
python
new_provider = await client.create_oauth_provider(
provider_id="{provider_id}", # Provide any unique ID
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 token。首次调用时,它会引导调用方完成 OAuth 2.0 认证流程。
在 LangGraph 上下文中
默认情况下,token 通过 Assistant ID 参数限定在发起调用的智能体范围内。
python
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 explicitly specify an agent_id for agent-scoped tokens
auth_result = await client.authenticate(
provider="{provider_id}",
scopes=["scopeA"],
user_id="your_user_id",
agent_id="specific-agent-id" # Optional: explicitly set agent scope
)在执行过程中,如果需要身份认证,SDK 会抛出一个中断。智能体执行会暂停,并向用户展示 OAuth URL:

在用户完成 OAuth 身份认证且我们收到来自服务商的回调后,用户将看到认证成功页面。

随后智能体会从离开处恢复执行,并且该 token 可用于任何 API 调用。我们会存储并刷新 OAuth token,这样用户或智能体之后再次使用该服务时无需重新进行 OAuth 流程。
python
token = auth_result.token在 LangGraph 上下文之外
为带外 OAuth 流程向用户提供 auth_url。
python
auth_result = await client.authenticate(
provider="{provider_id}",
scopes=["scopeA"],
user_id="your_user_id"
)
if auth_result.status == "pending":
print(f"Complete OAuth at: {auth_result.url}")
# Wait for user to complete OAuth
completed_auth = await client.wait_for_completion(auth_result.auth_id)
print("Authentication completed!")
else:
token = auth_result.token
print(f"Already authenticated, token: {token}")故障排查
自托管:405 Method Not Allowed
如果你收到 405 Method Not Allowed 错误,请确保 LANGSMITH_API_URL 指向 /api-host 路径:
bash
export LANGSMITH_API_URL="https://your-instance.com/api-host"自托管:格式错误的 OAuth 回调 URL
请确保你的 OAuth 服务商的重定向 URI 与你的 LangSmith 实例 URL 匹配:
https://your-instance.com/host-oauth-callback/{provider_id}