연습 - 자동으로 함수 호출

완료됨

이 연습에서는 프롬프트를 사용하여 사용자에게 노래를 권장하거나 최근 재생한 음악 목록에 노래를 추가하는 함수를 자동으로 호출하는 방법을 실습합니다. 그럼 시작하겠습니다.

  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 설정을 사용하면 사용자의 요구에 맞는 플러그 인을 빌드하는 데 집중할 수 있습니다.