Microsoft MVP성태의 닷넷 이야기
.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지 [링크 복사], [링크+제목 복사]
조회: 3699
글쓴 사람
정성태 (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)
13407정성태9/4/20233590닷넷: 2139. C# - ParallelEnumerable을 이용한 IEnumerable에 대한 병렬 처리
13406정성태9/4/20233559VS.NET IDE: 186. Visual Studio Community 버전의 라이선스
13405정성태9/3/20233985닷넷: 2138. C# - async 메서드 호출 원칙
13404정성태8/29/20233529오류 유형: 876. Windows - 키보드의 등호(=, Equals sign) 키가 눌리지 않는 경우
13403정성태8/21/20233330오류 유형: 875. The following signatures couldn't be verified because the public key is not available: NO_PUBKEY EB3E94ADBE1229CF
13402정성태8/20/20233408닷넷: 2137. ILSpy의 nuget 라이브러리 버전 - ICSharpCode.Decompiler
13401정성태8/19/20233636닷넷: 2136. .NET 5+ 환경에서 P/Invoke의 성능을 높이기 위한 SuppressGCTransition 특성 [1]
13400정성태8/10/20233489오류 유형: 874. 파이썬 - pymssql을 윈도우 환경에서 설치 불가
13399정성태8/9/20233466닷넷: 2135. C# - 지역 변수로 이해하는 메서드 매개변수의 값/참조 전달
13398정성태8/3/20234295스크립트: 55. 파이썬 - pyodbc를 이용한 SQL Server 연결 사용법
13397정성태7/23/20233793닷넷: 2134. C# - 문자열 연결 시 string.Create를 이용한 GC 할당 최소화
13396정성태7/22/20233503스크립트: 54. 파이썬 pystack 소개 - 메모리 덤프로부터 콜 스택 열거
13395정성태7/20/20233416개발 환경 구성: 685. 로컬에서 개발 중인 ASP.NET Core/5+ 웹 사이트에 대해 localhost 이외의 호스트 이름으로 접근하는 방법
13394정성태7/16/20233370오류 유형: 873. Oracle.ManagedDataAccess.Client - 쿼리 수행 시 System.InvalidOperationException
13393정성태7/16/20233557닷넷: 2133. C# - Oracle 데이터베이스의 Sleep 쿼리 실행하는 방법
13392정성태7/16/20233447오류 유형: 872. Oracle - ORA-01031: insufficient privileges
13391정성태7/14/20233491닷넷: 2132. C# - sealed 클래스의 메서드를 callback 호출했을 때 인라인 처리가 될까요?
13390정성태7/12/20233444스크립트: 53. 파이썬 - localhost 호출 시의 hang 현상
13389정성태7/5/20233471개발 환경 구성: 684. IIS Express로 호스팅하는 웹을 WSL 환경에서 접근하는 방법
13388정성태7/3/20233601오류 유형: 871. 윈도우 탐색기에서 열리지 않는 zip 파일 - The Compressed (zipped) Folder '[...].zip' is invalid. [1]파일 다운로드1
13387정성태6/28/20233643오류 유형: 870. _mysql - Commands out of sync; you can't run this command now
13386정성태6/27/20233711Linux: 61. docker - 원격 제어를 위한 TCP 바인딩 추가
13385정성태6/27/20233931Linux: 60. Linux - 외부에서의 접속을 허용하기 위한 TCP 포트 여는 방법
13384정성태6/26/20233657.NET Framework: 2131. C# - Source Generator로 해결하는 enum 박싱 문제파일 다운로드1
13383정성태6/26/20233418개발 환경 구성: 683. GPU 런타임을 사용하는 Colab 노트북 설정
13382정성태6/25/20233476.NET Framework: 2130. C# - Win32 API를 이용한 윈도우 계정 정보 (예: 마지막 로그온 시간)파일 다운로드1
1  2  3  4  5  6  7  8  [9]  10  11  12  13  14  15  ...