经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 大数据/云/AI » 人工智能基础 » 查看文章
基于Microsoft SemanticKernel和GPT4实现一个智能翻译服务
来源:cnblogs  作者:Eric zhou  时间:2024/2/18 9:01:53  对本文有异议

今年.NET Conf China 2023技术大会,我给大家分享了 .NET应用国际化-AIGC智能翻译+代码生成的议题

.NET Conf China 2023分享-.NET应用国际化-AIGC智能翻译+代码生成

今天将详细的代码实现和大家分享一下。

一、前提准备

1. 新建一个Console类的Project

2. 引用SK的Nuget包,SK的最新Nuget包

  1. dotnet add package Microsoft.SemanticKernel --version 1.4.0
  1. <ItemGroup>
  2. <PackageReference Include="Microsoft.SemanticKernel" Version="1.4.0" />
  3. <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
  4. </ItemGroup>

3. 在Azure OpenAI Service中创建一个GPT4的服务,这个可能大家没有账号,那就先看代码如何实现吧

部署好GPT4模型后,可以拿到以下三个重要的值

Azure OpenAI Deployment Name
Azure OpenAI Endpoint
Azure OpenAI Key
二、编写翻译使用的Prompt
  1. {{$input}}
  2. 请将上面的输入翻译为英文,不要返回任何解释说明,
  3. 请扮演一个美国电动汽车充电服务运营商(精通中文和英文),用户的输入数据是JSON格式,例如{"1":"充电站", "2":"充电桩"},
  4. 如果不是JSON格式,请返回无效的输入。
  5. 请使用以下专业术语进行翻译
  6. {
  7. "充电站":"Charging station",
  8. "电站":"Charging station",
  9. "场站":"Charging station",
  10. "充电桩":"Charging point",
  11. "充电终端":"Charging point",
  12. "终端":"Charging point",
  13. "电动汽车":"Electric Vehicle",
  14. "直流快充":"DC Fast Charger",
  15. "超级充电站":"Supercharger",
  16. "智能充电":"Smart Charging",
  17. "交流慢充":"AC Slow Charging"
  18. }
  19. 翻译结果请以JSON格式返回,例如 {"1":"Charging station", "2":"Charging point"}

类似的还有葡萄牙下的翻译Prompt

  1. {{$input}}
  2. 请将上面的输入翻译为葡萄牙语,不要返回任何解释说明,请扮演一个巴西的电动汽车充电服务运营商(精通葡萄牙语、中文和英文)
  3. 用户的输入数据是JSON格式,例如{"1":"充电站", "2":"充电桩"}, 如果不是JSON格式,请返回无效的输入
  4. 请使用以下专业术语进行翻译
  5. {
  6. "充电站": "Esta??o de carregamento",
  7. "电站": "Esta??o de carregamento",
  8. "场站": "Esta??o de carregamento",
  9. "充电桩": "Ponto de carregamento",
  10. "充电终端": "Ponto de carregamento",
  11. "终端": "Ponto de carregamento",
  12. "电动汽车": "Veículo Elétrico",
  13. "直流快充": "Carregador Rápido DC",
  14. "超级充电站": "Supercharger",
  15. "智能充电": "Carregamento Inteligente",
  16. "交流慢充": "Carregamento AC Lento"
  17. }
  18. 请以JSON格式返回,例如 {"1":"Esta??o de carregamento", "2":"Ponto de carregamento"}

在项目工程下新建Plugins目录和TranslatePlugin子目录,同时新建Translator_en和Translator_pt等多个子目录

 config.json文件下的内容如下:

  1. {
  2. "schema": 1,
  3. "type": "completion",
  4. "description": "Translate.",
  5. "completion": {
  6. "max_tokens": 2000,
  7. "temperature": 0.5,
  8. "top_p": 0.0,
  9. "presence_penalty": 0.0,
  10. "frequency_penalty": 0.0
  11. },
  12. "input": {
  13. "parameters": [
  14. {
  15. "name": "input",
  16. "description": "The user's input.",
  17. "defaultValue": ""
  18. }
  19. ]
  20. }
  21. }

