通过


Microsoft Foundry 代理

Microsoft Agent Framework 支持创建使用 Foundry 代理服务的代理。 可以创建具有服务管理的聊天历史记录的持久性服务代理实例。

入门

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

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

创建 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 DefaultAzureCredential());

警告

DefaultAzureCredential 对于开发来说很方便,但在生产中需要仔细考虑。 在生产环境中,请考虑使用特定凭据(例如), ManagedIdentityCredential以避免延迟问题、意外凭据探测以及回退机制的潜在安全风险。

若要使用代理服务,需要在服务中创建代理资源。 可以使用 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.");

再利用 Foundry 代理

可以通过使用现有 Foundry 代理的 ID 来重复使用它们。

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

小窍门

有关完整的可运行示例,请参阅 .NET 示例

使用代理

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

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

配置

环境变量

在使用 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"

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

安装

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

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

入门

身份验证

Foundry 代理使用 Azure 凭据进行身份验证。 最简单的方法是在运行AzureCliCredential后使用az login。 所有 Azure AI 客户端都接受统一的credential参数,支持TokenCredentialAsyncTokenCredential或可调用令牌提供程序。令牌缓存和刷新由系统自动处理。

from azure.identity.aio import AzureCliCredential

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

创建 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(credential=credential).as_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",
            credential=credential,
            agent_name="HelperAgent"
        ).as_agent(
            instructions="You are a helpful assistant."
        ) as agent,
    ):
        result = await agent.run("Hello!")
        print(result.text)

asyncio.run(main())

使用现有铸造厂代理

使用现有代理

如果您在 Foundry 中已经有一个代理,您可以通过提供其 ID 来使用它:

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

async def main():
    async with (
        AzureCliCredential() as credential,
        Agent(
            chat_client=AzureAIAgentClient(
                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 Agent
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 Agent(
                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 项目提供程序创建代理时,可以将 default_options 设置为以启用模型推理和责任 AI 内容筛选。

用于支持推理的 reasoning 模型:

from agent_framework.azure import AzureAIProjectAgentProvider
from azure.ai.projects.models import Reasoning
from azure.identity.aio import AzureCliCredential
    async with (
        AzureCliCredential() as credential,
        AzureAIProjectAgentProvider(credential=credential) as provider,
    ):
        agent = await provider.create_agent(
    async with (
        AzureCliCredential() as credential,
        AzureAIProjectAgentProvider(credential=credential) as provider,
    ):
        agent = await provider.create_agent(

使用 rai_config 来应用配置的 RAI 策略:

from azure.ai.projects.models import RaiConfig
from azure.identity.aio import AzureCliCredential
async def main() -> None:
    print("=== Azure AI Agent with Content Filtering ===\n")

    # Replace with your RAI policy from Azure AI Foundry portal
    rai_policy_name = (
        "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/"
        "Microsoft.CognitiveServices/accounts/{accountName}/raiPolicies/{policyName}"
    )

    async with (
        AzureCliCredential() as credential,
        AzureAIProjectAgentProvider(credential=credential) as provider,
    ):
        # Create agent with content filtering enabled via default_options
        agent = await provider.create_agent(

函数工具

可以向 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(credential=credential).as_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())

代码解释器

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

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

async def main():
    async with (
        AzureCliCredential() as credential,
        AzureAIAgentClient(credential=credential) as client,
        client.as_agent(
            name="CodingAgent",
            instructions="You are a helpful assistant that can write and execute Python code.",
            tools=client.get_code_interpreter_tool(),
        ) 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(credential=credential).as_agent(
            name="StreamingAgent",
            instructions="You are a helpful assistant."
        ) as agent,
    ):
        print("Agent: ", end="", flush=True)
        async for chunk in agent.run("Tell me a short story", stream=True):
            if chunk.text:
                print(chunk.text, end="", flush=True)
        print()

asyncio.run(main())

使用代理

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

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

后续步骤