重要
代理框架中的代理协调功能处于试验阶段。 它们处于积极开发阶段,在升级到预览版或候选发布阶段之前可能会发生重大变化。
在顺序业务流程中,代理在管道中组织。 每个代理反过来处理任务,将其输出传递给序列中的下一个代理。 对于每个步骤基于上一步(例如文档审阅、数据处理管道或多阶段推理)构建的工作流来说,这是理想的选择。
若要了解有关模式的详细信息,例如何时使用模式或何时避免工作负荷中的模式,请参阅 顺序业务流程。
常见用例
文档先通过摘要处理代理,然后通过翻译处理代理,最后通过质量保证代理,每个代理都基于上一个处理结果构建。
学习内容
- 如何定义代理序列,每个代理都具有专用角色
- 如何协调这些代理,以便每个代理处理上一个代理的输出
- 如何观察中间输出并收集最终结果
定义你的代理
代理是按顺序处理任务的专用实体。 在这里,我们定义了三个代理:分析师、复制作者和编辑器。
小窍门
在此,使用了 ChatCompletionAgent,但您可以使用任何 代理类型。
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Agents;
using Microsoft.SemanticKernel.Agents.Orchestration;
using Microsoft.SemanticKernel.Agents.Orchestration.Sequential;
using Microsoft.SemanticKernel.Agents.Runtime.InProcess;
// Create a kernel with an AI service
Kernel kernel = ...;
ChatCompletionAgent analystAgent = new ChatCompletionAgent {
Name = "Analyst",
Instructions = "You are a marketing analyst. Given a product description, identify:\n- Key features\n- Target audience\n- Unique selling points",
Kernel = kernel,
};
ChatCompletionAgent writerAgent = new ChatCompletionAgent {
Name = "Copywriter",
Instructions = "You are a marketing copywriter. Given a block of text describing features, audience, and USPs, compose a compelling marketing copy (like a newsletter section) that highlights these points. Output should be short (around 150 words), output just the copy as a single text block.",
Kernel = kernel,
};
ChatCompletionAgent editorAgent = new ChatCompletionAgent {
Name = "Editor",
Instructions = "You are an editor. Given the draft copy, correct grammar, improve clarity, ensure consistent tone, give format and make it polished. Output the final improved copy as a single text block.",
Kernel = kernel,
};
可选:观察代理响应
可以创建一个回调,以在序列通过 ResponseCallback 属性进行时捕获代理响应。
ChatHistory history = [];
ValueTask responseCallback(ChatMessageContent response)
{
history.Add(response);
return ValueTask.CompletedTask;
}
设置顺序编排
创建一个 SequentialOrchestration 对象,提供代理以及可选的响应回调函数。
SequentialOrchestration orchestration = new(analystAgent, writerAgent, editorAgent)
{
ResponseCallback = responseCallback,
};
启动运行时
需要运行时才能管理代理的执行。 在这里,我们在调用业务流程之前使用 InProcessRuntime 并启动它。
InProcessRuntime runtime = new InProcessRuntime();
await runtime.StartAsync();
调用编排
使用您的初始任务(例如产品说明)来启动编排。 输出将按顺序流经每个代理。
var result = await orchestration.InvokeAsync(
"An eco-friendly stainless steel water bottle that keeps drinks cold for 24 hours",
runtime);
收集结果
等待编排完成并获取最终输出。
string output = await result.GetValueAsync(TimeSpan.FromSeconds(20));
Console.WriteLine($"\n# RESULT: {text}");
Console.WriteLine("\n\nORCHESTRATION HISTORY");
foreach (ChatMessageContent message in history)
{
this.WriteAgentChatMessage(message);
}
可选:停止运行时
处理完成后,停止运行时以清理资源。
await runtime.RunUntilIdleAsync();
示例输出
# RESULT: Introducing our Eco-Friendly Stainless Steel Water Bottles – the perfect companion for those who care about the planet while staying hydrated! Our bottles ...
ORCHESTRATION HISTORY
# Assistant - Analyst: **Key Features:**
- Made from eco-friendly stainless steel
- Insulation technology that maintains cold temperatures for up to 24 hours
- Reusable and sustainable design
- Various sizes and colors available (assumed based on typical offerings)
- Leak-proof cap
- BPA-free ...
# Assistant - copywriter: Introducing our Eco-Friendly Stainless ...
# Assistant - editor: Introducing our Eco-Friendly Stainless Steel Water Bottles – the perfect companion for those who care about the planet while staying hydrated! Our bottles ...
小窍门
此处提供了完整的示例代码
定义你的代理
序列中的每个代理都有特定的责任。 在此示例中,我们有:
- ConceptExtractorAgent:从产品说明中提取关键功能、目标受众和独特的销售点。
- WriterAgent:根据提取的信息撰写营销文案。
- FormatProofAgent:编辑和优化草稿副本,以便清晰和一致性。
小窍门
此处 ChatCompletionAgent 与 Azure OpenAI 一起使用,但可以使用任何 代理类型 或 模型服务。
from semantic_kernel.agents import Agent, ChatCompletionAgent
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
def get_agents() -> list[Agent]:
concept_extractor_agent = ChatCompletionAgent(
name="ConceptExtractorAgent",
instructions=(
"You are a marketing analyst. Given a product description, identify:\n"
"- Key features\n"
"- Target audience\n"
"- Unique selling points\n\n"
),
service=AzureChatCompletion(),
)
writer_agent = ChatCompletionAgent(
name="WriterAgent",
instructions=(
"You are a marketing copywriter. Given a block of text describing features, audience, and USPs, "
"compose a compelling marketing copy (like a newsletter section) that highlights these points. "
"Output should be short (around 150 words), output just the copy as a single text block."
),
service=AzureChatCompletion(),
)
format_proof_agent = ChatCompletionAgent(
name="FormatProofAgent",
instructions=(
"You are an editor. Given the draft copy, correct grammar, improve clarity, ensure consistent tone, "
"give format and make it polished. Output the final improved copy as a single text block."
),
service=AzureChatCompletion(),
)
return [concept_extractor_agent, writer_agent, format_proof_agent]
可选:观察代理响应
可以定义一个回调函数,以便在序列进行时观察每个代理,并打印输出。
from semantic_kernel.contents import ChatMessageContent
def agent_response_callback(message: ChatMessageContent) -> None:
print(f"# {message.name}\n{message.content}")
设置顺序编排
SequentialOrchestration 对象,用于传入代理和可选的响应回调。
from semantic_kernel.agents import SequentialOrchestration
agents = get_agents()
sequential_orchestration = SequentialOrchestration(
members=agents,
agent_response_callback=agent_response_callback,
)
启动运行时
启动运行时以管理代理执行。
from semantic_kernel.agents.runtime import InProcessRuntime
runtime = InProcessRuntime()
runtime.start()
调用编排
使用您的初始任务(例如产品说明)来启动编排。 输出将按顺序流经每个代理。
orchestration_result = await sequential_orchestration.invoke(
task="An eco-friendly stainless steel water bottle that keeps drinks cold for 24 hours",
runtime=runtime,
)
收集结果
等待编排完成。
value = await orchestration_result.get(timeout=20)
print(f"***** Final Result *****\n{value}")
可选:停止运行时
处理完成后,停止运行时以清理资源。
await runtime.stop_when_idle()
示例输出
# ConceptExtractorAgent
- Key Features:
- Made of eco-friendly stainless steel
- Keeps drinks cold for 24 hours
...
# WriterAgent
Keep your beverages refreshingly chilled all day long with our eco-friendly stainless steel bottles...
# FormatProofAgent
Keep your beverages refreshingly chilled all day long with our eco-friendly stainless steel bottles...
***** Final Result *****
Keep your beverages refreshingly chilled all day long with our eco-friendly stainless steel bottles...
小窍门
此处提供了完整的示例代码。
注释
代理编排在 Java SDK 中尚不可用。