Azure AI Foundry Agent#

在 AutoGen 中,您可以使用 AzureAIAgent 类构建和部署由 Azure AI Foundry 代理服务支持的代理。在这里,代理的重要方面,包括预配的模型、工具(例如代码解释器、必应搜索基础、文件搜索等)、可观测性和安全性都由 Azure 管理。这使您能够专注于构建代理,而无需担心底层基础设施。

在本指南中,我们将探讨一个使用 AzureAIAgent 创建 Azure AI Foundry 代理的示例,该代理可以使用 Azure Grounding with Bing Search 工具处理任务。

# pip install "autogen-ext[azure]"  # For Azure AI Foundry Agent Service

必应搜索基础#

可以为 AzureAIAgent 分配一组工具,包括 必应搜索基础

必应搜索基础允许您的 Azure AI 代理在生成响应时结合实时公共网络数据。您需要创建必应搜索基础资源,然后将此资源连接到您的 Azure AI 代理。当用户发送查询时,Azure AI 代理会决定是否应利用必应搜索基础。如果需要,它将利用必应搜索公共网络数据并返回相关片段。最后,Azure AI 代理将使用返回的片段生成响应。

先决条件#

  • 您需要一个 Azure 订阅。

  • 您需要安装并配置 Azure CLI。(同时使用命令 az login 登录以启用默认凭据)

  • 您需要安装 autogen-ext[azure] 包。

您可以在 Azure 门户中创建必应搜索基础资源。请注意,您需要拥有订阅或资源组的所有者或参与者角色才能创建它。创建资源后,您可以使用资源名称将其传递给 Azure Foundry 代理。

在以下示例中,我们将创建一个使用必应搜索基础资源的新 Azure Foundry 代理。

import os

import dotenv
from autogen_agentchat.messages import TextMessage
from autogen_core import CancellationToken
from autogen_ext.agents.azure import AzureAIAgent
from azure.ai.agents.models import BingGroundingTool
from azure.ai.projects.aio import AIProjectClient
from azure.identity.aio import DefaultAzureCredential

dotenv.load_dotenv()


async def bing_example() -> None:
    async with DefaultAzureCredential() as credential:  # type: ignore
        async with AIProjectClient(  # type: ignore
            credential=credential, endpoint=os.getenv("AZURE_PROJECT_ENDPOINT", "")
        ) as project_client:
            conn = await project_client.connections.get(name=os.getenv("BING_CONNECTION_NAME", ""))

            bing_tool = BingGroundingTool(conn.id)
            agent_with_bing_grounding = AzureAIAgent(
                name="bing_agent",
                description="An AI assistant with Bing grounding",
                project_client=project_client,
                deployment_name="gpt-4o",
                instructions="You are a helpful assistant.",
                tools=bing_tool.definitions,
                metadata={"source": "AzureAIAgent"},
            )

            # For the bing grounding tool to return the citations, the message must contain an instruction for the model to do return them.
            # For example: "Please provide citations for the answers"

            result = await agent_with_bing_grounding.on_messages(
                messages=[
                    TextMessage(
                        content="What is Microsoft's annual leave policy? Provide citations for your answers.",
                        source="user",
                    )
                ],
                cancellation_token=CancellationToken(),
                message_limit=5,
            )
            print(result)


await bing_example()

请注意,您还可以为代理提供其他 Azure 支持的工具和本地客户端功能。

有关如何创建 Azure Foundry 代理的更多详细信息,请参阅 AzureAIAgent 类 API 文档。