练习 - 创建货币转换器

已完成

在本练习中,你将创建一个插件,允许用户将货币金额从一种货币转换为另一种货币。 由于模型无法访问 Internet 来确定当前汇率,因此需要在插件中提供汇率。 在本练习中,你将使用现有的 currencies.txt 文件来提供汇率。

重要

在开始本练习之前,需要完成上一单元“准备”中的设置说明。

创建本地函数

在此任务中,你将创建一个本机函数,该函数可将金额从基准货币转换为目标货币。

  1. 导航到CurrencyConverterPlugin.cs文件夹中的文件

  2. 创建一个ConvertAmount函数,使用以下代码:

    public static string ConvertAmount(string amount, string baseCurrencyCode, string targetCurrencyCode)
    {
        Currency targetCurrency = currencyDictionary[targetCurrencyCode];
        Currency baseCurrency = currencyDictionary[baseCurrencyCode];
    
        if (targetCurrency == null)
        {
            return targetCurrencyCode + " was not found";
        }
        else if (baseCurrency == null)
        {
            return baseCurrencyCode + " was not found";
        }
    }
    

    在此代码中,使用 Currency.Currencies 字典获取目标货币和基准货币的 Currency 对象。 在继续作之前,请检查是否已找到货币代码。

  3. 将货币转换逻辑添加到方法中。

    
        else
        {
            double amountInUSD = Double.Parse(amount) * baseCurrency.USDPerUnit;
            double result = amountInUSD * targetCurrency.UnitsPerUSD;
            return result + targetCurrencyCode;
        }
    

    在此代码中,将金额从基货币转换为目标货币,并返回包含已转换金额的字符串。 接下来,让我们添加内核函数属性。

  4. 将以下属性添加到 ConvertAmount 函数:

    [KernelFunction("ConvertAmount")]
    [Description("Converts an amount from one currency to another")]
    public static string ConvertAmount(string amount, string baseCurrencyCode, string targetCurrencyCode)
    {
    

    接下来,可以将插件注册到内核,以便它可以使用新 ConvertAmount 函数。

  5. Program.cs 文件中,注册插件并使用以下代码启用自动函数调用:

    kernel.ImportPluginFromType<CurrencyConverterPlugin>();
    
    OpenAIPromptExecutionSettings openAIPromptExecutionSettings = new() 
    {
        FunctionChoiceBehavior = FunctionChoiceBehavior.Auto()
    };
    
  6. 创建聊天历史记录对象并添加提示以指导大型语言模型(LLM):

    var history = new ChatHistory();
    AddUserMessage("Can you convert 52000 VND to USD?");
    await GetReply();
    
  7. 请通过将以下代码添加到方法中来完成AddUserMessage函数。

    void AddUserMessage(string msg) 
    {
        Console.WriteLine("User: " + msg);
        history.AddUserMessage(msg);
    }
    
  8. 将以下代码添加到 GetReply 方法以从 LLM 检索响应:

    async Task GetReply() 
    {
        ChatMessageContent reply = await chatCompletionService.GetChatMessageContentAsync(
            history,
            executionSettings: openAIPromptExecutionSettings,
            kernel: kernel
        );
    
        Console.WriteLine("Assistant: " + reply.ToString());
        history.AddAssistantMessage(reply.ToString());
    }
    

    现在,你已准备好测试插件函数。

  9. 在终端中输入 dotnet run。 应会看到以下输出:

    $52000 VND is approximately $2.13 in US Dollars (USD)
    

现在,你有一个插件,允许旅行社转换货币。 出色的工作!