通过


步骤 6:托管代理

生成代理后,需要托管代理,以便用户和其他代理可以与之交互。

宿主选项

选项 Description 最适用于
A2A 协议 通过Agent-to-Agent协议暴露代理 多代理系统
OpenAI-Compatible 端点 通过聊天完成或响应 API 公开代理 与 OpenAI 兼容的客户端
Azure Functions (Durable) 将 Azure Functions 作为持久化服务运行代理 无服务器、长时间运行的任务
AG-UI 协议 生成基于 Web 的 AI 代理应用程序 Web 前端

在 ASP.NET Core 中托管

代理框架提供托管库,使你能够将 AI 代理集成到 ASP.NET Core 应用程序中。 这些库简化了通过各种协议注册、配置和公开代理的过程。

代理概述中所述, AIAgent 是代理框架的基本概念。 它定义了一个“LLM 包装器”,它处理用户输入、做出决策、调用工具,并执行其他工作来执行作并生成响应。 从 ASP.NET Core 应用程序公开 AI 代理并不简单。 托管库通过在依赖项注入容器中注册 AI 代理来解决此问题,使你能够在应用程序服务中解析和使用它们。 它们还允许你从同一容器管理代理依赖项,例如工具和会话存储。 代理可以与应用程序基础结构一起托管,与所使用的协议无关。 同样,工作流可以托管并利用应用程序的通用基础结构。

核心托管库

Microsoft.Agents.AI.Hosting 库是 ASP.NET Core 中托管 AI 代理的基础。 它提供用于 IHostApplicationBuilder 注册和配置 AI 代理和工作流的扩展。 在 ASP.NET Core 中, IHostApplicationBuilder 是表示托管应用程序和服务的生成器、管理配置、日志记录、生存期等的基本类型。

在配置代理或工作流之前,在依赖项注入容器中注册 IChatClient 。 在下面的示例中,它注册为名称 chat-model下的键控单例:

// endpoint is of 'https://<your-own-foundry-endpoint>.openai.azure.com/' format
// deploymentName is 'gpt-4o-mini' for example

IChatClient chatClient = new AzureOpenAIClient(
        new Uri(endpoint),
        new DefaultAzureCredential())
    .GetChatClient(deploymentName)
    .AsIChatClient();
builder.Services.AddSingleton(chatClient);

AddAIAgent

使用依赖项注入注册 AI 代理:

var pirateAgent = builder.AddAIAgent(
    "pirate",
    instructions: "You are a pirate. Speak like a pirate",
    description: "An agent that speaks like a pirate.",
    chatClientServiceKey: "chat-model");

该方法 AddAIAgent() 返回一个 IHostedAgentBuilder,它提供用于配置代理的扩展方法。 例如,可以将工具添加到代理:

var pirateAgent = builder.AddAIAgent("pirate", instructions: "You are a pirate. Speak like a pirate")
    .WithAITool(new MyTool()); // MyTool is a custom type derived from AITool

还可以配置会话存储(会话数据的存储):

var pirateAgent = builder.AddAIAgent("pirate", instructions: "You are a pirate. Speak like a pirate")
    .WithInMemorySessionStore();

AddWorkflow

登记协调多个代理的工作流。 工作流本质上是一个“图形”,其中每个节点都是一个 AIAgent,代理相互通信。

在此示例中,两个代理按顺序工作。 用户输入首先被发送到 agent-1,然后生成响应并将其发送到 agent-2。 然后,工作流将输出最终响应。 还有一种方法 BuildConcurrent 可以创建并发代理工作流。

builder.AddAIAgent("agent-1", instructions: "you are agent 1!");
builder.AddAIAgent("agent-2", instructions: "you are agent 2!");

var workflow = builder.AddWorkflow("my-workflow", (sp, key) =>
{
    var agent1 = sp.GetRequiredKeyedService<AIAgent>("agent-1");
    var agent2 = sp.GetRequiredKeyedService<AIAgent>("agent-2");
    return AgentWorkflowBuilder.BuildSequential(key, [agent1, agent2]);
});

将工作流公开为 AIAgent

若要将协议集成(如 A2A 或 OpenAI)与工作流配合使用,请将其转换为独立代理。 目前,工作流本身不提供类似的集成功能,因此需要执行此转换步骤:

var workflowAsAgent = builder
    .AddWorkflow("science-workflow", (sp, key) => { ... })
    .AddAsAIAgent();  // Now the workflow can be used as an agent

实现细节

托管库充当桥接外部通信协议和代理框架内部 AIAgent 实现的协议适配器。 使用托管集成库时,该库从依赖项注入中检索已注册的 AIAgent,并将其通过协议特定的中间件进行封装以翻译传入的请求和传出响应,然后调用 AIAgent 来处理请求。 此体系结构使代理实现与协议无关。

例如,将 ASP.NET Core 托管库与 A2A 协议适配器配合使用:

// Register the agent
var pirateAgent = builder.AddAIAgent("pirate",
    instructions: "You are a pirate. Speak like a pirate",
    description: "An agent that speaks like a pirate.");

// Expose via a protocol (e.g. A2A)
builder.Services.AddA2AServer();
var app = builder.Build();
app.MapA2AServer();
app.Run();

小窍门

有关无服务器托管示例,请参阅 Durable Azure Functions 示例

安装 Azure Functions 托管包:

pip install agent-framework-azurefunctions --pre

创建代理:

from agent_framework.azure import AgentFunctionApp, AzureOpenAIChatClient
from azure.identity import AzureCliCredential


# 1. Instantiate the agent with the chosen deployment and instructions.
def _create_agent() -> Any:
    """Create the Joker agent."""

    return AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
        name="Joker",
        instructions="You are good at telling jokes.",
    )

将代理注册至 AgentFunctionApp

# 2. Register the agent with AgentFunctionApp so Azure Functions exposes the required triggers.
app = AgentFunctionApp(agents=[_create_agent()], enable_health_check=True, max_poll_retries=50)

使用 Azure Functions Core Tools 在本地运行:

func start

然后调用:

curl -X POST http://localhost:7071/api/agents/Joker/run \
  -H "Content-Type: text/plain" \
  -d "Tell me a short joke about cloud computing."

小窍门

请参阅完整的可运行文件的完整示例,以及展示更多模式的Azure Functions托管示例

后续步骤

更深入:

另请参阅