今年.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模型后,可以拿到以下三个重要的值

Azure OpenAI Deployment Name
Azure OpenAI Endpoint

Azure OpenAI Key
二、编写翻译使用的Prompt
 {{$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格式),翻译为指定的语言

using System.Runtime.InteropServices;
using Microsoft.SemanticKernel;
using Newtonsoft.Json;
namespace LLM_SK;
public class Translator
{
    Kernel kernel;
    public Translator(Kernel kernel)
    {
        this.kernel = kernel;
    }
    public IDictionary<int, string> Translate(IDictionary<int, string> textList, string language)
    {
        var pluginDirectory = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "Plugins/TranslatePlugin");
        var plugin = kernel.CreatePluginFromPromptDirectory(pluginDirectory, "Translator_" + language + "");        
        var json = JsonConvert.SerializeObject(textList);      
        if (!string.IsNullOrEmpty(json))
        {
            var output = kernel.InvokeAsync(plugin["Translator_" + language + ""], new() { ["input"] = json }).Result.ToString();
            if (!string.IsNullOrWhiteSpace(output))
            {
                Console.WriteLine(output);
                return JsonConvert.DeserializeObject<Dictionary<int, string>>(output);
            }
        }
        return new Dictionary<int, string>();
    }
}

这个类中构造函数中接收传入的Kernel对象,这个Kernel对象是指

Microsoft.SemanticKernel.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模板文件读取的操作。

        var pluginDirectory = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "Plugins/TranslatePlugin");
        var plugin = kernel.CreatePluginFromPromptDirectory(pluginDirectory, "Translator_" + language + "");    

从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实现一个智能翻译服务的更多相关文章

  1. 2、利用蓝牙定位及姿态识别实现一个智能篮球场套件(二)——CC2540/CC2541基于广播的RSSI获得

    CC2541一拖多例程中RSSI获得是通过一个事件回调函数实现的,前提是需要连接上蓝牙设备. 这个对于多点定位来说是不可行的,由于主机搜索蓝牙设备过程中也能获得当前蓝牙设备的RSSI等信息,因此可基于 ...

  2. 1、利用蓝牙定位及姿态识别实现一个智能篮球场套件(一)——用重写CC2541透传模块做成智能手环

    一.预言 要实现一个智能篮球场套件,需要设计一个佩戴在篮球运动员手臂上的可以检测投篮.记步的手环,以及一套可以根据RSSI定位运动员的蓝牙定位装置.下面是大致需要的步骤: 首先,需要用CC2541透传 ...

  3. 基于Microsoft Azure、ASP.NET Core和Docker的博客系统

    欢迎阅读daxnet的新博客:一个基于Microsoft Azure.ASP.NET Core和Docker的博客系统   2008年11月,我在博客园开通了个人帐号,并在博客园发表了自己的第一篇博客 ...

  4. NEO从入门到开窗(1) - 一个智能合约的诞生

    一.啰嗦两句 最近一直都在研究区块链,BitCoin,Etherenum, Hyper Ledger Fabric还有今天的主角小蚂蚁,当然出名以后改了一个艺名叫NEO.区块链大部分都是用Golang ...

  5. 基于Microsoft Graph打造自己的Timeline应用

    原文链接:https://github.com/chenxizhang/office365dev/blob/e9b5a59cb827841d36692cc4ec52c11d43062e04/docs/ ...

  6. 深度学习项目——基于循环神经网络(RNN)的智能聊天机器人系统

    基于循环神经网络(RNN)的智能聊天机器人系统 本设计研究智能聊天机器人技术,基于循环神经网络构建了一套智能聊天机器人系统,系统将由以下几个部分构成:制作问答聊天数据集.RNN神经网络搭建.seq2s ...

  7. 迁移基于Microsoft.DirectX的AudioRecoder类到SharpDX上

    最近迁移项目到x64上,要处理的东西还是蛮多的,所以我要在说一次,不到万不得已不要用COM组件,要用COM组件也得首先考虑不需要我们关心平台的做法,或者得有64位版本. 比如Office的COM组件调 ...

  8. Mac下基于testrpc和truffle的以太坊智能合约开发环境搭建

    原文地址:石匠的blog truffle是一个基于Javascript开发的一套智能合约开发框架,使用Solidity语言编写合约.truffle有一套自动的项目构建机制,集成了开发,测试和部署的各个 ...

  9. 将 WPF、UWP 以及其他各种类型的旧 csproj 迁移成基于 Microsoft.NET.Sdk 的新 csproj

    原文 将 WPF.UWP 以及其他各种类型的旧 csproj 迁移成基于 Microsoft.NET.Sdk 的新 csproj 写过 .NET Standard 类库或者 .NET Core 程序的 ...

  10. 2018-12-6-Roslyn-如何基于-Microsoft.NET.Sdk-制作源代码包

    title author date CreateTime categories Roslyn 如何基于 Microsoft.NET.Sdk 制作源代码包 lindexi 2018-12-06 16:2 ...

