以编程方式使用文档

安装

Python

pip install langchain-auth
uv add langchain-auth

JavaScript

npm install @langchain/auth

快速入门

1. 初始化客户端

Python

from langchain_auth import Client

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

JavaScript

const client = new Client({ apiKey: 'your-langsmith-api-key' });

自托管配置

对于自托管的 LangSmith 实例,使用 /api-host 实例上的路径指定 API URL。

Environment Variable

然后正常初始化客户端:

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

Explicit Configuration (Python)

client = Client(
    api_key="your-langsmith-api-key",
    api_url="https://your-langsmith-instance.com/api-host"
)

Explicit Configuration (JavaScript)

const client = new Client({
    apiKey: 'your-langsmith-api-key',
    apiUrl: 'https://your-langsmith-instance.com/api-host'
});

2. 设置 OAuth 提供商

在代理可以进行身份验证之前,您需要使用以下流程配置 OAuth 提供商:

  1. 为您的 OAuth 提供商选择一个唯一标识符,以便在 LangChain 平台中使用(例如:"github-local-dev"、"google-workspace-prod")。
  1. 前往您的 OAuth 提供商的开发者控制台,创建一个新的 OAuth 应用程序。
  1. 在您的 OAuth 提供商中设置回调 URL:

LangSmith Cloud

https://smith.langchain.com/host-oauth-callback/{provider_id}

例如,如果您的提供商_id 为 "github-local-dev",请使用:

https://smith.langchain.com/host-oauth-callback/github-local-dev

Self-hosted

https://{your-langsmith-instance}/host-oauth-callback/{provider_id}

例如,如果您的实例是 langsmith.example.com 且提供商_id 为 "github",请使用:

https://langsmith.example.com/host-oauth-callback/github
  1. 使用 client.create_oauth_provider() 以及您的 OAuth 应用中的凭据:

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}",
)

JavaScript

const newProvider = await client.createOAuthProvider({
    providerId: '{provider_id}',  // Provide any unique ID
    name: '{provider_display_name}',  // Provide any display name
    clientId: '{your_client_id}',
    clientSecret: '{your_client_secret}',
    authUrl: '{auth_url_of_your_provider}',
    tokenUrl: '{token_url_of_your_provider}',
});

3. 从代理进行身份验证

客户端 authenticate() API 用于从预配置的提供商获取 OAuth 令牌。在第一次调用时,它会引导调用者完成 OAuth 2.0 授权流程。

在 LangGraph 上下文中

默认情况下,令牌使用 Assistant 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 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 身份验证并收到来自提供商的回调后,他们将看到身份验证成功页面。

代理随后从中断点恢复执行,令牌可用于任何 API 调用。我们存储并刷新 OAuth 令牌,以便用户或代理将来使用服务时无需再次进行 OAuth 流程。

token = auth_result.token

在 LangGraph 上下文之外

向用户提供 auth_url 以进行带外 OAuth 流程。

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}")

JavaScript

const authResult = await client.authenticate({
    provider: '{provider_id}',
    scopes: ['scopeA'],
    userId: 'your_user_id'
});

if (authResult.status === 'pending') {
    console.log(`Complete OAuth at: ${authResult.authUrl}`);
    // Wait for user to complete OAuth
    const completedAuth = await client.waitForCompletion(authResult.authId);
    console.log('Authentication completed!');
} else {
    const token = authResult.token;
    console.log(`Already authenticated, token: ${token}`);
}

故障排除

自托管:405 方法不允许

如果收到 405 Method Not Allowed 错误,请确保 LANGSMITH_API_URL 指向 /api-host path:

自托管:格式错误的 OAuth 回调 URL

确保您的 OAuth 提供商的 redirect URI 与您的 LangSmith 实例 URL 匹配:

https://your-instance.com/host-oauth-callback/{provider_id}