基于Microsoft SemanticKernel和GPT4实现一个智能翻译服务
今年.NET Conf China 2023技术大会,我给大家分享了 .NET应用国际化-AIGC智能翻译+代码生成的议题
.NET Conf China 2023分享-.NET应用国际化-AIGC智能翻译+代码生成
今天将详细的代码实现和大家分享一下。
一、前提准备
1. 新建一个Console类的Project
2. 引用SK的Nuget包,SK的最新Nuget包
dotnet add package Microsoft.SemanticKernel --version 1.4.0
<ItemGroup>
<PackageReference Include="Microsoft.SemanticKernel" Version="1.4.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
3. 在Azure OpenAI Service中创建一个GPT4的服务,这个可能大家没有账号,那就先看代码如何实现吧
部署好GPT4模型后,可以拿到以下三个重要的值
{{$input}}
请将上面的输入翻译为英文,不要返回任何解释说明,
请扮演一个美国电动汽车充电服务运营商(精通中文和英文),用户的输入数据是JSON格式,例如{"1":"充电站", "2":"充电桩"},
如果不是JSON格式,请返回无效的输入。
请使用以下专业术语进行翻译
{
"充电站":"Charging station",
"电站":"Charging station",
"场站":"Charging station",
"充电桩":"Charging point",
"充电终端":"Charging point",
"终端":"Charging point",
"电动汽车":"Electric Vehicle",
"直流快充":"DC Fast Charger",
"超级充电站":"Supercharger",
"智能充电":"Smart Charging",
"交流慢充":"AC Slow Charging"
}
翻译结果请以JSON格式返回,例如 {"1":"Charging station", "2":"Charging point"}
类似的还有葡萄牙下的翻译Prompt
{{$input}}
请将上面的输入翻译为葡萄牙语,不要返回任何解释说明,请扮演一个巴西的电动汽车充电服务运营商(精通葡萄牙语、中文和英文)
用户的输入数据是JSON格式,例如{"1":"充电站", "2":"充电桩"}, 如果不是JSON格式,请返回无效的输入
请使用以下专业术语进行翻译
{
"充电站": "Estação de carregamento",
"电站": "Estação de carregamento",
"场站": "Estação de carregamento",
"充电桩": "Ponto de carregamento",
"充电终端": "Ponto de carregamento",
"终端": "Ponto de carregamento",
"电动汽车": "Veículo Elétrico",
"直流快充": "Carregador Rápido DC",
"超级充电站": "Supercharger",
"智能充电": "Carregamento Inteligente",
"交流慢充": "Carregamento AC Lento"
}
请以JSON格式返回,例如 {"1":"Estação de carregamento", "2":"Ponto de carregamento"}
在项目工程下新建Plugins目录和TranslatePlugin子目录,同时新建Translator_en和Translator_pt等多个子目录

config.json文件下的内容如下:
{
"schema": 1,
"type": "completion",
"description": "Translate.",
"completion": {
"max_tokens": 2000,
"temperature": 0.5,
"top_p": 0.0,
"presence_penalty": 0.0,
"frequency_penalty": 0.0
},
"input": {
"parameters": [
{
"name": "input",
"description": "The user's input.",
"defaultValue": ""
}
]
}
}
三、Translator翻译类,实现文本多语言翻译
这个类主要实现将用户输入的文本(系统处理为JSON格式),翻译为指定的语言
这个类中构造函数中接收传入的Kernel对象,这个Kernel对象是指
//
// Summary:
// Provides state for use throughout a Semantic Kernel workload.
//
// Remarks:
// An instance of Microsoft.SemanticKernel.Kernel is passed through to every function
// invocation and service call throughout the system, providing to each the ability
// to access shared state and services.
public sealed class Kernel
暂且理解为调用各类大模型的Kernel核心类,基于这个Kernel实例对象完成大模型的调用和交互
另外,上述代码中有个Prompt模板文件读取的操作。

