惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

量子位
C
CXSECURITY Database RSS Feed - CXSecurity.com
S
Schneier on Security
博客园 - 叶小钗
博客园 - 三生石上(FineUI控件)
C
Cybersecurity and Infrastructure Security Agency CISA
Engineering at Meta
Engineering at Meta
Google DeepMind News
Google DeepMind News
酷 壳 – CoolShell
酷 壳 – CoolShell
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园_首页
T
Threat Research - Cisco Blogs
C
Cisco Blogs
Recent Announcements
Recent Announcements
S
Securelist
N
Netflix TechBlog - Medium
The Register - Security
The Register - Security
P
Privacy & Cybersecurity Law Blog
宝玉的分享
宝玉的分享
D
Darknet – Hacking Tools, Hacker News & Cyber Security
L
LINUX DO - 热门话题
T
Tor Project blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
月光博客
月光博客
AWS News Blog
AWS News Blog
P
Proofpoint News Feed
博客园 - 司徒正美
L
LINUX DO - 最新话题
Stack Overflow Blog
Stack Overflow Blog
博客园 - 聂微东
H
Help Net Security
Spread Privacy
Spread Privacy
PCI Perspectives
PCI Perspectives
Project Zero
Project Zero
I
Intezer
T
The Blog of Author Tim Ferriss
有赞技术团队
有赞技术团队
The Last Watchdog
The Last Watchdog
C
Check Point Blog
Blog — PlanetScale
Blog — PlanetScale
B
Blog RSS Feed
MyScale Blog
MyScale Blog
V
Vulnerabilities – Threatpost
Recorded Future
Recorded Future
T
Tenable Blog
Jina AI
Jina AI
D
DataBreaches.Net
阮一峰的网络日志
阮一峰的网络日志

博客园 - 黄明基

解剖一个桌面级 AI Copilot 的架构:Stargazer AI Copilot(.NET 10 + Avalonia)是怎么“分层”的 StargazerLab Copilot使用说明 🚀 用 .NET + Avalonia 打造你的专属 AI Copilot 桌面端 分布式应用框架Microsoft Orleans - 7、基于 Microsoft Orleans 构建模块化微服务:用户、消息与存储三大核心模块解析 Semantic Kernel人工智能开发 - 第六章:Semantic Kernel的安全与过滤器机制——构建可信赖的AI应用防护体系 Semantic Kernel人工智能开发 - 第五章:提示词工程与模板优化——释放大语言模型真正潜力 Semantic Kernel人工智能开发 - 第四章:Semantic Kernel内存管理系统——为AI注入持久记忆与上下文感知能力 Semantic Kernel人工智能开发 - 第三章:Semantic Kernel插件系统详解——扩展AI能力的核心引擎 Semantic Kernel人工智能开发 - 第一章:Semantic Kernel框架概览——开启智能应用开发之门 结合.NET Aspire与Spring Boot:构建可观测的云原生Java应用 分布式应用框架Microsoft Orleans - 6、构建高可用Orleans应用:集群配置与容灾机制详解 分布式应用框架Microsoft Orleans - 5、掌握Orleans高级特性:计时器、提醒与流处理详解 分布式应用框架Microsoft Orleans - 4、掌握Microsoft Orleans状态管理:从持久化配置到事务处理 分布式应用框架Microsoft Orleans - 3、深入解析Orleans核心要素:Grain与Silo的工作原理 分布式应用框架Microsoft Orleans - 2、动手实践:构建你的第一个Microsoft Orleans应用程序 分布式应用框架Microsoft Orleans - 1、Microsoft Orleans简介 AI真的太好用啦!Aspire Dashboard集成GitHub Copilot。 智能助手客户端 设计模式学习:状态模式实现订单状态流转 设计模式学习:在支付系统中的实战应用 跨平台桌面应用开发:解锁 Electron 与 shadcn/ui 的潜力 构建你的.NET Aspire解决方案
Semantic Kernel人工智能开发 - 第二章:环境搭建与第一个AI应用——从零开始构建智能对话系统
黄明基 · 2025-12-22 · via 博客园 - 黄明基

1. 环境准备与安装配置

在开始使用Semantic Kernel之前,我们需要先搭建完整的开发环境。本章将详细介绍如何配置开发环境并创建第一个AI应用。

1.1 开发环境要求

操作系统支持

  • Windows 10/11

  • macOS 10.15+

  • Linux Ubuntu 18.04+

