Azure AI Foundry 代理

Microsoft Agent框架支持创建使用Azure AI Foundry 代理服务的代理,您可以创建持久化的、基于服务的代理实例并通过服务管理的会话线程进行交流。

入门

将所需的 NuGet 包添加到项目。

dotnet add package Azure.Identity
dotnet add package Microsoft.Agents.AI.AzureAI.Persistent --prerelease

创建 Azure AI Foundry 代理

首先需要创建客户端以连接到 Azure AI Foundry 代理服务。

using System;
using Azure.AI.Agents.Persistent;
using Azure.Identity;
using Microsoft.Agents.AI;

var persistentAgentsClient = new PersistentAgentsClient(
    "https://<myresource>.services.ai.azure.com/api/projects/<myproject>",
    new AzureCliCredential());

若要使用 Azure AI Foundry 代理服务,需要在服务中创建代理资源。 可以使用 Azure.AI.Agents.Persistent SDK 或使用 Microsoft Agent Framework 帮助程序来完成此作。

使用持久化 SDK

创建永久性代理并将其检索为 AIAgent 使用 PersistentAgentsClient.

// Create a persistent agent
var agentMetadata = await persistentAgentsClient.Administration.CreateAgentAsync(
    model: "gpt-4o-mini",
    name: "Joker",
    instructions: "You are good at telling jokes.");

// Retrieve the agent that was just created as an AIAgent using its ID
AIAgent agent1 = await persistentAgentsClient.GetAIAgentAsync(agentMetadata.Value.Id);

// Invoke the agent and output the text result.
Console.WriteLine(await agent1.RunAsync("Tell me a joke about a pirate."));

使用 Agent Framework 辅助工具

还可以一步创建并返回AIAgent

AIAgent agent2 = await persistentAgentsClient.CreateAIAgentAsync(
    model: "gpt-4o-mini",
    name: "Joker",
    instructions: "You are good at telling jokes.");

重用 Azure AI Foundry 代理

可以使用其 ID 检索现有 Azure AI Foundry 代理以实现重复利用。

AIAgent agent3 = await persistentAgentsClient.GetAIAgentAsync("<agent-id>");

使用代理

代理是标准的AIAgent,支持所有标准AIAgent操作。

有关如何运行和与代理交互的详细信息,请参阅 代理入门教程

配置

环境变量

在使用 Azure AI Foundry 代理之前,需要设置以下环境变量:

export AZURE_AI_PROJECT_ENDPOINT="https://<your-project>.services.ai.azure.com/api/projects/<project-id>"
export AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini"

或者,可以直接在代码中提供这些值。

Installation

将 Agent Framework Azure AI 包添加到项目:

pip install agent-framework-azure-ai --pre

入门

Authentication

Azure AI Foundry 代理使用 Azure 凭据进行身份验证。 最简单的方法是在运行AzureCliCredential后使用az login

from azure.identity.aio import AzureCliCredential

async with AzureCliCredential() as credential:
    # Use credential with Azure AI agent client

创建 Azure AI Foundry 代理

基本代理创建

创建代理的最简单方法是使用 AzureAIAgentClient 和环境变量:

import asyncio
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import AzureCliCredential

async def main():
    async with (
        AzureCliCredential() as credential,
        AzureAIAgentClient(async_credential=credential).create_agent(
            name="HelperAgent",
            instructions="You are a helpful assistant."
        ) as agent,
    ):
        result = await agent.run("Hello!")
        print(result.text)

asyncio.run(main())

显式配置

还可以显式提供配置,而不是使用环境变量:

import asyncio
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import AzureCliCredential

async def main():
    async with (
        AzureCliCredential() as credential,
        AzureAIAgentClient(
            project_endpoint="https://<your-project>.services.ai.azure.com/api/projects/<project-id>",
            model_deployment_name="gpt-4o-mini",
            async_credential=credential,
            agent_name="HelperAgent"
        ).create_agent(
            instructions="You are a helpful assistant."
        ) as agent,
    ):
        result = await agent.run("Hello!")
        print(result.text)

