練習 - 自動叫用函式

已完成

在本練習中,您將練習使用提示來自動呼叫可以向使用者建議歌曲或將歌曲新增至最近播放的音樂清單中的函式。 現在就開始吧!

  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 設定,可讓您專注於建置外掛程式以符合使用者的需求。