随机推荐

  1. js - body的滚动事件的坑

    文章来源 : https://www.cnblogs.com/Zting00/p/7497629.html 踩过些坑,得到的结论,不一定精确 1. body的滚动条,刷新页面的时候不会回到顶部.其他d ...

  2. C#调用C++——CLR方式

    一直是在写C#,最近接触到的项目中有C#调用C++接口的逻辑,自己学习了下,写个步骤日志,C#掉用C++的托管代码 项目分三个项目:1.底层C++动态库项目,2.中间层的CLR项目,3.上层的C#项目 ...

  3. Redis异常问题分析黄金一分钟

    Redis异常问题分析黄金一分钟 背景 同事发现一个环境redis比较卡顿,导致业务比较难以开展. 问题是下午出现的. 六点左右找到我这边. 想着帮忙看看, 问题其实没有定位完全, 仅是发现了一个可能 ...

  4. [转帖]ESX/ESXi 主机上的每个插槽中安装了多少内存

    https://www.cnblogs.com/reachos/p/11242302.html 要确定在 ESX/ESXi 主机上的每个插槽中安装了多少内存,请执行以下操作: 1. 启动ssh服务 2 ...

  5. [转帖]GitHub 近两万 Star,无需编码,可一键生成前后端代码,这个开源项目JeecgBoot有点强

    GitHub 近两万 Star,无需编码,可一键生成前后端代码,这个开源项目JeecgBoot有点强 https://www.cnblogs.com/05-hust/p/14515686.html 一 ...

  6. [转帖]xtrabackup2.4备份恢复脚本

    https://developer.aliyun.com/article/534230#:~:text=xtrabackup2.4%E5%A4%87%E4%BB%BD%E6%81%A2%E5%A4%8 ...

  7. [转帖]《Linux性能优化实战》笔记(七)—— CPU瓶颈快速分析及性能优化思路

    相当于是前面篇章的小结 一. CPU 性能指标 常见指标包括: 平均负载 CPU 使用率(user.iowait.system.软硬中断等) 进程上下文切换(自愿.非自愿) CPU 缓存的命中率 CP ...

  8. [转帖]clickHouse单机模式安装部署(RPM安装)

    关于版本和系统的选择 操作系统:Centos-7 ClickHouse: rpm 在安装,20.x 安装前的准备 CentOS7 打开文件数限 在 /etc/security/limits.conf ...

  9. [转帖]JMeter InfluxDB v2.0 listener plugin

    https://github.com/mderevyankoaqa/jmeter-influxdb2-listener-plugin Support my Ukrainian Family ️ Lik ...

  10. 人大金仓学习之一_kwr的简单学习

    人大金仓学习之一_kwr的简单学习 摘要 周末在家想着学习一下数据库相关的内容. 网上找了不少资料, 想着直接在本地机器上面进行一下安装与验证 理论上linux上面应该更加简单. windows 上面 ...