Microsoft MVP성태의 닷넷 이야기
.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지 [링크 복사], [링크+제목 복사]
조회: 3702
글쓴 사람
정성태 (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)
13433정성태11/1/20232397스크립트: 61. 파이썬 - 함수 오버로딩 미지원
13432정성태10/31/20232482오류 유형: 878. 탐색기의 WSL 디렉터리 접근 시 "Attempt to access invalid address." 오류 발생
13431정성태10/31/20232805스크립트: 60. 파이썬 - 비동기 FastAPI 앱을 gunicorn으로 호스팅
13430정성태10/30/20232694닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법
13429정성태10/27/20232976닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제파일 다운로드1
13428정성태10/25/20233054닷넷: 2151. C# 12 - ref readonly 매개변수
13427정성태10/18/20233251닷넷: 2150. C# 12 - 정적 문맥에서 인스턴스 멤버에 대한 nameof 접근 허용(Allow nameof to always access instance members from static context)
13426정성태10/13/20233410스크립트: 59. 파이썬 - 비동기 호출 함수(run_until_complete, run_in_executor, create_task, run_in_threadpool)
13425정성태10/11/20233197닷넷: 2149. C# - PLinq의 Partitioner<T>를 이용한 사용자 정의 분할파일 다운로드1
13423정성태10/6/20233175스크립트: 58. 파이썬 - async/await 기본 사용법
13422정성태10/5/20233321닷넷: 2148. C# - async 유무에 따른 awaitable 메서드의 병렬 및 예외 처리
13421정성태10/4/20233398닷넷: 2147. C# - 비동기 메서드의 async 예약어 유무에 따른 차이
13420정성태9/26/20235588스크립트: 57. 파이썬 - UnboundLocalError: cannot access local variable '...' where it is not associated with a value
13419정성태9/25/20233223스크립트: 56. 파이썬 - RuntimeError: dictionary changed size during iteration
13418정성태9/25/20233929닷넷: 2146. C# - ConcurrentDictionary 자료 구조의 동기화 방식
13417정성태9/19/20233455닷넷: 2145. C# - 제네릭의 형식 매개변수에 속한 (매개변수를 가진) 생성자를 호출하는 방법
13416정성태9/19/20233259오류 유형: 877. redis-py - MISCONF Redis is configured to save RDB snapshots, ...
13415정성태9/18/20233757닷넷: 2144. C# 12 - 컬렉션 식(Collection Expressions)
13414정성태9/16/20233516디버깅 기술: 193. Windbg - ThreadStatic 필드 값을 조사하는 방법
13413정성태9/14/20233711닷넷: 2143. C# - 시스템 Time Zone 변경 시 이벤트 알림을 받는 방법
13412정성태9/14/20236993닷넷: 2142. C# 12 - 인라인 배열(Inline Arrays) [1]
13411정성태9/12/20233494Windows: 252. 권한 상승 전/후 따로 관리되는 공유 네트워크 드라이브 정보
13410정성태9/11/20235033닷넷: 2141. C# 12 - Interceptor (컴파일 시에 메서드 호출 재작성) [1]
13409정성태9/8/20233889닷넷: 2140. C# - Win32 API를 이용한 모니터 전원 끄기
13408정성태9/5/20233845Windows: 251. 임의로 만든 EXE 파일을 포함한 ZIP 파일의 압축을 해제할 때 Windows Defender에 의해 삭제되는 경우
13407정성태9/4/20233590닷넷: 2139. C# - ParallelEnumerable을 이용한 IEnumerable에 대한 병렬 처리
1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...