Microsoft MVP성태의 닷넷 이야기
.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지 [링크 복사], [링크+제목 복사]
조회: 3707
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
(시리즈 글이 8개 있습니다.)
.NET Framework: 2117. C# - (OpenAI 기반의) Microsoft Semantic Kernel을 이용한 자연어 처리
; https://www.sysnet.pe.kr/2/0/13345

.NET Framework: 2118. C# - Semantic Kernel의 Prompt chaining 예제
; https://www.sysnet.pe.kr/2/0/13347

.NET Framework: 2119. C# - Semantic Kernel의 "Basic Loading of the Kernel" 예제
; https://www.sysnet.pe.kr/2/0/13348

.NET Framework: 2120. C# - Semantic Kernel의 Skill과 Function 사용 예제
; https://www.sysnet.pe.kr/2/0/13349

.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지
; https://www.sysnet.pe.kr/2/0/13352

.NET Framework: 2123. C# - Semantic Kernel의 ChatGPT 대화 구현
; https://www.sysnet.pe.kr/2/0/13355

.NET Framework: 2124. C# - Semantic Kernel의 Planner 사용 예제
; https://www.sysnet.pe.kr/2/0/13357

.NET Framework: 2125. C# - Semantic Kernel의 Semantic Memory 사용 예제
; https://www.sysnet.pe.kr/2/0/13358




C# - Semantic Kernel의 대화 문맥 유지

아래의 예제가 바로,

Using Context Variables to Build a Chat Experience
; https://github.com/microsoft/semantic-kernel/tree/main/samples/notebooks/dotnet

문맥 유지를 위한 코드를 싣고 있습니다. 예제를 보면 Semantic Function을 코드로 직접 만드는 것 때문에 다소 길어졌는데요, 그냥 이전 예제처럼 임의로 Skill/Function 디렉터리/파일을 만든 후 skprompt.txt 파일에 다음의 내용을 넣어주고,

ChatBot can have a conversation with you about any topic.
It can give explicit instructions or say 'I don't know' if it does not have an answer.

{{$history}}
Human: {{$human_input}}
ChatBot:

config.json은 이렇게 만들어 주면 "Using Context Variables to Build a Chat Experience" 글에서 RegisterSemanticFunction을 이용해 등록한,

KernelConfig kernelConfig = new KernelConfig();
kernelConfig.AddOpenAITextCompletionService("default", "text-davinci-003",  // OpenAI Model name
                                                        apiKey              // OpenAI API Key
);

var kernel = Kernel.Builder
    .WithConfiguration(kernelConfig)
    .Build();

var promptConfig = new PromptTemplateConfig
{
    Completion =
    {
        MaxTokens = 2000,
        Temperature = 0.7,
        TopP = 0.5,
    }
};

var promptTemplate = new PromptTemplate(skPrompt, promptConfig, kernel);
var functionConfig = new SemanticFunctionConfig(promptConfig, promptTemplate);
var chatFunction = kernel.RegisterSemanticFunction("ChatBot", "Chat", functionConfig);

"ChatBot" Skill의 "Chat" 함수와 동일하게 동작합니다. (따라서 취향대로 만드시면 됩니다.)

이후, 대화 내용에 대한 문맥을 유지할 방법이 필요한데요, "Using Context Variables to Build a Chat Experience" 글에서는 간단하게 메모리에 유지하는 방법을 사용합니다. (별도의 저장소를 사용하는 예제는 다른 글에서 다룬다고 합니다.)

이를 위해 SK 라이브러리에서 이미 ContextVariables 타입을 제공하고 있어 그걸 사용하고 있는데요, 다음은 문맥을 유지하기 위해 사용자의 질문을 ContextVariables에 담아 Chat Function을 부르는 코드입니다.

var skill = kernel.ImportSemanticSkillFromDirectory(Directory.GetCurrentDirectory(), "ChatBotSkill");

var context = new ContextVariables();
var history = "";
context.Set("history", history);

var human_input = "Hi, I'm looking for book suggestions";
context.Set("human_input", human_input);

