大模型 活跃维护

semantic-kernel

microsoft/semantic-kernel

将尖端的大型语言模型技术快速且轻松地整合到您的应用中

28709
Stars 标星
4841
Forks 分支
296
Watchers 关注
338
Open Issues
C#
主要语言
MIT
开源协议
105.1 MB
仓库大小
2 天前
最后推送
一键安装扩展 / 插件指令
dsh plugin --profile web add github:microsoft/semantic-kernel
git clone https://github.com/microsoft/semantic-kernel.git
git clone git@github.com:microsoft/semantic-kernel.git
README.md main

英文原文正文为项目原始 README(英文),本站后续会翻译为中文,当前仅剔除图片与无关章节并统一排版。

语义内核

[!重要]
语义内核现已成为 Microsoft 代理框架!Microsoft 代理框架(MAF)是语义内核的企业级继任者。Microsoft 代理框架现已发布版本 1.0,为生产就绪版本:稳定的 API,并承诺提供长期支持。无论你是在构建单个助手还是协调一群专业代理,Microsoft 代理框架 1.0 都为你提供企业级多代理编排、多供应商模型支持,以及通过 A2A 和 MCP 的跨运行时互操作性。

在此处了解有关语义内核和代理框架的更多信息:语义内核和 Microsoft 代理框架 - 代理框架博客,并试用 语义内核迁移指南。

使用这个面向企业的编排框架构建智能 AI 代理和多代理系统

什么是语义内核?

Semantic Kernel 是一个与模型无关的 SDK,使开发者能够构建、编排和部署 AI 代理及多代理系统。无论您是在构建一个简单的聊天机器人还是复杂的多代理工作流,Semantic Kernel 都提供了您所需的工具,同时具备企业级的可靠性和灵活性。

系统要求

  • Python:3.10
  • .NET:.NET 10.0
  • Java:JDK 17
  • 操作系统支持:Windows、macOS、Linux

主要功能

  • 模型灵活性:可连接到任何内置支持 OpenAI、Azure OpenAI、Hugging Face、NVidia 等的 LLM
  • 智能体框架:构建可访问工具/插件、内存和规划能力的模块化 AI 智能体
  • 多智能体系统:通过协作的专业智能体编排复杂工作流
  • 插件生态系统:通过原生代码功能、提示模板、OpenAPI 规范或模型上下文协议(MCP)进行扩展
  • 向量数据库支持:与 Azure AI 搜索、Elasticsearch、Chroma 等无缝集成
  • 多模态支持:处理文本、视觉和音频输入
  • 本地部署:可使用 Ollama、LMStudio 或 ONNX 运行
  • 流程框架:通过结构化工作流方法建模复杂业务流程
  • 企业级准备:为可观测性、安全性和稳定 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 构建。

快速入门

基础代理 - 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";
}

多智能体系统 - 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 :> 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())

下一步去哪儿

  1. 📖 试试我们的 入门指南 或了解 构建代理
  2. 🔌 探索 100 多个 详细示例
  3. 💡 了解核心语义内核 概念

API 参考

故障排除

常见问题

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

获取帮助

  • 查看我们的 GitHub 问题 获取已知问题
  • 在 Discord 社区 搜索解决方案
  • 在寻求帮助时,请包含您的 SDK 版本和完整错误信息

加入社区

我们欢迎您为 SK 社区提供贡献和建议!参与的最简单方式之一是参与 GitHub 仓库中的讨论。欢迎提交 Bug 报告和修复!

对于新功能、组件或扩展,请在发送 PR 之前先打开 issue 并与我们讨论。这是为了避免被拒绝,因为我们可能会将核心方向调整到不同的方向,同时也为了考虑对更大生态系统的影响。

要了解更多信息并开始使用:

行为准则

本项目已采用 Microsoft 开源行为准则。欲了解更多信息,请参阅 行为准则常见问题 或通过 opencode@microsoft.com 联系我们以获取任何额外的问题或意见。

许可证

版权所有 (c) Microsoft Corporation。保留所有权利。

根据 MIT 许可证授权。

本站来源与版权声明
  • 本文标题:semantic-kernel - 将尖端的大型语言模型技术快速且轻松地整合到您的应用中
  • 本文链接:https://www.cn121.com/llm/microsoft-semantic-kernel.html
  • 原项目:microsoft/semantic-kernel 版权归原作者 microsoft 及贡献者所有
  • 收录信息:本站于 2026-10-28 收录本项目,本页所列协议与仓库指标均为收录当时的状态;该日期之后原项目的版本更新与协议变更,本页不作同步。
  • 开源协议:收录时本项目采用 MIT(查看 LICENSE 原文),本站转载其原始文档(未改动文字,仅剔除图片与无关章节);使用、修改、分发请以该仓库 LICENSE 原文为准。
  • 站点出处:本文首发于 OneTwoOne,收录自 GitHub 开源项目 microsoft/semantic-kernel。
  • 内容说明:本页正文为原项目 README 原文(英文),本站后续会翻译为中文(当前尚未译出,仅将二级标题译为中文,便于按栏目定位;标题原文可在下方原仓库中查看),仅剔除了图片与赞助等无关章节、并把相对链接改为绝对地址;页首简介为机器翻译自仓库描述。
  • 引用声明:商业转载、第三方聚合或 AI 检索训练引用时,请务必保留以上来源出处、本文永久链接,以及原项目的版权声明与许可信息。
  • 下架通道:若原项目此后变更或收紧了许可协议、或作者/权利人认为本站的收录方式(译文、排版适配、简介翻译等)超出其授权范围,请通过 xyd3302001@163.com 发送下架通知,并附上项目地址与本页链接。本站核实后将第一时间删除本页内容,或改为不复制原文的目录性收录;署名更正等其他要求可一并提出。