asyncio.run(main())

使用现有的 Azure AI Foundry 代理

按 ID 使用现有代理

如果 Azure AI Foundry 中有现有代理,可以通过提供其 ID 来使用它:

import asyncio
from agent_framework import ChatAgent
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import AzureCliCredential

async def main():
    async with (
        AzureCliCredential() as credential,
        ChatAgent(
            chat_client=AzureAIAgentClient(
                async_credential=credential,
                agent_id="<existing-agent-id>"
            ),
            instructions="You are a helpful assistant."
        ) as agent,
    ):
        result = await agent.run("Hello!")
        print(result.text)

asyncio.run(main())

创建和管理持久代理

若要更好地控制代理生命周期,可以使用 Azure AI Projects 客户端创建永久性代理:

import asyncio
import os
from agent_framework import ChatAgent
from agent_framework.azure import AzureAIAgentClient
from azure.ai.projects.aio import AIProjectClient
from azure.identity.aio import AzureCliCredential

async def main():
    async with (
        AzureCliCredential() as credential,
        AIProjectClient(
            endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
            credential=credential
        ) as project_client,
    ):
        # Create a persistent agent
        created_agent = await project_client.agents.create_agent(
            model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
            name="PersistentAgent",
            instructions="You are a helpful assistant."
        )

        try:
            # Use the agent
            async with ChatAgent(
                chat_client=AzureAIAgentClient(
                    project_client=project_client,
                    agent_id=created_agent.id
                ),
                instructions="You are a helpful assistant."
            ) as agent:
                result = await agent.run("Hello!")
                print(result.text)
        finally:
            # Clean up the agent
            await project_client.agents.delete_agent(created_agent.id)

asyncio.run(main())

代理功能

函数工具

可以向 Azure AI Foundry 代理提供自定义函数工具:

import asyncio
from typing import Annotated
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import AzureCliCredential
from pydantic import Field

def get_weather(
    location: Annotated[str, Field(description="The location to get the weather for.")],
) -> str:
    """Get the weather for a given location."""
    return f"The weather in {location} is sunny with a high of 25°C."

async def main():
    async with (
        AzureCliCredential() as credential,
        AzureAIAgentClient(async_credential=credential).create_agent(
            name="WeatherAgent",
            instructions="You are a helpful weather assistant.",
            tools=get_weather
        ) as agent,
    ):
        result = await agent.run("What's the weather like in Seattle?")
        print(result.text)

asyncio.run(main())

代码解释器

Azure AI Foundry 代理通过托管代码解释器支持代码执行:

import asyncio
from agent_framework import HostedCodeInterpreterTool
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import AzureCliCredential

async def main():
    async with (
        AzureCliCredential() as credential,
        AzureAIAgentClient(async_credential=credential).create_agent(
            name="CodingAgent",
            instructions="You are a helpful assistant that can write and execute Python code.",
            tools=HostedCodeInterpreterTool()
        ) as agent,
    ):
        result = await agent.run("Calculate the factorial of 20 using Python code.")
        print(result.text)

asyncio.run(main())

流式处理响应

使用流式处理生成时立即获取响应:

import asyncio
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import AzureCliCredential

async def main():
    async with (
        AzureCliCredential() as credential,
        AzureAIAgentClient(async_credential=credential).create_agent(
            name="StreamingAgent",
            instructions="You are a helpful assistant."
        ) as agent,
    ):
        print("Agent: ", end="", flush=True)
        async for chunk in agent.run_stream("Tell me a short story"):
            if chunk.text:
                print(chunk.text, end="", flush=True)
        print()

asyncio.run(main())

使用代理

代理是标准 BaseAgent 代理,支持所有标准代理操作。

有关如何运行和与代理交互的详细信息,请参阅 代理入门教程

后续步骤