终极Semantic Kernel入门指南:从AI小白到多智能体应用开发大师

【免费下载链接】semantic-kernel Integrate cutting-edge LLM technology quickly and easily into your apps 【免费下载链接】semantic-kernel 项目地址: https://gitcode.com/GitHub_Trending/se/semantic-kernel

Semantic Kernel是一款企业级AI编排框架,能帮助开发者轻松构建智能AI代理和多代理系统。无论你是想创建简单的聊天机器人,还是复杂的多智能体工作流,Semantic Kernel都提供了企业级可靠性和灵活性的工具,让你快速集成尖端LLM技术到应用中。

🚀 为什么选择Semantic Kernel?

Semantic Kernel作为一款模型无关的SDK,具有以下核心优势:

  • 模型灵活性:内置支持OpenAI、Azure OpenAI、Hugging Face等多种LLM
  • 多语言支持:提供Python、.NET和Java版本,满足不同技术栈需求
  • 企业级特性:完善的可观测性、安全性和稳定的API设计
  • 本地部署能力:支持Ollama、LMStudio和ONNX等本地运行环境

Semantic Kernel智能体设计架构 图:Semantic Kernel的智能体设计架构展示了AgentChat、AgentGroupChat等核心组件的关系

🔧 快速安装指南

系统要求

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

Python安装

pip install semantic-kernel

.NET安装

dotnet add package Microsoft.SemanticKernel
dotnet add package Microsoft.SemanticKernel.Agents.Core

🤖 核心概念解析

智能体(Agent)

智能体是Semantic Kernel的核心构建块,是具有特定能力的AI实体。每个智能体可以配备工具、拥有记忆,并能独立或协作完成任务。

智能体关系图 图:展示了AgentChat与多个通道(Channel)和智能体(Agent)之间的关系

插件(Plugins)

插件是一组相关功能的集合,使智能体能够执行特定任务。Semantic Kernel支持多种类型的插件:

  • 原生函数:用传统编程语言(C#、Python等)编写
  • 语义函数:用自然语言在skprompt.txt文件中定义
  • OpenAPI规范:通过API集成外部服务

Semantic Kernel函数架构 图:展示了Semantic Kernel v1.0版本的函数架构,包括原生函数和语义函数

提示模板(Prompt Templates)

提示模板是定义AI提示的结构化方式,支持多种模板引擎,使你能够创建可重用、动态生成的提示。

提示模板工厂架构 图:展示了Semantic Kernel的提示模板工厂架构,支持基础模板和Handlebars模板

💻 入门示例:创建你的第一个AI智能体

Python示例

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

.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);
}

🔌 为智能体添加插件功能

通过插件扩展智能体能力,以下是一个简单的菜单插件示例:

from semantic_kernel.functions import kernel_function

class MenuPlugin:
    @kernel_function(description="Provides a list of specials from the menu.")
    def get_specials(self) -> str:
        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: str) -> str:
        return "$9.99"

将插件添加到智能体:

agent = ChatCompletionAgent(
    service=AzureChatCompletion(),
    name="SK-Assistant",
    instructions="You are a helpful assistant.",
    plugins=[MenuPlugin()]
)

🏭 构建多智能体系统

Semantic Kernel允许你创建协作的智能体网络,每个智能体专注于特定任务:

多智能体流程架构 图:展示了多智能体系统中翻译智能体和摘要智能体如何通过流程编排器协作

以下是创建多智能体系统的示例:

# 创建专业智能体
billing_agent = ChatCompletionAgent(
    service=AzureChatCompletion(),
    name="BillingAgent",
    instructions="You handle billing issues like charges, payment methods, cycles, fees..."
)

refund_agent = ChatCompletionAgent(
    service=AzureChatCompletion(),
    name="RefundAgent",
    instructions="Assist users with refund inquiries, including eligibility, policies..."
)

# 创建分诊智能体
triage_agent = ChatCompletionAgent(
    service=OpenAIChatCompletion(),
    name="TriageAgent",
    instructions="Evaluate user requests and forward them to appropriate agent",
    plugins=[billing_agent, refund_agent],
)

📊 监控与管理智能体

Semantic Kernel提供了强大的监控工具,帮助你跟踪和管理智能体性能:

Aspire仪表板 图:Aspire仪表板展示了运行中的智能体资源状态和端点信息

📚 学习资源

🔍 常见问题解答

Q: 如何处理认证错误?

A: 检查API密钥环境变量是否正确设置,确保AZURE_OPENAI_API_KEY或OPENAI_API_KEY已配置。

Q: 支持哪些AI模型?

A: 支持OpenAI、Azure OpenAI、Hugging Face、NVidia、Ollama等多种模型,详见README.md中的"Key Features"部分。

Q: 如何贡献代码?

A: 请阅读CONTRIBUTING.md了解贡献指南,或通过COMMUNITY.md参与社区讨论。

🎯 总结

Semantic Kernel为AI应用开发提供了强大而灵活的框架,无论你是AI新手还是经验丰富的开发者,都能快速构建从简单聊天机器人到复杂多智能体系统的各类AI应用。通过本文介绍的基础知识和示例,你已经具备了开始使用Semantic Kernel的能力。

现在就克隆仓库开始你的AI开发之旅吧:

git clone https://gitcode.com/GitHub_Trending/se/semantic-kernel

祝你的AI应用开发之旅顺利!如有任何问题,欢迎参与项目的社区讨论。

【免费下载链接】semantic-kernel Integrate cutting-edge LLM technology quickly and easily into your apps 【免费下载链接】semantic-kernel 项目地址: https://gitcode.com/GitHub_Trending/se/semantic-kernel

Logo

更多推荐