Poznámka:
Přístup k této stránce vyžaduje autorizaci. Můžete se zkusit přihlásit nebo změnit adresáře.
Přístup k této stránce vyžaduje autorizaci. Můžete zkusit změnit adresáře.
Důležité
Funkce orchestrace agentů v rozhraní Agent Framework jsou v experimentální fázi. Jsou ve fázi aktivního vývoje a můžou se výrazně změnit před přechodem do fáze Preview nebo release candidate.
Orchestrace předání umožňuje agentům převést řízení mezi sebou na základě kontextu nebo požadavku uživatele. Každý agent může "předat" konverzaci jinému agentu s odpovídajícími odbornými znalostmi a zajistit, aby správný agent zvládl každou část úlohy. To je zvlášť užitečné pro zákaznickou podporu, odborné systémy nebo jakýkoli scénář vyžadující dynamické delegování.
Další informace o vzoru, například kdy použít vzor nebo kdy se vyhnout vzoru ve vaší úloze, najdete v tématu Orchestrace předání.
Běžné případy použití
Agent zákaznické podpory zpracovává obecný dotaz, pak se v případě potřeby předá technickému odborníkovi na řešení potíží nebo fakturačnímu agentovi:
Co se naučíte
- Jak definovat agenty a jejich vztahy při předávání
- Jak nastavit orchestraci předání pro dynamické směrování agentů
- Jak zapojit člověka do smyčky konverzace
Definování specializovaných agentů
Každý agent zodpovídá za konkrétní oblast. V tomto příkladu definujeme agenta pro třídění, agenta refundace, agenta stavu objednávky a agenta vrácení objednávky. Někteří agenti používají moduly plug-in ke zpracování konkrétních úloh.
Návod
Tady se ChatCompletionAgent používá, ale můžete použít libovolný typ agenta.
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Agents;
using Microsoft.SemanticKernel.Agents.Orchestration;
using Microsoft.SemanticKernel.Agents.Orchestration.Handoff;
using Microsoft.SemanticKernel.Agents.Runtime.InProcess;
using Microsoft.SemanticKernel.ChatCompletion;
// Plugin implementations
public sealed class OrderStatusPlugin {
[KernelFunction]
public string CheckOrderStatus(string orderId) => $"Order {orderId} is shipped and will arrive in 2-3 days.";
}
public sealed class OrderReturnPlugin {
[KernelFunction]
public string ProcessReturn(string orderId, string reason) => $"Return for order {orderId} has been processed successfully.";
}
public sealed class OrderRefundPlugin {
[KernelFunction]
public string ProcessReturn(string orderId, string reason) => $"Refund for order {orderId} has been processed successfully.";
}
// Helper function to create a kernel with chat completion
public static Kernel CreateKernelWithChatCompletion(...)
{
...
}
ChatCompletionAgent triageAgent = new ChatCompletionAgent {
Name = "TriageAgent",
Description = "Handle customer requests.",
Instructions = "A customer support agent that triages issues.",
Kernel = CreateKernelWithChatCompletion(...),
};
ChatCompletionAgent statusAgent = new ChatCompletionAgent {
Name = "OrderStatusAgent",
Description = "A customer support agent that checks order status.",
Instructions = "Handle order status requests.",
Kernel = CreateKernelWithChatCompletion(...),
};
statusAgent.Kernel.Plugins.Add(KernelPluginFactory.CreateFromObject(new OrderStatusPlugin()));
ChatCompletionAgent returnAgent = new ChatCompletionAgent {
Name = "OrderReturnAgent",
Description = "A customer support agent that handles order returns.",
Instructions = "Handle order return requests.",
Kernel = CreateKernelWithChatCompletion(...),
};
returnAgent.Kernel.Plugins.Add(KernelPluginFactory.CreateFromObject(new OrderReturnPlugin()));
ChatCompletionAgent refundAgent = new ChatCompletionAgent {
Name = "OrderRefundAgent",
Description = "A customer support agent that handles order refund.",
Instructions = "Handle order refund requests.",
Kernel = CreateKernelWithChatCompletion(...),
};
refundAgent.Kernel.Plugins.Add(KernelPluginFactory.CreateFromObject(new OrderRefundPlugin()));
Nastavení relací předání
Použijte OrchestrationHandoffs, abyste určili, kterému agentovi lze předat úkol a za jakých okolností.
var handoffs = OrchestrationHandoffs
.StartWith(triageAgent)
.Add(triageAgent, statusAgent, returnAgent, refundAgent)
.Add(statusAgent, triageAgent, "Transfer to this agent if the issue is not status related")
.Add(returnAgent, triageAgent, "Transfer to this agent if the issue is not return related")
.Add(refundAgent, triageAgent, "Transfer to this agent if the issue is not refund related");
Sledování odpovědí agenta
Můžete vytvořit zpětné volání pro zachycení odpovědí agenta při průběhu konverzace prostřednictvím ResponseCallback vlastnosti.
ChatHistory history = [];
ValueTask responseCallback(ChatMessageContent response)
{
history.Add(response);
return ValueTask.CompletedTask;
}
Člověk zapojený do procesu
Klíčovou funkcí orchestrace předání je schopnost člověka účastnit se konverzace. Toho dosáhnete poskytnutím InteractiveCallback, který se zavolá pokaždé, když agent potřebuje vstup od uživatele. V reálné aplikaci by se uživateli zobrazila výzva k zadání vstupu; v ukázce můžete použít frontu odpovědí.
// Simulate user input with a queue
Queue<string> responses = new();
responses.Enqueue("I'd like to track the status of my order");
responses.Enqueue("My order ID is 123");
responses.Enqueue("I want to return another order of mine");
responses.Enqueue("Order ID 321");
responses.Enqueue("Broken item");
responses.Enqueue("No, bye");
ValueTask<ChatMessageContent> interactiveCallback()
{
string input = responses.Dequeue();
Console.WriteLine($"\n# INPUT: {input}\n");
return ValueTask.FromResult(new ChatMessageContent(AuthorRole.User, input));
}
Nastavení orchestrace předávání úloh
Vytvořte HandoffOrchestration objekt, předejte agenty, vztahy předání a zpětná volání.
HandoffOrchestration orchestration = new HandoffOrchestration(
handoffs,
triageAgent,
statusAgent,
returnAgent,
refundAgent)
{
InteractiveCallback = interactiveCallback,
ResponseCallback = responseCallback,
};
Spuštění modulu runtime
Modul runtime se vyžaduje ke správě provádění agentů. Tady použijeme InProcessRuntime a zahájíme to před vyvoláním orchestrace.
InProcessRuntime runtime = new InProcessRuntime();
await runtime.StartAsync();
Vyvolání orchestrace
Vyvolávejte orchestraci svým počátečním úkolem (např. "Jsem zákazník, který potřebuje pomoc s objednávkami"). Agenti budou podle potřeby směrovat konverzaci a zapojí člověka, když to bude vyžadováno.
string task = "I am a customer that needs help with my orders";
var result = await orchestration.InvokeAsync(task, runtime);
Shromáždit výsledky
Počkejte na dokončení orchestrace a načtení konečného výstupu.
string output = await result.GetValueAsync(TimeSpan.FromSeconds(300));
Console.WriteLine($"\n# RESULT: {output}");
Console.WriteLine("\n\nORCHESTRATION HISTORY");
foreach (ChatMessageContent message in history)
{
// Print each message
Console.WriteLine($"# {message.Role} - {message.AuthorName}: {message.Content}");
}
Volitelné: Zastavení modulu runtime
Po dokončení zpracování zastavte modul runtime pro vyčištění prostředků.
await runtime.RunUntilIdleAsync();
Ukázkový výstup
# RESULT: Handled order return for order ID 321 due to a broken item, and successfully processed the return.
ORCHESTRATION HISTORY
# Assistant - TriageAgent: Could you please specify what kind of help you need with your orders? Are you looking to check the order status, return an item, or request a refund?
# Assistant - OrderStatusAgent: Could you please tell me your order ID?
# Assistant - OrderStatusAgent: Your order with ID 123 has been shipped and will arrive in 2-3 days. Anything else I can assist you with?
# Assistant - OrderReturnAgent: I can help you with that. Could you please provide the order ID and the reason you'd like to return it?
# Assistant - OrderReturnAgent: Please provide the reason for returning the order with ID 321.
# Assistant - OrderReturnAgent: The return for your order with ID 321 has been successfully processed due to the broken item. Anything else I can assist you with?
Návod
Úplný vzorový kód je k dispozici tady.
Definování specializovaných agentů
Každý agent zodpovídá za konkrétní oblast. Například:
- TriageAgent: Zpracovává počáteční žádosti zákazníků a rozhoduje, kterého odborníka se má zapojit.
- RefundAgent: Zpracovává žádosti o refundaci.
- OrderStatusAgent: Kontroluje stav objednávky.
- OrderReturnAgent: Zpracovává vracení objednávek.
Zásuvné moduly
Nejprve musíme definovat moduly plug-in, které se použijí v agentech. Tyto moduly plug-in budou obsahovat logiku pro zpracování konkrétních úloh.
from semantic_kernel.functions import kernel_function
class OrderStatusPlugin:
@kernel_function
def check_order_status(self, order_id: str) -> str:
"""Check the status of an order."""
# Simulate checking the order status
return f"Order {order_id} is shipped and will arrive in 2-3 days."
class OrderRefundPlugin:
@kernel_function
def process_refund(self, order_id: str, reason: str) -> str:
"""Process a refund for an order."""
# Simulate processing a refund
print(f"Processing refund for order {order_id} due to: {reason}")
return f"Refund for order {order_id} has been processed successfully."
class OrderReturnPlugin:
@kernel_function
def process_return(self, order_id: str, reason: str) -> str:
"""Process a return for an order."""
# Simulate processing a return
print(f"Processing return for order {order_id} due to: {reason}")
return f"Return for order {order_id} has been processed successfully."
Agenti
Dále definujeme agenty, kteří budou tyto moduly plug-in používat.
Návod
Používá se ChatCompletionAgent zde s Azure OpenAI, ale můžete použít libovolný typ agenta nebo službu modelu.
from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
support_agent = ChatCompletionAgent(
name="TriageAgent",
description="A customer support agent that triages issues.",
instructions="Handle customer requests.",
service=OpenAIChatCompletion(),
)
refund_agent = ChatCompletionAgent(
name="RefundAgent",
description="A customer support agent that handles refunds.",
instructions="Handle refund requests.",
service=OpenAIChatCompletion(),
plugins=[OrderRefundPlugin()],
)
order_status_agent = ChatCompletionAgent(
name="OrderStatusAgent",
description="A customer support agent that checks order status.",
instructions="Handle order status requests.",
service=OpenAIChatCompletion(),
plugins=[OrderStatusPlugin()],
)
order_return_agent = ChatCompletionAgent(
name="OrderReturnAgent",
description="A customer support agent that handles order returns.",
instructions="Handle order return requests.",
service=OpenAIChatCompletion(),
plugins=[OrderReturnPlugin()],
)
Definování relací předání
Použijte OrchestrationHandoffs, abyste určili, kterému agentovi lze předat úkol a za jakých okolností.
from semantic_kernel.agents import OrchestrationHandoffs
handoffs = (
OrchestrationHandoffs()
.add_many( # Use add_many to add multiple handoffs to the same source agent at once
source_agent=support_agent.name,
target_agents={
refund_agent.name: "Transfer to this agent if the issue is refund related",
order_status_agent.name: "Transfer to this agent if the issue is order status related",
order_return_agent.name: "Transfer to this agent if the issue is order return related",
},
)
.add( # Use add to add a single handoff
source_agent=refund_agent.name,
target_agent=support_agent.name,
description="Transfer to this agent if the issue is not refund related",
)
.add(
source_agent=order_status_agent.name,
target_agent=support_agent.name,
description="Transfer to this agent if the issue is not order status related",
)
.add(
source_agent=order_return_agent.name,
target_agent=support_agent.name,
description="Transfer to this agent if the issue is not order return related",
)
)
Sledování odpovědí agenta
Při průběhu konverzace můžete definovat zpětné volání, které vytiskne zprávu jednotlivých agentů.
from semantic_kernel.contents import ChatMessageContent
def agent_response_callback(message: ChatMessageContent) -> None:
print(f"{message.name}: {message.content}")
Člověk zapojený do procesu
Klíčovou funkcí orchestrace předání je schopnost člověka účastnit se konverzace. Toho dosáhnete poskytnutím zpětného human_response_function volání, které se volá vždy, když agent potřebuje vstup od uživatele.
from semantic_kernel.contents import AuthorRole, ChatMessageContent
def human_response_function() -> ChatMessageContent:
user_input = input("User: ")
return ChatMessageContent(role=AuthorRole.USER, content=user_input)
Nastavení orchestrace předávání úloh
Vytvořte HandoffOrchestration objekt, předejte agenty, vztahy předání a zpětná volání.
from semantic_kernel.agents import HandoffOrchestration
handoff_orchestration = HandoffOrchestration(
members=[
support_agent,
refund_agent,
order_status_agent,
order_return_agent,
],
handoffs=handoffs,
agent_response_callback=agent_response_callback,
human_response_function=human_response_function,
)
Spuštění modulu runtime
Spusťte modul runtime pro správu provádění agenta.
from semantic_kernel.agents.runtime import InProcessRuntime
runtime = InProcessRuntime()
runtime.start()
Vyvolání orchestrace
Vyvolejte orchestraci pomocí vašeho počátečního úkolu (např. "Zákazník je na telefonu."). Agenti budou podle potřeby směrovat konverzaci a zapojí člověka, když to bude vyžadováno.
orchestration_result = await handoff_orchestration.invoke(
task="A customer is on the line.",
runtime=runtime,
)
Shromáždit výsledky
Počkejte na dokončení orchestrace.
value = await orchestration_result.get()
print(value)
Volitelné: Zastavení modulu runtime
Po dokončení zpracování zastavte modul runtime pro vyčištění prostředků.
await runtime.stop_when_idle()
Ukázkový výstup
TriageAgent: Hello! Thank you for reaching out. How can I assist you today?
User: I'd like to track the status of my order
OrderStatusAgent: Sure, I can help you with that. Could you please provide me with your order ID?
User: My order ID is 123
OrderStatusAgent: Your order with ID 123 has been shipped and is expected to arrive in 2-3 days. Is there anything else I can assist you with?
User: I want to return another order of mine
OrderReturnAgent: I can help you with returning your order. Could you please provide the order ID for the return and the reason you'd like to return it?
User: Order ID 321
OrderReturnAgent: Please provide the reason for returning the order with ID 321.
User: Broken item
OrderReturnAgent: The return for your order with ID 321 has been successfully processed due to the broken item. Is there anything else I can assist you with?
User: No, bye
Task is completed with summary: Handled order return for order ID 321 due to a broken item, and successfully processed the return.
Návod
Úplný vzorový kód je k dispozici tady.
Poznámka:
Orchestrace agentů zatím není v Java vývojovém prostředí SDK k dispozici.