AgentGroupChat 业务流程迁移指南

这是针对已在语义内核中使用 AgentGroupChat 并想要过渡到新 GroupChatOrchestration开发人员的迁移指南。 新类提供了一种更灵活、更强大的方法来管理代理之间的群组聊天交互。

AgentGroupChat 中迁移到 GroupChatOrchestration

新的GroupChatOrchestration类替换了AgentGroupChat,具有统一且可扩展的编排模型。 下面介绍如何迁移 C# 代码:

步骤 1:替换 using 语句和类引用

  • 删除任何using语句或对AgentChatAgentGroupChat的引用。 例如,删除以下项:

    using Microsoft.SemanticKernel.Agents.Chat;
    
  • 添加对新编排命名空间的引用:

    using Microsoft.SemanticKernel.Agents.Orchestration.GroupChat;
    

步骤 2:更新初始化

之前:

AgentGroupChat chat = new(agentWriter, agentReviewer)
{
    ExecutionSettings = new()
    {
        SelectionStrategy = new CustomSelectionStrategy(),
        TerminationStrategy = new CustomTerminationStrategy(),
    }
};

之后:

using Microsoft.SemanticKernel.Agents.Orchestration.GroupChat;

GroupChatOrchestration orchestration = new(
    new RoundRobinGroupChatManager(),
    agentWriter,
    agentReviewer);

步骤 3:启动群组聊天

之前:

chat.AddChatMessage(input);
await foreach (var response in chat.InvokeAsync())
{
    // handle response
}

之后:

using Microsoft.SemanticKernel.Agents.Orchestration;
using Microsoft.SemanticKernel.Agents.Runtime.InProcess;

InProcessRuntime runtime = new();
await runtime.StartAsync();

OrchestrationResult<string> result = await orchestration.InvokeAsync(input, runtime);
string text = await result.GetValueAsync(TimeSpan.FromSeconds(timeout));

步骤 4:自定义编排

通过新的业务流程模型,可以通过子类化 GroupChatManager 和重写其方法,为终止、代理选择等创建自定义策略。 有关更多详细信息,请参阅 GroupChatOrchestration 文档

步骤 5:删除弃用的 API

删除任何直接操作 AgentGroupChat 特定属性或方法的代码,因为它们不再支持。

步骤 6:查看和测试

  • 检查代码中是否仍包含对旧类的引用。
  • 测试群聊方案,以确保新的业务流程按预期方式运行。

完整示例

本指南演示了如何将Step03_Chat.cs的核心逻辑从AgentGroupChat迁移到新的GroupChatOrchestration,其中包括一个实现基于审批终止策略的自定义群组聊天管理器。

步骤 1:代理定义

代理定义中不需要更改。 可以继续使用这两个AgentWriterAgentReviewer,就像以前一样。

步骤 2:实现自定义群组聊天管理器

创建自定义 GroupChatManager ,当最后一条消息包含“批准”且只有审核者可以批准时,终止聊天。

private sealed class ApprovalGroupChatManager : RoundRobinGroupChatManager
{
    private readonly string _approverName;
    public ApprovalGroupChatManager(string approverName)
    {
        _approverName = approverName;
    }

    public override ValueTask<GroupChatManagerResult<bool>> ShouldTerminate(ChatHistory history, CancellationToken cancellationToken = default)
    {
        var last = history.LastOrDefault();
        bool shouldTerminate = last?.AuthorName == _approverName &&
            last.Content?.Contains("approve", StringComparison.OrdinalIgnoreCase) == true;
        return ValueTask.FromResult(new GroupChatManagerResult<bool>(shouldTerminate)
        {
            Reason = shouldTerminate ? "Approved by reviewer." : "Not yet approved."
        });
    }
}

步骤 3:初始化业务流程

AgentGroupChat 初始化替换为:

var orchestration = new GroupChatOrchestration(
    new ApprovalGroupChatManager(ReviewerName)
    {
        MaximumInvocationCount = 10
    },
    agentWriter,
    agentReviewer);

步骤 4:运行业务流程

将消息循环替换为:

var runtime = new InProcessRuntime();
await runtime.StartAsync();

var result = await orchestration.InvokeAsync("concept: maps made out of egg cartons.", runtime);
string text = await result.GetValueAsync(TimeSpan.FromSeconds(60));
Console.WriteLine($"\n# RESULT: {text}");

await runtime.RunUntilIdleAsync();

概要

  • 使用自定义 GroupChatManager 进行基于审批的终止。
  • 将聊天循环替换为编排调用。
  • 代理设置的其余部分和消息格式可能保持不变。