var bot_answer = await kernel.RunAsync(context, skill["Chat"]);
Console.WriteLine(bot_answer);

/* 출력 결과
Hi there! What kind of books are you looking for?
*/

(context.Set에 지정한 "history"와 "human_input"은 skprompt.txt 파일에 지정했던 특수 변수의 이름입니다.)

위의 경우, 1개의 질문과 답변을 했고, 이제 그 상태를 기억하기 위해 단순히 ContextVariables의 history에 지난 대화 내용을 업데이트하기만 하면 됩니다.

history += $"\nHuman: {human_input}\nAssistant: {bot_answer}\n";
context.Update(history);

Console.WriteLine(context);
/* 출력 결과
Human: Hi, I'm looking for book suggestions
Assistant:  Hi there! What kind of books are you looking for?
*/

아마도 실제 대화를 위한 Bot 응용 프로그램을 만든다면 위의 코드는 Loop를 돌면서 구현할 것입니다.

var skill = kernel.ImportSemanticSkillFromDirectory(Directory.GetCurrentDirectory(), "ChatBotSkill");

var context = new ContextVariables();
var history = "";
context.Set("history", history);

while (true)
{
    var human_input = Console.ReadLine();
    if (human_input == "exit")
    {
        break;
    }

    context.Set("human_input", human_input);

    var bot_answer = await kernel.RunAsync(context, skill["Chat"]);
    Console.WriteLine(bot_answer);

    // 지난 대화에 대한 문맥 보관
    history += $"\nHuman: {human_input}\nAssistant: {bot_answer}\n"; 
    context.Set("history", history);
}

"Using Context Variables to Build a Chat Experience" 글의 예제에서는 위와 같은 코드를 쓰지 않고, 비동기 람다로 바꿨으니 그 코드를 따른다면 다음과 같은 식으로 루프를 구현할 수 있습니다.

Func<string, Task> Chat = async (string input) => {
    // Save new message in the context variables
    context.Set("human_input", input);

    // Process the user message and get an answer
    var answer = await kernel.RunAsync(context, skill["Chat"]);
    if (answer.LastException != null)
    {
        Console.WriteLine(answer);
        return;
    }

    // Append the new interaction to the chat history
    history += $"\nHuman: {input}\nMelody: {answer}\n"; context.Set("history", history);

    // Show the response
    Console.WriteLine(context);
};

while (true)
{
    string? human_input = Console.ReadLine();
    if (string.IsNullOrEmpty(human_input) == true || human_input == "exit")
    {
        break;
    }

    await Chat(human_input);
}

어디, 잘 동작하는지, 예제에서 묻는 질문을 해볼까요? ^^

질문: Hi, I'm looking for book suggestions
답변: Hi there! What kind of books are you looking for?

질문: I would like a non-fiction book suggestion about Greece history. Please only list one book.
답변; The History of the Peloponnesian War by Thucydides is an excellent non-fiction book about the history of Greece.

질문: that sounds interesting, what are some of the topics I will learn about?
답변: The History of the Peloponnesian War covers topics such as the causes of the war, the strategies used by both sides, the major battles, and the consequences of the war. It also provides insight into the political and social structures of ancient Greece.

질문: Which topic from the ones you listed do you think most people find interesting?
답변: I think most people find the major battles and the strategies used by both sides to be the most interesting topics.

질문: could you list some more books I could read about the topic(s) you mentioned?
답변: Sure! Here are some other books about the history of Greece and the Peloponnesian War: The Landmark Thucydides: A Comprehensive Guide to the Peloponnesian War by Thucydides, The Peloponnesian War by Donald Kagan, The History of the Ancient World: From the Earliest Accounts to the Fall of Rome by Susan Wise Bauer, and Ancient Greece: A Political, Social, and Cultural History by Sarah B. Pomeroy.


보는 바와 같이 ContextVariables 덕분에 이전 질문의 문맥이 유지되면서 대화를 할 수 있습니다. 물론, 한글도 잘 됩니다. ^^

