Semantic Kernel 教程

微软的企业级AI编排框架

⭐ 15K+ Stars 🏢 Microsoft 🔌 插件系统 3️⃣ 三语言支持

💎 Semantic Kernel核心特性

🔌

Plugin(插件)

封装特定功能的可重用组件,类似函数但更强大

  • • Semantic Functions(语义函数)
  • • Native Functions(原生函数)
  • • 参数化和组合
🎯

Planner(规划器)

AI自动规划任务执行步骤,智能调用插件

  • • Sequential Planner(顺序)
  • • Action Planner(单步)
  • • Stepwise Planner(逐步)
🧠

Memory(记忆)

存储和检索上下文信息,实现长期记忆

  • • 向量存储
  • • 语义搜索
  • • 上下文管理

🆚 Semantic Kernel vs LangChain

特性 Semantic Kernel LangChain
语言支持 C#、Python、Java Python、JavaScript
核心定位 企业级AI编排 通用LLM框架
设计理念 插件化、规划器 链式调用
企业集成 Azure深度集成 开放生态
适用场景 .NET生态、企业应用 通用、快速开发

💡 选择SK如果你用.NET技术栈或需要Azure深度集成;选择LangChain如果追求生态和社区

🚀 快速开始

📦 安装

Python

pip install semantic-kernel

C#

dotnet add package Microsoft.SemanticKernel

Python示例

import semantic_kernel as sk
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion

# 创建kernel
kernel = sk.Kernel()

# 添加AI服务
kernel.add_service(
    OpenAIChatCompletion(
        service_id="gpt-4",
        api_key="your-key"
    )
)

# 创建语义函数
prompt = "将以下文本翻译成{{\$language}}:{{\$text}}"
translate = kernel.create_semantic_function(prompt)

# 调用
result = await translate.invoke_async(
    text="Hello World",
    language="中文"
)
print(result)

C#示例

using Microsoft.SemanticKernel;

// 创建kernel
var kernel = Kernel.CreateBuilder()
    .AddOpenAIChatCompletion(
        modelId: "gpt-4",
        apiKey: "your-key")
    .Build();

// 创建函数
var translate = kernel.CreateFunctionFromPrompt(
    "将以下文本翻译成{{\$language}}:{{\$text}}"
);

// 调用
var result = await kernel.InvokeAsync(
    translate,
    new() {
        ["text"] = "Hello World",
        ["language"] = "中文"
    }
);

Console.WriteLine(result);

🔌 插件系统深度解析

1. Semantic Functions(语义函数)

使用自然语言定义的函数,由LLM执行

Python版本

# 定义语义函数
summarize_prompt = """
将以下文本总结为3-5个要点:

文本:{{\$input}}

要点:
"""

summarize = kernel.create_semantic_function(
    summarize_prompt,
    function_name="summarize",
    plugin_name="TextPlugin"
)

# 使用
result = await summarize.invoke_async(
    input="很长的文档内容..."
)

C#版本

