使用这个企业级编排框架,构建智能 AI 代理与多代理系统
Semantic Kernel 是一个模型无关的 SDK,它使开发者能够构建、编排和部署 AI 代理与多代理系统。无论你是构建一个简单的聊天机器人,还是一个复杂的多代理工作流,Semantic Kernel 都能提供你所需的企业级可靠性与灵活性工具。
首先,为你的 AI 服务设置环境变量:
Azure OpenAI:
export AZURE_OPENAI_API_KEY=AAA....
或直接使用 OpenAI:
export OPENAI_API_KEY=sk-...
pip install semantic-kernel
dotnet add package Microsoft.SemanticKernel
dotnet add package Microsoft.SemanticKernel.Agents.Core
请参阅 semantic-kernel-java 构建说明。
创建一个响应提示的简单助手:
import asyncio
from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
async def main():
# 使用基本指令初始化聊天代理
agent = ChatCompletionAgent(
service=AzureChatCompletion(),
name="SK-Assistant",
instructions="You are a helpful assistant.",
)
# 获取对用户消息的响应
response = await agent.get_response(messages="Write a haiku about Semantic Kernel.")
print(response.content)
asyncio.run(main())
# 输出:
# Language's essence,
# Semantic threads intertwine,
# Meaning's core revealed.
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Agents;
var builder = Kernel.CreateBuilder();
builder.AddAzureOpenAIChatCompletion(
Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT"),
Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT"),
Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")
);
var kernel = builder.Build();
ChatCompletionAgent agent =
new()
{
Name = "SK-Agent",
Instructions = "You are a helpful assistant.",
Kernel = kernel,
};
await foreach (AgentResponseItem<ChatMessageContent> response
in agent.InvokeAsync("Write a haiku about Semantic Kernel."))
{
Console.WriteLine(response.Message);
}
// 输出:
// Language's essence,
// Semantic threads intertwine,
// Meaning's core revealed.
使用自定义工具(插件)和结构化输出来增强你的代理:
import asyncio
from typing import Annotated
from pydantic import BaseModel
from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion, OpenAIChatPromptExecutionSettings
from semantic_kernel.functions import kernel_function, KernelArguments
class MenuPlugin:
@kernel_function(description="Provides a list of specials from the menu.")
def get_specials(self) -> Annotated[str, "Returns the specials from the menu."]:
return """
Special Soup: Clam Chowder
Special Salad: Cobb Salad
Special Drink: Chai Tea
"""
@kernel_function(description="Provides the price of the requested menu item.")
def get_item_price(
self, menu_item: Annotated[str, "The name of the menu item."]
) -> Annotated[str, "Returns the price of the menu item."]:
return "$9.99"
class MenuItem(BaseModel):
price: float
name: str
async def main():
# 配置结构化输出格式
settings = OpenAIChatPromptExecutionSettings()
settings.response_format = MenuItem
# 创建带有插件和设置的代理
agent = ChatCompletionAgent(
service=AzureChatCompletion(),
name="SK-Assistant",
instructions="You are a helpful assistant.",
plugins=[MenuPlugin()],
arguments=KernelArguments(settings)
)
response = await agent.get_response(messages="What is the price of the soup special?")
print(response.content)
# 输出:
# The price of the Clam Chowder, which is the soup special, is $9.99.
asyncio.run(main())
using System.ComponentModel;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Agents;
using Microsoft.SemanticKernel.ChatCompletion;
var builder = Kernel.CreateBuilder();
builder.AddAzureOpenAIChatCompletion(
Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT"),
Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT"),
Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")
);
var kernel = builder.Build();
kernel.Plugins.Add(KernelPluginFactory.CreateFromType<MenuPlugin>());
ChatCompletionAgent agent =
new()
{
Name = "SK-Assistant",
Instructions = "You are a helpful assistant.",
Kernel = kernel,
Arguments = new KernelArguments(new PromptExecutionSettings() { FunctionChoiceBehavior = FunctionChoiceBehavior.Auto() })
};
await foreach (AgentResponseItem<ChatMessageContent> response
in agent.InvokeAsync("What is the price of the soup special?"))
{
Console.WriteLine(response.Message);
}
sealed class MenuPlugin
{
[KernelFunction, Description("Provides a list of specials from the menu.")]
public string GetSpecials() =>
"""
Special Soup: Clam Chowder
Special Salad: Cobb Salad
Special Drink: Chai Tea
""";
[KernelFunction, Description("Provides the price of the requested menu item.")]
public string GetItemPrice(
[Description("The name of the menu item.")]
string menuItem) =>
"$9.99";
}
构建一个可以协作的专家代理系统:
import asyncio
from semantic_kernel.agents import ChatCompletionAgent, ChatHistoryAgentThread
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion, OpenAIChatCompletion
billing_agent = ChatCompletionAgent(
service=AzureChatCompletion(),
name="BillingAgent",
instructions="You handle billing issues like charges, payment methods, cycles, fees, discrepancies, and payment failures."
)
refund_agent = ChatCompletionAgent(
service=AzureChatCompletion(),
name="RefundAgent",
instructions="Assist users with refund inquiries, including eligibility, policies, processing, and status updates.",
)
triage_agent = ChatCompletionAgent(
service=OpenAIChatCompletion(),
name="TriageAgent",
instructions="Evaluate user requests and forward them to BillingAgent or RefundAgent for targeted assistance."
" Provide the full answer to the user containing any information from the agents",
plugins=[billing_agent, refund_agent],
)
thread: ChatHistoryAgentThread = None
async def main() -> None:
print("Welcome to the chat bot!\n Type 'exit' to exit.\n Try to get some billing or refund help.")
while True:
user_input = input("User:> ")
if user_input.lower().strip() == "exit":
print("\n\nExiting chat...")
return False
response = await triage_agent.get_response(
messages=user_input,
thread=thread,
)
if response:
print(f"Agent :> {response}")
# Agent :> I understand that you were charged twice for your subscription last month, and I'm here to assist you with resolving this issue. Here’s what we need to do next:
# 1. **Billing Inquiry**:
# - Please provide the email address or account number associated with your subscription, the date(s) of the charges, and the amount charged. This will allow the billing team to investigate the discrepancy in the charges.
# 2. **Refund Process**:
# - For the refund, please confirm your subscription type and the email address associated with your account.
# - Provide the dates and transaction IDs for the charges you believe were duplicated.
# Once we have these details, we will be able to:
# - Check your billing history for any discrepancies.
# - Confirm any duplicate charges.
# - Initiate a refund for the duplicate payment if it qualifies. The refund process usually takes 5-10 business days after approval.
# Please provide the necessary details so we can proceed with resolving this issue for you.
if __name__ == "__main__":
asyncio.run(main())
我们欢迎您为 SK 社区做出贡献和提出建议!参与 GitHub 仓库的讨论是最简单的参与方式之一。欢迎提交错误报告和修复!
对于新功能、组件或扩展,请在发送 PR 之前先开一个 issue 与我们讨论。这是为了避免被拒绝,因为我们可能正在将核心向不同方向发展,同时也需要考虑对更大生态系统的影响。
要了解更多信息并开始使用:
本项目采用了
Microsoft 开源行为准则。
欲了解更多信息,请参阅
行为准则 FAQ
或联系 opencode@microsoft.com
提出任何其他问题或意见。
版权所有 (c) Microsoft Corporation。保留所有权利。
根据 MIT 许可证授权。