从Plugins/TranslatePlugin目录下读取指定的KernelPlugin,例如Translator_en英语翻译插件和Translator_pt 葡萄牙翻译插件
var output = kernel.InvokeAsync(plugin["Translator_" + language + ""], new() { ["input"] = json }).Result.ToString();
调用KernelFunction方式实现GPT4大模型调用
//
// Summary:
// Invokes the Microsoft.SemanticKernel.KernelFunction.
//
// Parameters:
// function:
// The Microsoft.SemanticKernel.KernelFunction to invoke.
//
// arguments:
// The arguments to pass to the function's invocation, including any Microsoft.SemanticKernel.PromptExecutionSettings.
//
//
// cancellationToken:
// The System.Threading.CancellationToken to monitor for cancellation requests.
// The default is System.Threading.CancellationToken.None.
//
// Returns:
// The result of the function's execution.
//
// Exceptions:
// T:System.ArgumentNullException:
// function is null.
//
// T:Microsoft.SemanticKernel.KernelFunctionCanceledException:
// The Microsoft.SemanticKernel.KernelFunction's invocation was canceled.
//
// Remarks:
// This behaves identically to invoking the specified function with this Microsoft.SemanticKernel.Kernel
// as its Microsoft.SemanticKernel.Kernel argument.
public Task<FunctionResult> InvokeAsync(KernelFunction function, KernelArguments? arguments = null, CancellationToken cancellationToken = default(CancellationToken))
{
Verify.NotNull(function, "function");
return function.InvokeAsync(this, arguments, cancellationToken);
}
继续封装GPT4TranslateService,构造Microsoft.SemanticKernel.Kernel 类实例。
using System.Globalization;
using Microsoft.SemanticKernel; namespace LLM_SK;
public class GPT4TranslateService
{
public IDictionary<int,string> Translate(IDictionary<int, string> texts, CultureInfo cultureInfo)
{
var kernel = BuildKernel();
var translator = new Translator(kernel);
return translator.Translate(texts, cultureInfo.TwoLetterISOLanguageName );
} //私有方法,构造IKernel
private Kernel BuildKernel()
{
var builder = Kernel.CreateBuilder();
builder.AddAzureOpenAIChatCompletion(
"xxxxgpt4", // Azure OpenAI Deployment Name
"https://****.openai.azure.com/", // Azure OpenAI Endpoint
"***************"); // Azure OpenAI Key return builder.Build();
}
}
四、测试调用
这里我们设计了2种语言,英语和葡萄牙的文本翻译
var culture = new CultureInfo("en-US");
var translator = new GPT4TranslateService();
translator.Translate(new Dictionary<int, string>(){{ 1,"电站"}, {2,"终端不可用"},{3,"充电桩不可用"} ,
{4,"场站"},{5,"充电站暂未运营" }},culture);
culture = new CultureInfo("pt-BR");
translator.Translate(new Dictionary<int, string>(){{ 1,"电站"}, {2,"终端不可用"},{3,"充电桩不可用"} ,
{4,"场站"},{5,"充电站暂未运营" }},culture);
输出的结果
{"1":"Charging station","2":"Charging point unavailable","3":"Charging station unavailable","4":"Charging station","5":"Charging station not in operation yet"}
{"1":"Estação de carregamento","2":"Ponto de carregamento não está disponível","3":"Ponto de carregamento não está disponível","4":"Estação de carregamento","5":"A estação de carregamento ainda não está em operação"}
五、总结
以上是基于SemanticKernel和GPT4实现一个智能翻译服务的Demo和框架,大家可以基于这个示例继续完善,增加更多动态的数据和API调用,例如将JSON数据写入数据库
同时还可以记录翻译不稳定的异常,手工处理或者继续完善Prompt。
周国庆
2024/2/17
基于Microsoft SemanticKernel和GPT4实现一个智能翻译服务的更多相关文章
- 2、利用蓝牙定位及姿态识别实现一个智能篮球场套件(二)——CC2540/CC2541基于广播的RSSI获得
CC2541一拖多例程中RSSI获得是通过一个事件回调函数实现的,前提是需要连接上蓝牙设备. 这个对于多点定位来说是不可行的,由于主机搜索蓝牙设备过程中也能获得当前蓝牙设备的RSSI等信息,因此可基于 ...
- 1、利用蓝牙定位及姿态识别实现一个智能篮球场套件(一)——用重写CC2541透传模块做成智能手环
一.预言 要实现一个智能篮球场套件,需要设计一个佩戴在篮球运动员手臂上的可以检测投篮.记步的手环,以及一套可以根据RSSI定位运动员的蓝牙定位装置.下面是大致需要的步骤: 首先,需要用CC2541透传 ...
- 基于Microsoft Azure、ASP.NET Core和Docker的博客系统
欢迎阅读daxnet的新博客:一个基于Microsoft Azure.ASP.NET Core和Docker的博客系统 2008年11月,我在博客园开通了个人帐号,并在博客园发表了自己的第一篇博客 ...
- NEO从入门到开窗(1) - 一个智能合约的诞生
一.啰嗦两句 最近一直都在研究区块链,BitCoin,Etherenum, Hyper Ledger Fabric还有今天的主角小蚂蚁,当然出名以后改了一个艺名叫NEO.区块链大部分都是用Golang ...
- 基于Microsoft Graph打造自己的Timeline应用
原文链接:https://github.com/chenxizhang/office365dev/blob/e9b5a59cb827841d36692cc4ec52c11d43062e04/docs/ ...
- 深度学习项目——基于循环神经网络(RNN)的智能聊天机器人系统
基于循环神经网络(RNN)的智能聊天机器人系统 本设计研究智能聊天机器人技术,基于循环神经网络构建了一套智能聊天机器人系统,系统将由以下几个部分构成:制作问答聊天数据集.RNN神经网络搭建.seq2s ...
- 迁移基于Microsoft.DirectX的AudioRecoder类到SharpDX上
最近迁移项目到x64上,要处理的东西还是蛮多的,所以我要在说一次,不到万不得已不要用COM组件,要用COM组件也得首先考虑不需要我们关心平台的做法,或者得有64位版本. 比如Office的COM组件调 ...
- Mac下基于testrpc和truffle的以太坊智能合约开发环境搭建
原文地址:石匠的blog truffle是一个基于Javascript开发的一套智能合约开发框架,使用Solidity语言编写合约.truffle有一套自动的项目构建机制,集成了开发,测试和部署的各个 ...
- 将 WPF、UWP 以及其他各种类型的旧 csproj 迁移成基于 Microsoft.NET.Sdk 的新 csproj
原文 将 WPF.UWP 以及其他各种类型的旧 csproj 迁移成基于 Microsoft.NET.Sdk 的新 csproj 写过 .NET Standard 类库或者 .NET Core 程序的 ...
- 2018-12-6-Roslyn-如何基于-Microsoft.NET.Sdk-制作源代码包
title author date CreateTime categories Roslyn 如何基于 Microsoft.NET.Sdk 制作源代码包 lindexi 2018-12-06 16:2 ...
随机推荐
- python之pycharm常见使用技巧
一.ctrl+d:复制
- java - 对象装载数据传递到方法中
1. 创建 Phone 类 package class_object; public class Phone { String brand; String color; double price; v ...
- grpc-环境与示例
1. 数据传输基本原理 2. grpc环境安装 代码生成器 go get -u github.com/golang/protobuf/protoc-gen-go // 会自动在 $GOPATH/bin ...
- IDE-常用插件
2021-8-25_IDE-常用插件 1. 背景 提升编写代码的舒适度,提升开发效率 2. 常用插件列表 IDE EVal Reset 白嫖付费的golang编辑器,reset插件可以重置golang ...
- Shell-函数-function
- 【OpenVINO】基于 OpenVINO C# API 部署 RT-DETR 模型
RT-DETR是在DETR模型基础上进行改进的,一种基于 DETR 架构的实时端到端检测器,它通过使用一系列新的技术和算法,实现了更高效的训练和推理,在前文我们发表了<基于 OpenVINO ...
- Linux_sqlcmd或者是Cloudquery连接SQLSERVER2012的问题解决
Linux_sqlcmd或者是Cloudquery连接SQLSERVER2012的问题解决 背景 最近想使用shell脚本给SQLServer数据库插入数据,但是发现了报错 同时进行CLoudquer ...
- [转帖]signal 11 (SIGSEGV)错误排查
https://www.jianshu.com/p/a4250c72d391 jni调试最蛋疼的就是signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault a ...
- [转帖]tidb数据库5.4.3和6.5.3版本性能测试对比
https://tidb.net/blog/5454621f 一.测试需求: 基于历史原因,我们的业务数据库一直使用5.4.3,最近由于研发提出需求:需要升级到6.5.3版本,基于版本不同,需要做 ...
- [转帖]Linux中查找大文件两种姿势
https://rumenz.com/rumenbiji/linux-find-du-max-file.html 使用find命令查找大文件 find命令是Linux系统管理员工具库中最强大的工具之一 ...