질문: 안녕하세요, 책 좀 추천해 주세요.
답변: 안녕하세요! 어떤 종류의 책을 찾고 계신가요?

질문: 한국 역사에 대한 소설책을 읽고 싶습니다. 그에 관한 책 한 권만 추천해 주세요.
답변: 한국 역사에 대한 소설책을 읽고 싶으신가요? 제가 추천해 드릴 책은 '나는 이렇게 살았다'입니다. 이 책은 한국 역사에
대한 소설책으로, 역사를 통해 인간의 삶과 사랑을 다루고 있습니다. 여러분이 이 책을 읽고 느낄 수 있는 감정과 생각이 많이
담겨 있습니다. 이 책을 읽으면서 한국 역사를 더 잘 이해할 수 있을 것 같습니다.


(첨부 파일은 이 글의 예제 코드를 포함합니다.)




그나저나, 다른 모델을 사용하려고 했더니,

kernelConfig.AddOpenAITextCompletionService(
    "default",
    "gpt-3.5-turbo", // 또는, "davinci", "gpt-3.5-turbo-0301" 등...
    apiKey       // OpenAI API Key
);

"Error: InvalidRequest: The request is not valid, HTTP status: 400", 또는 "404" 오류가 발생합니다. 이와 관련한 이슈가 있지만,

InvalidRequest: The request is not valid, HTTP status: 400" When running Jupiter notebooks
; https://github.com/microsoft/semantic-kernel/issues/649

해결되었다는 이야기 없이 그냥 "Closed"로 바뀐 상태입니다. 암튼... 현재는 Preview 버전이라 그런지 뭔가 요상한 점들이 있으니 그걸 감안해서 테스트하시면 되겠습니다. (gpt 모델의 경우 AddOpenAIChatCompletionService로 사용해야 합니다.)

참고로, 지원되는 다른 모델이 있긴 합니다. ChatBot 서비스로는 사용할 수 없지만, "text-embedding-ada-002" (Word Embedding, "OpenAI가 자연어처리 및 이미지생성 AI의 '임베딩 모델'을 쇄신, 성능대비 코스트가 99.8%나 저렴하게")를 사용하면 다음과 같은 출력을 얻습니다. ^^;

