Microsoft MVP성태의 닷넷 이야기
.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지 [링크 복사], [링크+제목 복사]
조회: 3704
글쓴 사람
정성태 (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)
13510정성태1/3/20242106닷넷: 2192. C# - 특정 실행 파일이 있는지 확인하는 방법 (Linux)
13509정성태1/3/20242146오류 유형: 887. .NET Core 2 이하의 프로젝트에서 System.Runtime.CompilerServices.Unsafe doesn't support netcoreapp2.0.
13508정성태1/3/20242168오류 유형: 886. ORA-28000: the account is locked
13507정성태1/2/20242830닷넷: 2191. C# - IPGlobalProperties를 이용해 netstat처럼 사용 중인 Socket 목록 구하는 방법파일 다운로드1
13506정성태12/29/20232396닷넷: 2190. C# - 닷넷 코어/5+에서 달라지는 System.Text.Encoding 지원
13505정성태12/27/20232951닷넷: 2189. C# - WebSocket 클라이언트를 닷넷으로 구현하는 예제 (System.Net.WebSockets)파일 다운로드1
13504정성태12/27/20232526닷넷: 2188. C# - ASP.NET Core SignalR로 구현하는 채팅 서비스 예제파일 다운로드1
13503정성태12/27/20232387Linux: 67. WSL 환경 + mlocate(locate) 도구의 /mnt 디렉터리 검색 문제
13502정성태12/26/20232489닷넷: 2187. C# - 다른 프로세스의 환경변수 읽는 예제파일 다운로드1
13501정성태12/25/20232299개발 환경 구성: 700. WSL + uwsgi - IPv6로 바인딩하는 방법
13500정성태12/24/20232365디버깅 기술: 194. Windbg - x64 가상 주소를 물리 주소로 변환
13498정성태12/23/20233054닷넷: 2186. 한국투자증권 KIS Developers OpenAPI의 C# 래퍼 버전 - eFriendOpenAPI NuGet 패키지
13497정성태12/22/20232456오류 유형: 885. Visual Studiio - error : Could not connect to the remote system. Please verify your connection settings, and that your machine is on the network and reachable.
13496정성태12/21/20232436Linux: 66. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (gdb)
13495정성태12/20/20232406Linux: 65. clang++로 공유 라이브러리의 -static 옵션 빌드가 가능할까요?
13494정성태12/20/20232538Linux: 64. Linux 응용 프로그램의 (C++) so 의존성 줄이기(ReleaseMinDependency) - 두 번째 이야기
13493정성태12/19/20232631닷넷: 2185. C# - object를 QueryString으로 직렬화하는 방법
13492정성태12/19/20232315개발 환경 구성: 699. WSL에 nopCommerce 예제 구성
13491정성태12/19/20232262Linux: 63. 리눅스 - 다중 그룹 또는 사용자를 리소스에 권한 부여
13490정성태12/19/20232389개발 환경 구성: 698. Golang - GLIBC 의존을 없애는 정적 빌드 방법
13489정성태12/19/20232172개발 환경 구성: 697. GoLand에서 ldflags 지정 방법
13488정성태12/18/20232102오류 유형: 884. HTTP 500.0 - 명령행에서 실행한 ASP.NET Core 응용 프로그램을 실행하는 방법
13487정성태12/16/20232406개발 환경 구성: 696. C# - 리눅스용 AOT 빌드를 docker에서 수행 [1]
13486정성태12/15/20232220개발 환경 구성: 695. Nuget config 파일에 값 설정/삭제 방법
13485정성태12/15/20232099오류 유형: 883. dotnet build/restore - error : Root element is missing
13484정성태12/14/20232175개발 환경 구성: 694. Windows 디렉터리 경로를 WSL의 /mnt 포맷으로 구하는 방법
1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...