// 定义语义函数
var summarize = kernel.CreateFunctionFromPrompt(@"
将以下文本总结为3-5个要点:

文本:{{\$input}}

要点:
");

// 使用
var result = await kernel.InvokeAsync(
    summarize,
    new() { ["input"] = "很长的文档内容..." }
);

Console.WriteLine(result);

2. Native Functions(原生函数)

用代码实现的函数,可以调用API、数据库等

Python原生函数

from semantic_kernel.skill_definition import sk_function

class MathPlugin:
    @sk_function(
        description="计算两个数的和",
        name="add"
    )
    def add(self, a: int, b: int) -> int:
        return a + b
    
    @sk_function(
        description="获取当前时间",
        name="get_time"
    )
    def get_time(self) -> str:
        from datetime import datetime
        return datetime.now().strftime("%Y-%m-%d %H:%M:%S")

# 注册插件
kernel.import_plugin(MathPlugin(), "MathPlugin")

# 调用
result = await kernel.invoke(
    "MathPlugin",
    "add",
    a=5,
    b=3
)

C#原生函数

using Microsoft.SemanticKernel;

public class MathPlugin
{
    [SKFunction("计算两个数的和")]
    public int Add(int a, int b)
    {
        return a + b;
    }
    
    [SKFunction("获取当前时间")]
    public string GetTime()
    {
        return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
    }
}

// 注册插件
kernel.ImportPluginFromObject(new MathPlugin());

// 调用
var result = await kernel.InvokeAsync(
    "MathPlugin",
    "Add",
    new() { ["a"] = 5, ["b"] = 3 }
);

3. 插件组合

将多个函数串联,实现复杂功能

# 定义多个函数
get_news = kernel.create_semantic_function("搜索{{\$topic}}的最新新闻")
summarize = kernel.create_semantic_function("总结以下新闻:{{\$input}}")
translate = kernel.create_semantic_function("将{{\$input}}翻译成{{\$language}}")

# 组合调用
news = await get_news.invoke_async(topic="AI")
summary = await summarize.invoke_async(input=news)
translated = await translate.invoke_async(input=summary, language="英文")

print(translated)

🎯 Planner规划器

AI自动规划任务步骤,智能选择和调用插件,是SK的核心优势

Sequential Planner示例

from semantic_kernel.planning import SequentialPlanner

# 创建规划器
planner = SequentialPlanner(kernel)

# 定义目标
goal = """
1. 搜索"DeepSeek-V3"的最新信息
2. 总结成200字
3. 翻译成英文
"""

# 自动规划并执行
plan = await planner.create_plan_async(goal)

# 查看计划
for step in plan._steps:
    print(f"步骤: {step.description}")

# 执行计划
result = await plan.invoke_async()
print(result)

AI自动生成的执行计划:

  1. 1. 调用SearchPlugin.search(搜索DeepSeek-V3)
  2. 2. 调用TextPlugin.summarize(总结为200字)
  3. 3. 调用TranslatePlugin.translate(翻译成英文)

Sequential Planner

顺序规划器,生成线性执行计划

  • • 适合明确步骤的任务
  • • 自动选择插件
  • • 步骤可预览

Action Planner

单步规划器,选择最佳插件

  • • 简单任务
  • • 快速响应
  • • 成本更低

Stepwise Planner

逐步规划,动态调整

  • • 复杂任务
  • • 根据结果调整
  • • 更智能

🧠 Memory记忆系统

实现长期记忆

from semantic_kernel.memory import MemoryBuilder

# 创建记忆系统
memory = MemoryBuilder()
    .with_open_ai_text_embedding_generation(api_key="your-key")
    .with_memory_store(QdrantMemoryStore())
    .build()

# 存储信息
await memory.save_information_async(
    collection="company_docs",
    id="doc1",
    text="Semantic Kernel是微软的AI编排框架"
)

# 语义搜索
results = await memory.search_async(
    collection="company_docs",
    query="什么是SK?",
    limit=3
)

for result in results:
    print(f"相似度:{result.relevance}")
    print(f"内容:{result.text}")

💾 支持的存储后端

  • • Qdrant(推荐)
  • • Pinecone
  • • Azure Cognitive Search
  • • Chroma
  • • Weaviate

🎯 应用场景

  • • 对话上下文记忆
  • • 企业知识库
  • • 个性化推荐
  • • 用户偏好学习

💼 实战案例

案例1:企业智能客服系统

结合插件、规划器、记忆的完整应用

# 1. 创建插件
class CustomerServicePlugin:
    @sk_function(description="查询订单状态")
    def get_order_status(self, order_id: str) -> str:
        # 调用数据库
        return f"订单{order_id}状态:已发货"
    
    @sk_function(description="查询退款政策")
    def get_refund_policy(self) -> str:
        return "7天无理由退货,30天质量问题退款"

# 2. 注册插件
kernel.import_plugin(CustomerServicePlugin(), "CustomerService")

# 3. 添加记忆(知识库)
await memory.save_information_async(
    collection="kb",
    id="faq1",
    text="运费说明:单笔订单满99元免运费"
)

# 4. 创建规划器
planner = SequentialPlanner(kernel)

# 5. 处理用户请求
user_query = "我的订单123456什么时候能到?运费多少?"

plan = await planner.create_plan_async(user_query)
result = await plan.invoke_async()

print(result)

案例2:AI内容生成Pipeline

从选题到发布的自动化流程

# 定义内容生成插件
class ContentPlugin:
    @sk_function(description="生成文章大纲")
    async def create_outline(self, topic: str) -> str:
        prompt = f"为'{topic}'生成文章大纲(5个小标题)"
        return await kernel.invoke_semantic_function(prompt)
    
    @sk_function(description="根据大纲生成文章")
    async def write_article(self, outline: str) -> str:
        prompt = f"根据以下大纲撰写1500字文章:\n{outline}"
        return await kernel.invoke_semantic_function(prompt)
    
    @sk_function(description="SEO优化")
    async def optimize_seo(self, article: str) -> str:
        prompt = f"为文章添加SEO优化的标题和meta描述:\n{article}"
        return await kernel.invoke_semantic_function(prompt)

# 注册插件
kernel.import_plugin(ContentPlugin(), "Content")

# 使用规划器自动执行
goal = "为'Semantic Kernel教程'主题创建一篇SEO优化的文章"
plan = await planner.create_plan_async(goal)
result = await plan.invoke_async()

print(result)

🎓 高级功能

🤖 多模型支持

同时使用多个AI模型

# 添加多个服务
kernel.add_service(
    OpenAIChatCompletion("gpt-4", api_key)
)
kernel.add_service(
    AzureChatCompletion("gpt-35-turbo", endpoint, key)
)

# 指定使用哪个
result = await kernel.invoke(
    function,
    service_id="gpt-4"
)

🎚️ 过滤器(Filters)

拦截和修改函数调用

# 添加日志过滤器
class LoggingFilter:
    async def on_function_invoking(self, context):
        print(f"调用: {context.function.name}")
    
    async def on_function_invoked(self, context):
        print(f"结果: {context.result}")

kernel.add_filter(LoggingFilter())

📞 Function Calling

自动调用函数(工具)

# 启用自动函数调用
settings = OpenAIPromptExecutionSettings(
    function_call_behavior=FunctionCallBehavior.AutoInvokeKernelFunctions
)

result = await kernel.invoke(
    function,
    settings=settings
)

⚡ 流式输出

# 流式生成
async for chunk in kernel.invoke_stream(function):
    print(chunk, end="")

⭐ 最佳实践

✅ 推荐做法

  • 插件单一职责:每个插件专注一个领域
  • 描述清晰:函数description要准确,帮助Planner选择
  • 错误处理:原生函数要有异常处理
  • 测试优先:每个插件要有单元测试

❌ 常见陷阱

  • 过度规划:简单任务不需要Planner
  • 函数太多:插件数量控制在10个以内
  • 描述模糊:会导致Planner选错插件
  • 忽略成本:规划器会调用多次LLM

❓ 常见问题

Q1: SK vs LangChain如何选择?

  • 选SK:使用C#/.NET技术栈,或需要Azure深度集成
  • 选LangChain:使用Python,追求丰富生态和社区
  • 技术特点:SK更工程化,LangChain更灵活

Q2: Planner规划失败怎么办?

  • • 简化目标描述,拆分复杂任务
  • • 优化插件的description
  • • 减少插件数量,避免选择困难
  • • 使用gpt-4而非gpt-3.5

Q3: 如何优化性能?

  • • 缓存函数结果
  • • 使用Action Planner代替Sequential
  • • 批量处理减少API调用
  • • 启用流式输出

开始学习Semantic Kernel