跳至主要内容

在 Copilot SDK 中使用 Azure 托管身份

使用 Azure 托管标识(Entra ID)对 GitHub Copilot SDK 进行身份验证,以访问 Azure AI Foundry 模型,而不是使用静态 API 密钥。

谁可以使用此功能?

GitHub Copilot SDK 在所有 Copilot 计划中均可使用。

注意

Copilot SDK 当前处于技术预览阶段。功能和可用性可能会发生变化。

由于 Azure 部署通常使用 托管标识(Entra ID)而非长期密钥,您需要采取额外步骤才能在 Copilot SDK 中使用 BYOK 模式。由于 SDK 本身不支持 Entra ID 身份验证,您可以通过提供程序配置的承载令牌字段使用短期承载令牌(Python 中为 bearer_token,Node.js / TypeScript 和 .NET 中为 bearerToken)。

本指南展示了如何使用 Azure Identity 库中的 DefaultAzureCredential 通过 Copilot SDK 对 Azure AI Foundry 模型进行身份验证。

它是如何工作的

Azure AI Foundry 的兼容 OpenAI 的端点接受来自 Entra ID 的承载令牌,以替代静态 API 密钥。其模式如下

  1. 使用 DefaultAzureCredential 获取针对 https://cognitiveservices.azure.com/.default 范围的令牌。
  2. 在 BYOK 提供程序配置中通过承载令牌字段传递令牌(Python 中为 bearer_token,Node.js / TypeScript 和 .NET 中为 bearerToken)。
  3. 在令牌过期前刷新。令牌通常有效约一小时。

Diagram showing the authentication flow for Azure Managed Identity with the Copilot SDK.

先决条件

  • 已部署 Azure AI Foundry 资源的 Azure 订阅。
  • 已安装 Azure Identity 库(Python 使用 azure-identity,Node.js 使用 @azure/identity,.NET 使用 Azure.Identity)。
  • 已安装 Copilot SDK。欲了解更多信息,请参阅 Copilot SDK 入门指南

Python 示例

安装依赖

pip install github-copilot-sdk azure-identity

基本用法

import asyncio
import os

from azure.identity import DefaultAzureCredential
from copilot import CopilotClient, PermissionHandler

COGNITIVE_SERVICES_SCOPE = "https://cognitiveservices.azure.com/.default"

async def main():
    # Get a token using Managed Identity, Azure CLI, or other credential chain
    credential = DefaultAzureCredential()
    token = credential.get_token(COGNITIVE_SERVICES_SCOPE).token

    foundry_url = os.environ["AZURE_AI_FOUNDRY_RESOURCE_URL"]

    client = CopilotClient()
    await client.start()

    session = await client.create_session(
        on_permission_request=PermissionHandler.approve_all,
        model="gpt-4.1",
        provider={
            "type": "openai",
            "base_url": f"{foundry_url.rstrip('/')}/openai/v1/",
            "bearer_token": token,  # Short-lived bearer token
            "wire_api": "responses",
        },
    )

    response = await session.send_and_wait({"prompt": "Hello from Managed Identity!"})
    print(response.data.content)

    await client.stop()

asyncio.run(main())

