练习 - 自动调用函数

已完成

在本练习中,你将试着使用提示来自动调用可向用户推荐歌曲或将歌曲添加到最近播放的音乐列表中的函数。 现在就开始吧!

  1. 打开在上一练习中使用的 Visual Studio Code 项目。

  2. 使用以下代码更新“Program.cs”文件:

    OpenAIPromptExecutionSettings settings = new()
    {
        ToolCallBehavior = ToolCallBehavior.AutoInvokeKernelFunctions
    };
    
    var songSuggesterFunction = kernel.CreateFunctionFromPrompt(
        promptTemplate: @"Based on the user's recently played music:
            {{$recentlyPlayedSongs}}
            recommend a song to the user from the music library:
            {{$musicLibrary}}",
        functionName: "SuggestSong",
        description: "Recommend a song from the library"
    );
    
    kernel.Plugins.AddFromFunctions("SuggestSong", [songSuggesterFunction]);
    
    string prompt = @"Can you recommend a song from the music library?";
    
    var result = await kernel.InvokePromptAsync(prompt, new(settings));
    
    Console.WriteLine(result);
    

    在此代码中,你将通过提示创建一个函数,告知 LLM 如何建议歌曲。 之后,将调用启用了自动函数调用设置的提示。 内核能够运行函数并提供正确的参数来完成提示。

  3. 在终端中,输入 dotnet run 以运行代码。

    生成的输出应根据最近播放的音乐向用户推荐歌曲。 响应可能类似于以下输出:

    Based on your recently played music, I recommend you listen to the song "Luv(sic)". It falls under the genres of hiphop and rap, which aligns with some of your recently played songs. Enjoy!  
    

    接下来,让我们尝试一个提示来更新最近播放的歌曲列表。

  4. 使用以下代码更新“Program.cs”文件:

    string prompt = @"Add this song to the recently played songs list:  title: 'Touch', artist: 'Cat's Eye', genre: 'Pop'";
    
    var result = await kernel.InvokePromptAsync(prompt, new(settings));
    
    Console.WriteLine(result);
    
  5. 在终端中输入 dotnet run

    输出应如下所示:

    I have added the song 'Touch' by Cat's Eye to the recently played songs list.
    

    打开 recentlyplayed.txt 文件时,应会看到添加到列表顶部的新歌曲。

使用 AutoInvokeKernelFunctions 设置可以专注于生成插件以满足用户的需求。