microsoft/semantic-kernel
GitHub: microsoft/semantic-kernel
微软开源的企业级 AI 编排框架,帮助开发者快速将大语言模型集成到应用中,支持构建单代理和多代理协作系统。
Stars: 27878 | Forks: 4593
# Semantic Kernel
**使用这款企业级编排框架构建智能 AI 代理和多代理系统**
[](https://github.com/microsoft/semantic-kernel/blob/main/LICENSE)
[](https://pypi.org/project/semantic-kernel/)
[](https://www.nuget.org/packages/Microsoft.SemanticKernel/)
[](https://aka.ms/SKDiscord)
## 什么是 Semantic Kernel?
Semantic Kernel 是一个模型无关的 SDK,使开发者能够构建、编排和部署 AI 代理及多代理系统。无论您是在构建一个简单的聊天机器人,还是复杂的多代理工作流,Semantic Kernel 都能为您提供所需的工具,并具备企业级的可靠性和灵活性。
## 系统要求
- **Python**: 3.10+
- **.NET**: .NET 10.0+
- **Java**: JDK 17+
- **操作系统支持**: Windows, macOS, Linux
## 核心功能
- **模型灵活性**:内置对 [OpenAI](https://platform.openai.com/docs/introduction)、[Azure OpenAI](https://azure.microsoft.com/en-us/products/ai-services/openai-service)、[Hugging Face](https://huggingface.co/)、[NVidia](https://www.nvidia.com/en-us/ai-data-science/products/nim-microservices/) 等的支持,可连接到任何 LLM
- **代理框架**:构建模块化的 AI 代理,使其具备访问工具/插件、内存和规划功能的能力
- **多代理系统**:通过协作的专业代理来编排复杂的工作流
- **插件生态系统**:通过原生代码函数、prompt 模板、OpenAPI 规范或 Model Context Protocol (MCP) 进行扩展
- **向量数据库支持**:与 [Azure AI Search](https://learn.microsoft.com/en-us/azure/search/search-what-is-azure-search)、[Elasticsearch](https://www.elastic.co/)、[Chroma](https://docs.trychroma.com/docs/overview/getting-started) 等无缝集成
- **多模态支持**:处理文本、视觉和音频输入
- **本地部署**:使用 [Ollama](https://ollama.com/)、[LMStudio](https://lmstudio.ai/) 或 [ONNX](https://onnx.ai/) 运行
- **流程框架**:使用结构化的工作流方法对复杂的业务流程进行建模
- **企业级就绪**:为可观察性、安全性和稳定的 API 而构建
## 安装
首先,为您的 AI 服务设置环境变量:
**Azure OpenAI:**
```
export AZURE_OPENAI_API_KEY=AAA....
```
**或者直接使用 OpenAI:**
```
export OPENAI_API_KEY=sk-...
```
### Python
```
pip install semantic-kernel
```
### .NET
```
dotnet add package Microsoft.SemanticKernel
dotnet add package Microsoft.SemanticKernel.Agents.Core
```
### Java
有关说明,请参见 [semantic-kernel-java 构建](https://github.com/microsoft/semantic-kernel-java/blob/main/BUILD.md)。
## 快速入门
### 基础代理 - Python
创建一个响应用户 prompt 的简单助手:
```
import asyncio
from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
async def main():
# Initialize a chat agent with basic instructions
agent = ChatCompletionAgent(
service=AzureChatCompletion(),
name="SK-Assistant",
instructions="You are a helpful assistant.",
)
# Get a response to a user message
response = await agent.get_response(messages="Write a haiku about Semantic Kernel.")
print(response.content)
asyncio.run(main())
# 输出:
# 语言之精髓,
# 语义丝线交织,
# 意义之核心彰显。
```
### 基础代理 - .NET
```
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 response
in agent.InvokeAsync("Write a haiku about Semantic Kernel."))
{
Console.WriteLine(response.Message);
}
// Output:
// Language's essence,
// Semantic threads intertwine,
// Meaning's core revealed.
```
### 带有插件的代理 - Python
使用自定义工具(插件)和结构化输出增强您的代理:
```
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():
# Configure structured output format
settings = OpenAIChatPromptExecutionSettings()
settings.response_format = MenuItem
# Create agent with plugin and settings
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)
# Output:
# The price of the Clam Chowder, which is the soup special, is $9.99.
asyncio.run(main())
```
### 带有插件的代理 - .NET
```
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());
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 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";
}
```
### 多代理系统 - Python
构建一个可以协作的专业代理系统:
```
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 :> 我了解到您上个月的订阅被扣款了两次,我在这里协助您解决此问题。接下来我们需要执行以下操作:
# 1. **账单查询**:
# - 请提供与您的订阅关联的邮箱地址或账号、扣款日期以及扣款金额。这将便于账单团队调查扣款差异。
# 2. **退款流程**:
# - 关于退款,请确认您的订阅类型以及与您账号关联的邮箱地址。
# - 请提供您认为被重复扣款的日期和交易 ID。
# 一旦我们收到这些详细信息,我们将能够:
# - 检查您的账单历史记录以排查任何差异。
# - 确认任何重复的扣款。
# - 如果符合条件,将为重复的付款发起退款。退款流程在获得批准后通常需要 5-10 个工作日。
# 请提供必要的详细信息,以便我们着手为您解决此问题。
if __name__ == "__main__":
asyncio.run(main())
```
## 接下来去哪里
1. 📖 尝试我们的[入门指南](https://learn.microsoft.com/en-us/semantic-kernel/get-started/quick-start-guide)或了解有关[构建代理](https://learn.microsoft.com/en-us/semantic-kernel/frameworks/agent/)的内容
2. 🔌 探索超过 100 个[详细示例](https://learn.microsoft.com/en-us/semantic-kernel/get-started/detailed-samples)
3. 💡 学习 Semantic Kernel 核心[概念](https://learn.microsoft.com/en-us/semantic-kernel/concepts/kernel)
### API 参考
- [C# API 参考](https://learn.microsoft.com/en-us/dotnet/api/microsoft.semantickernel?view=semantic-kernel-dotnet)
- [Python API 参考](https://learn.microsoft.com/en-us/python/api/semantic-kernel/semantic_kernel?view=semantic-kernel-python)
## 故障排除
### 常见问题
- **身份验证错误**:检查您的 API 密钥环境变量是否已正确设置
- **模型可用性**:验证您的 Azure OpenAI 部署或 OpenAI 模型访问权限
### 获取帮助
- 查看我们的 [GitHub issues](https://github.com/microsoft/semantic-kernel/issues) 以了解已知问题
- 在 [Discord 社区](https://aka.ms/SKDiscord)中搜索解决方案
- 在寻求帮助时,请附上您的 SDK 版本和完整的错误信息
## 行为准则
本项目采用了
[Microsoft 开源行为准则](https://opensource.microsoft.com/codeofconduct/)。
有关更多信息,请参见
[行为准则 FAQ](https://opensource.microsoft.com/codeofconduct/faq/)
或联系 [opencode@microsoft.com](mailto:opencode@microsoft.com)
以提出任何其他问题或建议。
## 许可证
版权所有 (c) Microsoft Corporation。保留所有权利。
根据 [MIT](LICENSE) 许可证授权。
标签:AI代理, AI开发框架, AI风险缓解, Azure OpenAI, CNCF毕业项目, Copilot, CreateRemoteThread, DLL 劫持, Hugging Face, IaC 扫描, JS文件枚举, LLM, MCP, OpenAI, PyRIT, Python, RAG, Semantic Kernel, Unmanaged PE, 人工智能, 企业级应用, 内存规避, 向量数据库, 多智能体系统, 大语言模型, 大语言模型蜜罐, 微软, 无后门, 智能工作流, 检索增强生成, 模型上下文协议, 用户模式Hook绕过, 编排框架, 网络调试, 自动化, 逆向工具