开发工具

  • Visual Studio 2022 17.8+ 或 Visual Studio Code

  • .NET SDK 8.0+(C#)

1.2 安装Semantic Kernel及Ollama连接器

C#/.NET环境安装

# 创建新项目
dotnet new console -n MyFirstAIApp
cd MyFirstAIApp

# 安装Semantic Kernel包
dotnet add package Microsoft.SemanticKernel
dotnet add package Microsoft.SemanticKernel.Connectors.Ollama

1.3 配置AI服务

Semantic Kernel支持多种AI服务,包括OpenAI、Azure OpenAI等。以下是基本配置方法:

配置Ollama服务

using Microsoft.Extensions.AI;  
using Microsoft.SemanticKernel;

// 创建内核构建器  
var builder = Kernel.CreateBuilder();  
  
// 从环境变量中获取endpoint  
string ollamaUri = Environment.GetEnvironmentVariable("OLLAMA-LLAMA2_URI") ?? throw new ArgumentNullException($"OLLAMA-LLAMA2_URI");  
// 添加OpenAI聊天完成服务  
builder.AddOllamaChatClient(  
    modelId: "llama2",  
    endpoint: new Uri(ollamaUri)  
);  
  
// 构建内核  
var kernel = builder.Build();

配置OpenAI服务,连接Deepseek开放平台

var openAIClientCredential = new ApiKeyCredential("your-deepseek-apikey");  
var openAIClientOption = new OpenAIClientOptions  
{  
    Endpoint = new Uri("https://api.deepseek.com"),  
};  
var builder = Kernel.CreateBuilder()  
    .AddOpenAIChatCompletion(modelId, new OpenAIClient(openAIClientCredential, openAIClientOption));  
  
var kernel = builder.Build();

2. 理解内核(Kernel)核心概念

2.1 内核的作用与重要性

内核是Semantic Kernel的核心组件,它充当AI服务的协调中心,负责管理插件、记忆和执行上下文。可以将其类比为计算机的操作系统内核,统一调度各种资源和服务。

2.2 内核的基本配置

基础内核初始化

// 创建内核构建器
IKernelBuilder kernelBuilder = Kernel.CreateBuilder();

// 添加基础服务
kernelBuilder.Services.AddLogging(loggingBuilder =>
    loggingBuilder.AddConsole().SetMinimumLevel(LogLevel.Information));

// 添加AI服务
kernelBuilder.AddOpenAIChatCompletion("gpt-3.5-turbo", "your-api-key");

// 构建内核
Kernel kernel = kernelBuilder.Build();

2.3 多模型支持配置

在实际应用中,我们可能需要同时使用多个AI模型。Semantic Kernel支持灵活的多模型配置:

// 配置多个AI服务
kernelBuilder.AddAzureOpenAIChatCompletion(
    deploymentName: "gpt-4",
    endpoint: "https://your-endpoint.openai.azure.com/",
    apiKey: "your-azure-key",
    serviceId: "gpt4-service"  // 指定服务ID
);

kernelBuilder.AddOpenAIChatCompletion(
    modelId: "gpt-3.5-turbo", 
    apiKey: "your-openai-key",
    serviceId: "gpt3-service"  // 指定服务ID
);

3. 创建第一个AI应用:智能对话系统

3.1 基础对话功能实现

让我们创建一个简单的控制台对话应用:

using Microsoft.Extensions.AI;  
using Microsoft.SemanticKernel;  

var configuration = new ConfigurationBuilder()  
    .SetBasePath(Directory.GetCurrentDirectory())  
    .AddJsonFile("appsettings.json")  
    .Build();
  
string apiKey = configuration.GetRequiredSection("api_key").Value ?? "";  
var openAIClientCredential = new ApiKeyCredential(apiKey);
var openAIClientOption = new OpenAIClientOptions  {    
	Endpoint = new Uri("https://api.deepseek.com")
};
var builder = Kernel.CreateBuilder()    
    .AddOpenAIChatCompletion(modelId: "deepseek-chat", openAIClient: new OpenAIClient(openAIClientCredential, openAIClientOption));
  
// 构建内核  
var kernel = builder.Build();  
var chatCompletionService = kernel.GetRequiredService<IChatCompletionService>();  
ChatHistory chatHistory = new();  
chatHistory.AddSystemMessage("你是一个专业的客服助手,请根据以下规则回答问题:\n1. 始终使用中文回答\n2. 保持友好和专业的态度\n3. 回答要简洁明了,不超过100字\n4. 如果遇到不确定的问题,建议用户联系专业支持");  
  
while (true)  
{  
    Console.WriteLine("User: ");  
    var content = Console.ReadLine();  
    if (content == "exit")  
    {        
	    break;  
    }  
    if (string.IsNullOrWhiteSpace(content))  
    {        
	    continue;  
    }  
    chatHistory.AddUserMessage(content);  
    // 创建聊天请求  
    var stream = chatCompletionService.GetStreamingChatMessageContentsAsync(chatHistory);  
    Console.WriteLine("Assistant: ");  
    StringBuilder assistantMessage = new StringBuilder();  
	await foreach (var response in stream)  
	{  
	    assistantMessage.Append(response.Content);  
	    Console.Write(response.Content);  
	}  
	chatHistory.AddAssistantMessage(assistantMessage.ToString()); 
    Console.WriteLine();  
}

3.2 使用提示词模板

提示词模板是Semantic Kernel的重要特性,让我们创建更结构化的对话:

// 创建带模板的提示函数
string promptTemplate = """
                        你是一个专业的客服助手,请根据以下规则回答问题:
                        1. 保持友好和专业的态度
                        2. 回答要简洁明了,不超过100字
                        3. 如果遇到不确定的问题,建议用户联系专业支持
                        
                        用户问题:{{$input}}
                        """;

// 创建提示函数
KernelFunction promptFunction = kernel.CreateFunctionFromPrompt(promptTemplate);

// 使用提示函数
KernelArguments arguments = new() { ["input"] = "我的订单什么时候能到?" };
FunctionResult result = await kernel.InvokeAsync(promptFunction, arguments);
Console.WriteLine(result.GetValue<string>());

3.3 添加基本插件功能

插件是扩展AI能力的重要手段。让我们创建一个简单的时间插件:

// 定义时间插件
public class TimePlugin
{
    [KernelFunction, Description("获取当前时间")]
    public string GetCurrentTime() => DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
    
    [KernelFunction, Description("获取指定天数后的日期")]
    public string GetDateAfterDays([Description("天数")] int days) 
        => DateTime.Now.AddDays(days).ToString("yyyy-MM-dd");
}

// 注册插件到内核
kernel.ImportPluginFromType<TimePlugin>("time");

// 使用插件
var timeResult = await kernel.InvokeAsync("time", "GetCurrentTime");
Console.WriteLine($"当前时间: {timeResult.GetValue<string>()}");

4. 应用测试与调试

4.1 测试对话功能

运行应用后,尝试以下测试对话:

用户: 你好,今天天气怎么样?
AI助手: 我是一个AI助手,无法获取实时天气信息,但您可以告诉我您的位置,我可以为您提供一般的天气建议。

用户: 那现在几点?
AI助手: 当前时间是:2024-06-19 14:30:25

4.2 错误处理与调试

添加基本的错误处理机制:

try
{
    var result = await kernel.InvokeAsync(function, arguments);
    Console.WriteLine(result.GetValue<string>());
}
catch (Exception ex)
{
    Console.WriteLine($"发生错误: {ex.Message}");
    // 记录详细日志
    kernel.Logger.LogError(ex, "函数执行失败");
}

5. 常见问题与解决方案

5.1 安装问题

  • NuGet包安装失败:检查网络连接,尝试使用国内镜像源

  • Python包冲突:使用虚拟环境隔离项目依赖

5.2 API配置问题

  • 认证失败:确认API密钥正确且未过期

  • 端点连接超时:检查网络设置,特别是企业防火墙限制

5.3 性能优化建议

  • 使用连接池管理HTTP连接

  • 实现适当的重试机制处理临时性故障

总结

本章我们完成了Semantic Kernel开发环境的搭建,并创建了第一个智能对话应用。通过实践,我们掌握了:

  1. 环境配置:安装必要的开发工具和SDK

  2. 内核初始化:创建和配置Kernel实例

  3. 基础功能实现:构建简单的对话系统

  4. 插件开发:扩展AI能力

  5. 测试调试:验证应用功能并处理异常

这些基础技能为后续学习更高级功能(如插件系统、规划器、记忆管理等)奠定了坚实基础。在下一章中,我们将深入探讨Semantic Kernel的插件系统,学习如何创建和使用更复杂的功能模块。


相关代码:https://github.com/huangmingji/semantic-kernel-project