三、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  
  1. //
  2. // Summary:
  3. // Provides state for use throughout a Semantic Kernel workload.
  4. //
  5. // Remarks:
  6. // An instance of Microsoft.SemanticKernel.Kernel is passed through to every function
  7. // invocation and service call throughout the system, providing to each the ability
  8. // to access shared state and services.
  9. 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大模型调用

  1. //
  2. // Summary:
  3. // Invokes the Microsoft.SemanticKernel.KernelFunction.
  4. //
  5. // Parameters:
  6. // function:
  7. // The Microsoft.SemanticKernel.KernelFunction to invoke.
  8. //
  9. // arguments:
  10. // The arguments to pass to the function's invocation, including any Microsoft.SemanticKernel.PromptExecutionSettings.
  11. //
  12. //
  13. // cancellationToken:
  14. // The System.Threading.CancellationToken to monitor for cancellation requests.
  15. // The default is System.Threading.CancellationToken.None.
  16. //
  17. // Returns:
  18. // The result of the function's execution.
  19. //
  20. // Exceptions:
  21. // T:System.ArgumentNullException:
  22. // function is null.
  23. //
  24. // T:Microsoft.SemanticKernel.KernelFunctionCanceledException:
  25. // The Microsoft.SemanticKernel.KernelFunction's invocation was canceled.
  26. //
  27. // Remarks:
  28. // This behaves identically to invoking the specified function with this Microsoft.SemanticKernel.Kernel
  29. // as its Microsoft.SemanticKernel.Kernel argument.
  30. public Task<FunctionResult> InvokeAsync(KernelFunction function, KernelArguments? arguments = null, CancellationToken cancellationToken = default(CancellationToken))
  31. {
  32. Verify.NotNull(function, "function");
  33. return function.InvokeAsync(this, arguments, cancellationToken);
  34. }

 继续封装GPT4TranslateService,构造Microsoft.SemanticKernel.Kernel 类实例。

  1. using System.Globalization;
  2. using Microsoft.SemanticKernel;
  3. namespace LLM_SK;
  4. public class GPT4TranslateService
  5. {
  6. public IDictionary<int,string> Translate(IDictionary<int, string> texts, CultureInfo cultureInfo)
  7. {
  8. var kernel = BuildKernel();
  9. var translator = new Translator(kernel);
  10. return translator.Translate(texts, cultureInfo.TwoLetterISOLanguageName );
  11. }
  12. //私有方法,构造IKernel
  13. private Kernel BuildKernel()
  14. {
  15. var builder = Kernel.CreateBuilder();
  16. builder.AddAzureOpenAIChatCompletion(
  17. "xxxxgpt4", // Azure OpenAI Deployment Name
  18. "https://****.openai.azure.com/", // Azure OpenAI Endpoint
  19. "***************"); // Azure OpenAI Key
  20.  
  21. return builder.Build();
  22. }
  23. }

四、测试调用

这里我们设计了2种语言,英语和葡萄牙的文本翻译

  1. var culture = new CultureInfo("en-US");
  2. var translator = new GPT4TranslateService();
  3. translator.Translate(new Dictionary<int, string>(){{ 1,"电站"}, {2,"终端不可用"},{3,"充电桩不可用"} ,
  4. {4,"场站"},{5,"充电站暂未运营" }},culture);
  5. culture = new CultureInfo("pt-BR");
  6. translator.Translate(new Dictionary<int, string>(){{ 1,"电站"}, {2,"终端不可用"},{3,"充电桩不可用"} ,
  7. {4,"场站"},{5,"充电站暂未运营" }},culture);

输出的结果

  1. {"1":"Charging station","2":"Charging point unavailable","3":"Charging station unavailable","4":"Charging station","5":"Charging station not in operation yet"}
  2. {"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

原文链接:https://www.cnblogs.com/tianqing/p/18018050

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号