Files
microsoft--semantic-kernel/README.md
T
wehub-resource-sync ef1c7a25d3
CodeQL / Analyze (csharp) (push) Waiting to run
CodeQL / Analyze (python) (push) Waiting to run
docs: make Chinese README the default
2026-07-13 11:04:05 +00:00

14 KiB
Raw Blame History

Note

本文档由 WeHub 基于上游 README 翻译整理,属于社区翻译,非官方中文文档。
English · 原始项目 · 上游 README
原作者、版权与许可证归属以原始项目及本仓库 LICENSE 文件为准。

Semantic Kernel

Important

Semantic Kernel 现已发展为 Microsoft Agent Framework! Microsoft Agent FrameworkMAF)是 Semantic Kernel 的企业级继任产品。Microsoft Agent Framework 现已推出 1.0 正式版:API 稳定,并承诺长期支持。无论你是构建单一助手,还是编排一支由专业化智能体组成的团队,Microsoft Agent Framework 1.0 均可提供企业级多智能体编排、多提供商模型支持,以及通过 A2A 与 MCP 实现的跨运行时互操作性。

在此了解更多关于 Semantic Kernel 与 Agent Framework 的信息:Agent Framework 博客上的 Semantic Kernel 与 Microsoft Agent Framework, and try out the Semantic Kernel 迁移指南.

使用这一企业级编排框架构建智能 AI 智能体与多智能体系统

License: MIT Python package Nuget package Discord

什么是 Semantic Kernel

Semantic Kernel 是一款模型无关的 SDK,帮助开发者构建、编排并部署 AI 智能体与多智能体系统。无论你是构建简单的聊天机器人,还是复杂的多智能体工作流,Semantic Kernel 都能提供所需工具,并具备企业级的可靠性与灵活性。

系统要求

  • Python3.10+
  • .NET.NET 10.0+
  • JavaJDK 17+
  • 操作系统支持Windows、macOS、Linux

核心特性

  • 模型灵活性:可连接任意 LLM,内置支持 OpenAI, Azure OpenAI, Hugging Face, NVidia
  • 智能体框架(Agent Framework:构建模块化 AI 智能体,可使用工具/插件、记忆与规划能力
  • 多智能体系统:通过协作的专业化智能体编排复杂工作流
  • 插件生态:通过原生代码函数、提示模板、OpenAPI 规范或 Model Context ProtocolMCP)进行扩展
  • 向量数据库支持:与 Azure AI Search, Elasticsearch, Chroma, 等无缝集成
  • 多模态支持:处理文本、视觉与音频输入
  • 本地部署:可使用 Ollama, LMStudio, 或 ONNX 运行
  • 流程框架(Process Framework:以结构化工作流方式建模复杂业务流程
  • 企业级就绪:面向可观测性、安全性与稳定 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 build

快速入门

基础智能体 - Python

创建一个响应用户提示的简单助手:

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()) 

# Output:
# Language's essence,
# Semantic threads intertwine,
# Meaning's core revealed.

基础智能体 - .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<ChatMessageContent> 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<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";
}

Multi-Agent System - Python

构建一个能够协作的专用智能体(agent)系统:

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. Heres 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())

下一步

  1. 📖 试用我们的 入门指南 or 了解 构建智能体
  2. 🔌 探索 100 多个 详细示例
  3. 💡 了解 Semantic Kernel 核心 概念

API 参考

故障排除

常见问题

  • 身份验证错误:请检查 API 密钥环境变量是否已正确设置
  • 模型可用性:请确认你的 Azure OpenAI 部署或 OpenAI 模型访问权限

获取帮助

  • 查看我们的 GitHub issues 以了解已知问题
  • Discord 社区 中搜索解决方案
  • 寻求帮助时,请附上 SDK 版本和完整错误信息

加入社区

我们欢迎你对 SK 社区的贡献与建议!参与方式之一是在 GitHub 仓库中参与讨论。欢迎提交 bug 报告和修复!

若要添加新功能、组件或扩展,请先提交 issue 并与我们讨论,再发送 PR。这可以避免 PR 被拒绝——我们可能对核心采取不同方向——同时也便于评估对更大生态系统的影响。

了解更多并开始参与:

贡献者名人堂

semantic-kernel 贡献者

行为准则

本项目已采纳 Microsoft 开源行为准则. 更多信息请参阅 行为准则常见问题 或通过 opencode@microsoft.com 联系我们 提出任何其他问题或意见。

许可证

Copyright (c) Microsoft Corporation. All rights reserved.

根据 MIT 许可证授权。