Microsoft MVP성태의 닷넷 이야기
.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지 [링크 복사], [링크+제목 복사]
조회: 3698
글쓴 사람
정성태 (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)
13381정성태6/25/20233867오류 유형: 869. Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
13380정성태6/24/20233300스크립트: 52. 파이썬 3.x에서의 동적 함수 추가
13379정성태6/23/20233308스크립트: 51. 파이썬 2.x에서의 동적 함수 추가
13378정성태6/22/20233205오류 유형: 868. docker - build 시 "CANCELED ..." 뜨는 문제
13377정성태6/22/20237077오류 유형: 867. 파이썬 mysqlclient 2.2.x 설치 시 "Specify MYSQLCLIENT_CFLAGS and MYSQLCLIENT_LDFLAGS env vars manually" 오류
13376정성태6/21/20233427.NET Framework: 2129. C# - Polly를 이용한 클라이언트 측의 요청 재시도파일 다운로드1
13375정성태6/20/20233107스크립트: 50. Transformers (신경망 언어모델 라이브러리) 강좌 - 2장 코드 실행 결과
13374정성태6/20/20233213오류 유형: 866. 파이썬 - <class 'AttributeError'> module 'flask.json' has no attribute 'JSONEncoder'
13373정성태6/19/20234530오류 유형: 865. 파이썬 - pymssql 설치 관련 오류 정리
13372정성태6/15/20233209개발 환경 구성: 682. SQL Server TLS 통신을 위해 사용되는 키 길이 확인 방법
13371정성태6/15/20233243개발 환경 구성: 681. openssl - 인증서 버전(V1 / V3)
13370정성태6/14/20233412개발 환경 구성: 680. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 - TLS 1.2 지원
13369정성태6/13/20233235개발 환경 구성: 679. PyCharm(을 비롯해 JetBrains에 속한 여타) IDE에서 내부 Window들의 탭이 없어진 경우
13368정성태6/13/20233368개발 환경 구성: 678. openssl로 생성한 인증서를 SQL Server의 암호화 인증서로 설정하는 방법
13367정성태6/10/20233502오류 유형: 864. openssl로 만든 pfx 인증서를 Windows Server 2016 이하에서 등록 시 "The password you entered is incorrect" 오류 발생
13366정성태6/10/20233281.NET Framework: 2128. C# - 윈도우 시스템에서 지원하는 암호화 목록(Cipher Suites) 나열파일 다운로드1
13365정성태6/8/20233020오류 유형: 863. MODIFY FILE encountered operating system error 112(failed to retrieve text for this error. Reason: 15105)
13364정성태6/8/20233813.NET Framework: 2127. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 [1]
13363정성태6/7/20233376스크립트: 49. 파이썬 - "Transformers (신경망 언어모델 라이브러리) 강좌" - 1장 2절 코드 실행 결과
13362정성태6/1/20233320.NET Framework: 2126. C# - 서버 측의 요청 제어 (Microsoft.AspNetCore.RateLimiting)파일 다운로드1
13361정성태5/31/20233744오류 유형: 862. Facebook - ASP.NET/WebClient 사용 시 graph.facebook.com/me 호출에 대해 403 Forbidden 오류
13360정성태5/31/20233133오류 유형: 861. WSL/docker - failed to start shim: start failed: io.containerd.runc.v2: create new shim socket
13359정성태5/19/20233464오류 유형: 860. Docker Desktop - k8s 초기화 무한 반복한다면?
13358정성태5/17/20233792.NET Framework: 2125. C# - Semantic Kernel의 Semantic Memory 사용 예제 [1]파일 다운로드1
13357정성태5/16/20233573.NET Framework: 2124. C# - Semantic Kernel의 Planner 사용 예제파일 다운로드1
13356정성태5/15/20233896DDK: 10. Device Driver 테스트 설치 관련 오류 (Code 37, Code 31) 및 인증서 관련 정리
1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...