AZURE_AI_FOUNDRY_RESOURCE_URL 替换为保存您 Azure AI Foundry 资源 URL 的环境变量(例如 https://myresource.openai.azure.com)。

长期运行应用的令牌刷新

承载令牌大约在一小时后过期。对于服务器或长期运行的代理,请在创建每个会话之前刷新令牌。

from azure.identity import DefaultAzureCredential
from copilot import CopilotClient, PermissionHandler

COGNITIVE_SERVICES_SCOPE = "https://cognitiveservices.azure.com/.default"

class ManagedIdentityCopilotAgent:
    """Copilot agent that refreshes Entra ID tokens for Azure AI Foundry."""

    def __init__(self, foundry_url: str, model: str = "gpt-4.1"):
        self.foundry_url = foundry_url.rstrip("/")
        self.model = model
        self.credential = DefaultAzureCredential()
        self.client = CopilotClient()

    def _get_provider_config(self) -> dict:
        """Build a provider config dict with a fresh bearer token."""
        token = self.credential.get_token(COGNITIVE_SERVICES_SCOPE).token
        return {
            "type": "openai",
            "base_url": f"{self.foundry_url}/openai/v1/",
            "bearer_token": token,
            "wire_api": "responses",
        }

    async def chat(self, prompt: str) -> str:
        """Send a prompt and return the response text."""
        # Fresh token for each session
        provider = self._get_provider_config()
        session = await self.client.create_session(
            on_permission_request=PermissionHandler.approve_all,
            model=self.model,
            provider=provider,
        )

        response = await session.send_and_wait({"prompt": prompt})
        await session.disconnect()

        return response.data.content if response else ""

Node.js / TypeScript 示例

import { DefaultAzureCredential } from "@azure/identity";
import { CopilotClient } from "@github/copilot-sdk";

const credential = new DefaultAzureCredential();
const tokenResponse = await credential.getToken(
    "https://cognitiveservices.azure.com/.default"
);

const client = new CopilotClient();

const session = await client.createSession({
    model: "gpt-4.1",
    provider: {
        type: "openai",
        baseUrl: `${process.env.AZURE_AI_FOUNDRY_RESOURCE_URL}/openai/v1/`,
        bearerToken: tokenResponse.token,
        wireApi: "responses",
    },
});

const response = await session.sendAndWait({ prompt: "Hello!" });
console.log(response?.data.content);

await client.stop();

.NET 示例

using Azure.Identity;
using GitHub.Copilot;

var credential = new DefaultAzureCredential();
var token = await credential.GetTokenAsync(
    new Azure.Core.TokenRequestContext(
        new[] { "https://cognitiveservices.azure.com/.default" }));

await using var client = new CopilotClient();
var foundryUrl = Environment.GetEnvironmentVariable("AZURE_AI_FOUNDRY_RESOURCE_URL");

await using var session = await client.CreateSessionAsync(new SessionConfig
{
    Model = "gpt-4.1",
    Provider = new ProviderConfig
    {
        Type = "openai",
        BaseUrl = $"{foundryUrl!.TrimEnd('/')}/openai/v1/",
        BearerToken = token.Token,
        WireApi = "responses",
    },
});

var response = await session.SendAndWaitAsync(
    new MessageOptions { Prompt = "Hello from Managed Identity!" });
Console.WriteLine(response?.Data.Content);

环境配置

需要以下环境变量

变量描述示例
AZURE_AI_FOUNDRY_RESOURCE_URL您的 Azure AI Foundry 资源 URLhttps://myresource.openai.azure.com

无需 API 密钥环境变量——身份验证由 DefaultAzureCredential 处理,它会自动支持

  • 托管标识(系统分配或用户分配)用于 Azure 托管的应用。
  • Azure CLIaz login)用于本地开发。
  • 环境变量AZURE_CLIENT_IDAZURE_TENANT_IDAZURE_CLIENT_SECRET)用于服务主体。
  • 工作负载身份用于 Kubernetes。

有关完整凭据链,请参阅 DefaultAzureCredential 文档

何时使用此模式

情形建议
使用托管标识的 Azure 托管应用使用此模式。
具有现有 Azure AD 服务主体的应用使用此模式。
使用 az login 的本地开发使用此模式。
使用静态 API 密钥的非 Azure 环境使用标准 BYOK。更多信息,请参阅 github/copilot-sdk 仓库中的 BYOK
GitHub Copilot 订阅可用使用 GitHub OAuth。更多信息,请参阅 github/copilot-sdk 仓库中的 GitHub OAuth

延伸阅读

© . This site is unofficial and not affiliated with GitHub, Inc.