AgentGroupChat 中迁移到 GroupChatOrchestration

Python 中的新 GroupChatOrchestration API 取代了较旧的 AgentGroupChat 模式,提供了一种更灵活且可扩展的方法来管理多代理对话。 下面介绍如何迁移代码:

步骤 1:替换导入和类引用

  • 删除对AgentGroupChat及其相关策略的任何导入或引用。 例如,删除以下项:

    from semantic_kernel.agents import AgentGroupChat
    
  • 导入新的编排类

    from semantic_kernel.agents import GroupChatOrchestration, RoundRobinGroupChatManager
    from semantic_kernel.agents.runtime import InProcessRuntime
    

步骤 2:更新初始化

AgentGroupChat替换为GroupChatOrchestrationGroupChatManager(例如,RoundRobinGroupChatManager或自定义的)以控制流程。

之前:

group_chat = AgentGroupChat(
    agents=[agent_writer, agent_reviewer],
    termination_strategy=CustomTerminationStrategy(),
    selection_strategy=CustomSelectionStrategy(),
)

之后:

from semantic_kernel.agents import GroupChatOrchestration, RoundRobinGroupChatManager

orchestration = GroupChatOrchestration(
    members=[agent_writer, agent_reviewer],
    manager=RoundRobinGroupChatManager(),
)

步骤 3:启动群组聊天

之前:

await group_chat.add_chat_message(message=TASK)
async for content in group_chat.invoke():
    # handle response

之后:

from semantic_kernel.agents.runtime import InProcessRuntime

runtime = InProcessRuntime()
runtime.start()

orchestration_result = await group_chat_orchestration.invoke(task=TASK, runtime=runtime)
value = await orchestration_result.get()

步骤 4:自定义编排

通过新的业务流程模型,可以通过子类化 GroupChatManager 和重写其方法,为终止、代理选择等创建自定义策略。 有关更多详细信息,请参阅 GroupChatOrchestration 文档

步骤 5:删除弃用的 API

删除任何直接操作 AgentGroupChat 特定属性或方法的代码,因为它们不再维护。

步骤 6:查看和测试

  • 检查代码是否还有对旧类的遗留引用。
  • 测试群聊方案,以确保新的业务流程按预期方式运行。

完整示例

本指南演示了如何将step06_chat_completion_agent_group_chat.py的核心逻辑从AgentGroupChat迁移到新的GroupChatOrchestration,其中包括一个实现基于审批终止策略的自定义群组聊天管理器。

步骤 1:代理定义

代理定义中不需要更改。 可以继续使用这两个AgentWriterAgentReviewer,就像以前一样。

步骤 2:实现自定义群组聊天管理器

创建在最后一条消息包含“已批准”且只有审阅者可以批准时终止聊天的自定义 GroupChatManager

from semantic_kernel.agents import RoundRobinGroupChatManager, BooleanResult

class ApprovalGroupChatManager(RoundRobinGroupChatManager):
    def __init__(self, approver_name: str, max_rounds: int = 10):
        super().__init__(max_rounds=max_rounds)
        self._approver_name = approver_name

    async def should_terminate(self, chat_history):
        last = chat_history[-1] if chat_history else None
        should_terminate = (
            last is not None and
            getattr(last, 'name', None) == self._approver_name and
            'approved' in (last.content or '').lower()
        )
        return BooleanResult(result=should_terminate, reason="Approved by reviewer." if should_terminate else "Not yet approved.")

步骤 3:初始化业务流程

AgentGroupChat 初始化替换为:

from semantic_kernel.agents import GroupChatOrchestration
from semantic_kernel.agents.runtime import InProcessRuntime

orchestration = GroupChatOrchestration(
    members=[agent_writer, agent_reviewer],
    manager=ApprovalGroupChatManager(approver_name=REVIEWER_NAME, max_rounds=10),
)

步骤 4:运行业务流程

将消息循环替换为:

runtime = InProcessRuntime()
runtime.start()

orchestration_result = await orchestration.invoke(
    task="a slogan for a new line of electric cars.",
    runtime=runtime,
)

value = await orchestration_result.get()
print(f"***** Result *****\n{value}")

await runtime.stop_when_idle()

概要

  • 使用自定义 GroupChatManager 进行基于审批的终止。
  • 将聊天循环替换为编排调用。
  • 代理设置的其余部分和消息格式可能保持不变。

注释

代理协调功能在 Java SDK 中尚未可用。