今年.NET Conf China 2023技術(shù)大會(huì),我給大家分享了 .NET應(yīng)用國際化-AIGC智能翻譯+代碼生成的議題
.NET Conf China 2023分享-.NET應(yīng)用國際化-AIGC智能翻譯+代碼生成
今天將詳細(xì)的代碼實(shí)現(xiàn)和大家分享一下。
一、前提準(zhǔn)備
1. 新建一個(gè)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中創(chuàng)建一個(gè)GPT4的服務(wù),這個(gè)可能大家沒有賬號(hào),那就先看代碼如何實(shí)現(xiàn)吧
部署好GPT4模型后,可以拿到以下三個(gè)重要的值
{{$input}} 請(qǐng)將上面的輸入翻譯為英文,不要返回任何解釋說明, 請(qǐng)扮演一個(gè)美國電動(dòng)汽車充電服務(wù)運(yùn)營商(精通中文和英文),用戶的輸入數(shù)據(jù)是JSON格式,例如{"1":"充電站", "2":"充電樁"}, 如果不是JSON格式,請(qǐng)返回?zé)o效的輸入。 請(qǐng)使用以下專業(yè)術(shù)語進(jìn)行翻譯 { "充電站":"Charging station", "電站":"Charging station", "場站":"Charging station", "充電樁":"Charging point", "充電終端":"Charging point", "終端":"Charging point", "電動(dòng)汽車":"Electric Vehicle", "直流快充":"DC Fast Charger", "超級(jí)充電站":"Supercharger", "智能充電":"Smart Charging", "交流慢充":"AC Slow Charging" } 翻譯結(jié)果請(qǐng)以JSON格式返回,例如 {"1":"Charging station", "2":"Charging point"}
類似的還有葡萄牙下的翻譯Prompt
{{$input}} 請(qǐng)將上面的輸入翻譯為葡萄牙語,不要返回任何解釋說明,請(qǐng)扮演一個(gè)巴西的電動(dòng)汽車充電服務(wù)運(yùn)營商(精通葡萄牙語、中文和英文) 用戶的輸入數(shù)據(jù)是JSON格式,例如{"1":"充電站", "2":"充電樁"}, 如果不是JSON格式,請(qǐng)返回?zé)o效的輸入 請(qǐng)使用以下專業(yè)術(shù)語進(jìn)行翻譯 { "充電站": "Esta??o de carregamento", "電站": "Esta??o de carregamento", "場站": "Esta??o de carregamento", "充電樁": "Ponto de carregamento", "充電終端": "Ponto de carregamento", "終端": "Ponto de carregamento", "電動(dòng)汽車": "Veículo Elétrico", "直流快充": "Carregador Rápido DC", "超級(jí)充電站": "Supercharger", "智能充電": "Carregamento Inteligente", "交流慢充": "Carregamento AC Lento" } 請(qǐng)以JSON格式返回,例如 {"1":"Esta??o de carregamento", "2":"Ponto de carregamento"}
在項(xiàng)目工程下新建Plugins目錄和TranslatePlugin子目錄,同時(shí)新建Translator_en和Translator_pt等多個(gè)子目錄
?config.json文件下的內(nèi)容如下:
{ "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翻譯類,實(shí)現(xiàn)文本多語言翻譯
這個(gè)類主要實(shí)現(xiàn)將用戶輸入的文本(系統(tǒng)處理為JSON格式),翻譯為指定的語言
這個(gè)類中構(gòu)造函數(shù)中接收傳入的Kernel對(duì)象,這個(gè)Kernel對(duì)象是指
// // 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
暫且理解為調(diào)用各類大模型的Kernel核心類,基于這個(gè)Kernel實(shí)例對(duì)象完成大模型的調(diào)用和交互
另外,上述代碼中有個(gè)Prompt模板文件讀取的操作。
?從Plugins/TranslatePlugin目錄下讀取指定的KernelPlugin,例如Translator_en英語翻譯插件和Translator_pt 葡萄牙翻譯插件
?var output = kernel.InvokeAsync(plugin["Translator_" + language + ""], new() { ["input"] = json }).Result.ToString();
?調(diào)用KernelFunction方式實(shí)現(xiàn)GPT4大模型調(diào)用
// // 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); }
繼續(xù)封裝GPT4TranslateService,構(gòu)造Microsoft.SemanticKernel.Kernel 類實(shí)例。
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 ); } //私有方法,構(gòu)造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(); } }
四、測試調(diào)用
這里我們?cè)O(shè)計(jì)了2種語言,英語和葡萄牙的文本翻譯
var culture = new CultureInfo("en-US"); var translator = new GPT4TranslateService(); translator.Translate(new Dictionary<int, string>(){{ 1,"電站"}, {2,"終端不可用"},{3,"充電樁不可用"} , {4,"場站"},{5,"充電站暫未運(yùn)營" }},culture); culture = new CultureInfo("pt-BR"); translator.Translate(new Dictionary<int, string>(){{ 1,"電站"}, {2,"終端不可用"},{3,"充電樁不可用"} , {4,"場站"},{5,"充電站暫未運(yùn)營" }},culture);
輸出的結(jié)果
{"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"}
五、總結(jié)
以上是基于SemanticKernel和GPT4實(shí)現(xiàn)一個(gè)智能翻譯服務(wù)的Demo和框架,大家可以基于這個(gè)示例繼續(xù)完善,增加更多動(dòng)態(tài)的數(shù)據(jù)和API調(diào)用,例如將JSON數(shù)據(jù)寫入數(shù)據(jù)庫
同時(shí)還可以記錄翻譯不穩(wěn)定的異常,手工處理或者繼續(xù)完善Prompt。
?
周國慶文章來源:http://www.zghlxwxcb.cn/news/detail-825328.html
2024/2/17文章來源地址http://www.zghlxwxcb.cn/news/detail-825328.html
到了這里,關(guān)于基于Microsoft SemanticKernel和GPT4實(shí)現(xiàn)一個(gè)智能翻譯服務(wù)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!