Semantic Kernel 是微软推出的一个强大框架,允许开发者轻松创建具有高级功能的AI代理。本文将详细指导你如何使用C#创建一个交互式AI应用。
首先,你需要安装以下NuGet包:
Bashdotnet add package Microsoft.SemanticKernel dotnet add package Microsoft.Extensions.Logging dotnet add package Microsoft.Extensions.Logging.Console
在开始之前,确保你已经:
C#using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.OpenAI;
namespace AppSemantic01
{
internal class Program
{
static async Task Main(string[] args)
{
// 配置OpenAI服务参数
var modelId = "Qwen/QVQ-72B-Preview";
var endpoint = "https://api.siliconflow.cn/v1/chat/completions";
var apiKey = "sk-******";
// 创建Kernel构建器
var httpClient = new HttpClient(new SiliconflowOpenAIHttpClientHandler());
var builder = Kernel.CreateBuilder().AddOpenAIChatCompletion(modelId: modelId,
apiKey: apiKey, httpClient: httpClient);
// 添加日志服务
builder.Services.AddLogging(services =>
services.AddConsole().SetMinimumLevel(LogLevel.Trace));
// 构建Kernel
Kernel kernel = builder.Build();
// 获取聊天完成服务
var chatCompletionService = kernel.GetRequiredService<IChatCompletionService>();
// 创建聊天历史记录
var history = new ChatHistory();
// 主交互循环
while (true)
{
Console.Write("User > ");
var userInput = Console.ReadLine();
if (string.IsNullOrWhiteSpace(userInput))
break;
// 将用户输入添加到聊天历史
history.AddUserMessage(userInput);
// 获取AI响应
var result = await chatCompletionService.GetChatMessageContentAsync(
history,
kernel:kernel
);
// 打印AI响应
Console.WriteLine("Assistant > " + result);
// 将AI响应添加到聊天历史
history.AddMessage(result.Role, result.Content ?? string.Empty);
}
}
}
}
C#using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AppSemantic01
{
public class SiliconflowOpenAIHttpClientHandler : HttpClientHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
switch (request.RequestUri?.LocalPath)
{
case "/v1/chat/completions":
var uriBuilder = new UriBuilder(request.RequestUri)
{
Scheme = "https",
Path= "/v1/chat/completions",
Host = "api.siliconflow.cn",
};
request.RequestUri = uriBuilder.Uri;
break;
}
HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
return response;
}
}
}
Semantic Kernel 为开发者提供了一个强大的框架,使得构建智能、可交互的AI代理变得简单而直观。通过灵活的插件系统和先进的函数调用能力,你可以创建具有复杂交互能力的AI应用。
本文作者:技术老小子
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!