질문: 안녕하세요, 책 좀 추천해 주세요.
답변:  ( 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0, 0 0 0 0 0 1 0 0, 0 0 0, 0 0 0, 0 0, 0 0, 0 0 0, 0 0 0 0,0 0 0, 0 0 0,0,0 0 0 0, 0 0 0 0, 0 0 0,0,0 0, 0,0,0,,0,0,0,0 1 0, 0,0,0,0,0,0, 0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,0,0, 0,0,0, 0,0,0,0,0,, 0,0,0, 0,0,0,0,0,,0,0,0,0, 1 0,0,0,0,0,0,0,0, 0,0,0,0, 0,0,0, 0,0,0, 0 1 0,0,0,0,0,,, 0,0,0,0, 0,0,0, 0,0, 0,0,0, 0,0, 0,0, 0,0, 0,0,0, 0,0, 0,0,1, 0,0, 0,0, 0,0,0,0, 0,0,0, 0,0, 1,0,0, 0,0, 0,0,0, 0,0,1,0,0,0,0,1, 0,0,0, 0,0,0,1,1,0, 0,0,0,0, 1,0,0,1,1,0, 1,0,0,0,0,0, 1,0,0,0,0,1,0,1,1, 1,0,0,0,1,1, 1,0,1,1,0, 0,0,0,0,0, 0,0, 1, 0,0,1,0,1,1,1, 0,0,0,1,0,1,1, 0,0,0,0, 0,0, 1,0,1,0, 1,1,1,0, 0,0,0, 1,0,0,0,1,1, 1,0,1,1,1, 0,0,0,0, 0,0,0,1,1,1,1,1,1,1,1, 1,0,0,0,0, 1,0,1,1,1,1, 0,0,0,0, 1,1,0,1,0,1,1, 1,0,0,0, 0,0,0,1,,1,0,0,0,1,1,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,1,0,0,0,1,0,0,0,1,1,1,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,1,0,1,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,1,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1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 5/17/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13357정성태5/16/20233576.NET Framework: 2124. C# - Semantic Kernel의 Planner 사용 예제파일 다운로드1
13356정성태5/15/20233903DDK: 10. Device Driver 테스트 설치 관련 오류 (Code 37, Code 31) 및 인증서 관련 정리
13355정성태5/12/20233837.NET Framework: 2123. C# - Semantic Kernel의 ChatGPT 대화 구현 [1]파일 다운로드1
13354정성태5/12/20234096.NET Framework: 2122. C# - "Use Unicode UTF-8 for worldwide language support" 설정을 한 경우, 한글 입력이 '\0' 문자로 처리
13352정성태5/12/20233707.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지파일 다운로드1
13351정성태5/11/20234211VS.NET IDE: 185. Visual Studio - 원격 Docker container 내에 실행 중인 응용 프로그램에 대한 디버깅 [1]
13350정성태5/11/20233481오류 유형: 859. Windows Date and Time - Unable to continue. You do not have permission to perform this task
13349정성태5/11/20233794.NET Framework: 2120. C# - Semantic Kernel의 Skill과 Function 사용 예제파일 다운로드1
13348정성태5/10/20233690.NET Framework: 2119. C# - Semantic Kernel의 "Basic Loading of the Kernel" 예제
13347정성태5/10/20234083.NET Framework: 2118. C# - Semantic Kernel의 Prompt chaining 예제파일 다운로드1
13346정성태5/10/20233914오류 유형: 858. RDP 원격 환경과 로컬 PC 간의 Ctrl+C, Ctrl+V 복사가 안 되는 문제
13345정성태5/9/20235314.NET Framework: 2117. C# - (OpenAI 기반의) Microsoft Semantic Kernel을 이용한 자연어 처리 [1]파일 다운로드1
13344정성태5/9/20236493.NET Framework: 2116. C# - OpenAI API 사용 - 지원 모델 목록 [1]파일 다운로드1
13343정성태5/9/20234366디버깅 기술: 192. Windbg - Hyper-V VM으로 이더넷 원격 디버깅 연결하는 방법
13342정성태5/8/20234274.NET Framework: 2115. System.Text.Json의 역직렬화 시 필드/속성 주의
13341정성태5/8/20234008닷넷: 2114. C# 12 - 모든 형식의 별칭(Using aliases for any type)
13340정성태5/8/20234081오류 유형: 857. Microsoft.Data.SqlClient.SqlException - 0x80131904
13339정성태5/6/20234749닷넷: 2113. C# 12 - 기본 생성자(Primary Constructors)
13338정성태5/6/20234265닷넷: 2112. C# 12 - 기본 람다 매개 변수파일 다운로드1
13337정성태5/5/20234770Linux: 59. dockerfile - docker exec로 container에 접속 시 자동으로 실행되는 코드 적용
13336정성태5/4/20234579.NET Framework: 2111. C# - 바이너리 출력 디렉터리와 연관된 csproj 설정
13335정성태4/30/20234680.NET Framework: 2110. C# - FFmpeg.AutoGen 라이브러리를 이용한 기본 프로젝트 구성 - Windows Forms파일 다운로드1
13334정성태4/29/20234313Windows: 250. Win32 C/C++ - Modal 메시지 루프 내에서 SetWindowsHookEx를 이용한 Thread 메시지 처리 방법
13333정성태4/28/20233755Windows: 249. Win32 C/C++ - 대화창 템플릿을 런타임에 코딩해서 사용파일 다운로드1
13332정성태4/27/20233856Windows: 248. Win32 C/C++ - 대화창을 위한 메시지 루프 사용자 정의파일 다운로드1
13331정성태4/27/20233887오류 유형: 856. dockerfile - 구 버전의 .NET Core 이미지 사용 시 apt update 오류
1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...