Microsoft MVP성태의 닷넷 이야기
.NET Framework: 2124. C# - Semantic Kernel의 Planner 사용 예제 [링크 복사], [링크+제목 복사]
조회: 3573
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

(시리즈 글이 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의 Planner 사용 예제

Semantic Kernel의 구성 요소는 다음의 그림에서 잘 확인할 수 있습니다.

[출처: https://devblogs.microsoft.com/semantic-kernel/hello-world/]
sk_planner_1.png

ASK는 Kernel에 보내는 요청이고, Kernel은 이미 그동안 우리가 만든 코드의 시작에 해당하는 타입이었습니다.

var kernel = Kernel.Builder.Build(); // C# - Semantic Kernel의 "Basic Loading of the Kernel" 예제

그림에서 S는 Skill인데 이것도 "C# - Semantic Kernel의 Skill과 Function 사용 예제" 글을 통해 이미 다뤘습니다.

나머지는 M(Memory), C(Connector)와 오늘의 주제인 Planner인데요, 이에 대한 예제를 다음의 글에서 다루고 있습니다.

Introduction to the Planner
; https://github.com/microsoft/semantic-kernel/blob/main/samples/notebooks/dotnet/05-using-the-planner.ipynb

코드는 기존 예제와 동일하게 Kernel을 준비하는 것으로 시작하고,

KernelConfig kernelConfig = new KernelConfig();
kernelConfig.AddOpenAITextCompletionService("default", "text-davinci-003", apiKey);

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

그다음 planner를 만들고 Kernel에 Skill/Function을 담고 있습니다.

var planner = new SequentialPlanner(kernel);

var skillsDirectory = Path.Combine(Directory.GetCurrentDirectory(), "skills");
kernel.ImportSemanticSkillFromDirectory(skillsDirectory, "SummarizeSkill");
kernel.ImportSemanticSkillFromDirectory(skillsDirectory, "WriterSkill");

/*
SummarizeSkill
    Function: MakeAbstractReadable, Notegen, Summarize, Topics

WriterSkill
    Function: Acronym, AcronymGenerator, AcronymReverse, Brainstorm, EmailGen, EmailTo, 
              EnglishImprover, NovelChapter, NovelChapterWithNotes, NovelOutline, Rewrite, 
              ShortPoem, StoryGen, TellMeMore, Translate, TwoSentenceSummary
*/

해당 스킬들은 github에 예제로 제공되고 있는 것들인데, clone 시킨 디렉터리에서 복사할 수 있습니다. 프로젝트에 파일로 추가하는 경우 각각 CopyToOutputDirectory 설정을 해야 하는데, 일일이 파일 하나씩 하는 것은 번잡하므로 와일드카드 문자열을 사용해 "skills\**\*"로 지정하면 skills 디렉터리 하위에 있는 모든 디렉터리 및 파일들을 복사하게 됩니다. 아래는 csproj에 그 설정을 추가한 것입니다.

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net7.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.SemanticKernel" Version="0.13.277.1-preview" />
  </ItemGroup>

  <ItemGroup>
    <None Update="skills\**\*">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
  </ItemGroup>

</Project>

그다음 코드에서는 planner를 이용해 사용자의 요청에 기반한 Planner를 생성하는데요,

var ask = "Tomorrow is Valentine's day. I need to come up with a few date ideas and e-mail them to my significant other.";
var originalPlan = await planner.CreatePlanAsync(ask);

Console.WriteLine("Original plan:\n");
Console.WriteLine(JsonSerializer.Serialize(originalPlan, new JsonSerializerOptions { WriteIndented = true }));

재미있는 건, 어떤 스킬을 사용하라고 지정하지도 않았다는 점입니다. 즉, 단순히 현재 Kernel에 포함된 Skill/Function을 이용해 사용자의 ASK를 만족하는 Planner를 구성하는데요, 아래는 originalPlan의 내부 구조를 JSON 포맷으로 보여줍니다.

Original plan:

{
  "state": [
    {
      "Key": "INPUT",
      "Value": ""
    }
  ],
  "steps": [
    {
      "state": [
        {
          "Key": "INPUT",
          "Value": ""
        }
      ],
      "steps": [],
      "named_parameters": [
        {
          "Key": "INPUT",
          "Value": "Valentine\u0027s day date ideas"
        }
      ],
      "named_outputs": [
        {
          "Key": "DATE_IDEAS",
          "Value": ""
        },
        {
          "Key": "INPUT",
          "Value": ""
        }
      ],
      "next_step_index": 0,
      "name": "Brainstorm",
      "skill_name": "WriterSkill",
      "description": "Given a goal or topic description generate a list of ideas"
    },
    {
      "state": [
        {
          "Key": "INPUT",
          "Value": ""
        }
      ],
      "steps": [],
      "named_parameters": [
        {
          "Key": "INPUT",
          "Value": ""
        }
      ],
      "named_outputs": [
        {
          "Key": "INPUT",
          "Value": ""
        }
      ],
      "next_step_index": 0,
      "name": "",
      "skill_name": "Microsoft.SemanticKernel.Orchestration.Plan",
      "description": ""
    },
    {
      "state": [
        {
          "Key": "INPUT",
          "Value": ""
        }
      ],
      "steps": [],
      "named_parameters": [
        {
          "Key": "sender",
          "Value": "Me"
        },
        {
          "Key": "to",
          "Value": "My Significant Other"
        },
        {
          "Key": "INPUT",
          "Value": "$DATE_IDEA_1;$DATE_IDEA_2;$DATE_IDEA_3"
        }
      ],
      "named_outputs": [
        {
          "Key": "INPUT",
          "Value": ""
        }
      ],
      "next_step_index": 0,
      "name": "EmailTo",
      "skill_name": "WriterSkill",
      "description": "Turn bullet points into an email to someone, using a polite tone"
    }
  ],
  "named_parameters": [
    {
      "Key": "INPUT",
      "Value": ""
    }
  ],
  "named_outputs": [
    {
      "Key": "INPUT",
      "Value": ""
    }
  ],
  "next_step_index": 0,
  "name": "Tomorrow is Valentine\u0027s day. I need to come up with a few date ideas and e-mail them to my significant other.",
  "skill_name": "Microsoft.SemanticKernel.Orchestration.Plan",
  "description": "Tomorrow is Valentine\u0027s day. I need to come up with a few date ideas and e-mail them to my significant other."
}

어찌 보면, 저것 하나가 새롭게 "Skill"이 된 것입니다. 결국 이러한 Planner대로 실행을 하면,

var originalPlanResult = await kernel.RunAsync(originalPlan);

Console.WriteLine("Original Plan results:\n");
Console.WriteLine(Utils.WordWrap(originalPlanResult.Result, 80));

다음과 같은 출력을 볼 수 있습니다.

Original Plan results:

Dear My Significant Other,

I wanted to take a moment to thank you for being my
significant other. You have been a source of joy and comfort in my life, and I
am so grateful for your presence. I am so lucky to have you in my life.

Thanks,
Me

그러니까, 사용자의 "Tomorrow is Valentine's day. I need to come up with a few date ideas and e-mail them to my significant other." 입력을 바탕으로, 내부에 구성한 Skill/Function을 활용해 위의 출력을 만들어 낸 것입니다.




그럼, 이 상태에서 Shakespeare 화법으로 말하라는 Skill/Function도 (위에서 만든 Kernel에) 추가해 볼까요? ^^

string skPrompt = """
{{$input}}

Rewrite the above in the style of Shakespeare.
""";
var shakespeareFunction = kernel.CreateSemanticFunction(skPrompt, "shakespeare", "ShakespeareSkill", maxTokens: 2000, temperature: 0.2, topP: 0.5);

이번 Skill/Function은 ImportSemanticSkillFromDirectory가 아닌 동적으로 CreateSemanticFunction을 이용해 추가했습니다. 이러한 변화를 반영해 Planner를 다시 생성하고,

var ask = @"Tomorrow is Valentine's day. I need to come up with a few date ideas.
She likes Shakespeare so write using his style. E-mail these ideas to my significant other";
var newPlan = await planner.CreatePlanAsync(ask);

Planner의 내부 변화를 확인합니다.

Console.WriteLine("Updated plan:\n");
Console.WriteLine(JsonSerializer.Serialize(newPlan, new JsonSerializerOptions { WriteIndented = true }));

Updated plan:

{
  "state": [
    {
      "Key": "INPUT",
      "Value": ""
    }
  ],
  "steps": [
    {
      "state": [
        {
          "Key": "INPUT",
          "Value": ""
        }
      ],
      "steps": [],
      "named_parameters": [
        {
          "Key": "INPUT",
          "Value": "Date ideas for Valentine\u0027s day"
        }
      ],
      "named_outputs": [
        {
          "Key": "INPUT",
          "Value": ""
        },
        {
          "Key": "DATE_IDEAS",
          "Value": ""
        }
      ],
      "next_step_index": 0,
      "name": "Brainstorm",
      "skill_name": "WriterSkill",
      "description": "Given a goal or topic description generate a list of ideas"
    },
    {
      "state": [
        {
          "Key": "INPUT",
          "Value": ""
        }
      ],
      "steps": [],
      "named_parameters": [
        {
          "Key": "INPUT",
          "Value": "$DATE_IDEAS"
        }
      ],
      "named_outputs": [
        {
          "Key": "INPUT",
          "Value": ""
        },
        {
          "Key": "SHAKESPEARE_IDEAS",
          "Value": ""
        }
      ],
      "next_step_index": 0,
      "name": "shakespeare",
      "skill_name": "ShakespeareSkill",
      "description": "Generic function, unknown purpose"
    },
    {
      "state": [
        {
          "Key": "INPUT",
          "Value": ""
        }
      ],
      "steps": [],
      "named_parameters": [
        {
          "Key": "sender",
          "Value": "Myself"
        },
        {
          "Key": "INPUT",
          "Value": "$SHAKESPEARE_IDEAS"
        },
        {
          "Key": "to",
          "Value": "My Significant Other"
        }
      ],
      "named_outputs": [
        {
          "Key": "INPUT",
          "Value": ""
        }
      ],
      "next_step_index": 0,
      "name": "EmailTo",
      "skill_name": "WriterSkill",
      "description": "Turn bullet points into an email to someone, using a polite tone"
    }
  ],
  "named_parameters": [
    {
      "Key": "INPUT",
      "Value": ""
    }
  ],
  "named_outputs": [
    {
      "Key": "INPUT",
      "Value": ""
    }
  ],
  "next_step_index": 0,
  "name": "Tomorrow is Valentine\u0027s day. I need to come up with a few date ideas.\r\nShe likes Shakespeare so write using his style. E-mail these ideas to my significant other",
  "skill_name": "Microsoft.SemanticKernel.Orchestration.Plan",
  "description": "Tomorrow is Valentine\u0027s day. I need to come up with a few date ideas.\r\nShe likes Shakespeare so write using his style. E-mail these ideas to my significant other"
}

이에 따라 텍스트를 생성하면,

var newPlanResult = await kernel.RunAsync(newPlan);
Console.WriteLine("New Plan results:\n");
Console.WriteLine(newPlanResult.Result);

이런 출력을 확인할 수 있습니다.

New Plan results:

Dear My Significant Other,

I hope you're doing well. I wanted to suggest some activities that we could do together.

We could make a delicious feast together. We could take a romantic walk. We could watch a romantic movie. We could attend a local event. We could take a dancing class. We could visit a museum. We could go to a spa. We could go stargazing. We could go to a concert. We could have a picnic.

I look forward to hearing your thoughts.

Thanks,
Myself

음... 잘하면 시라노 같은 친구도 만들 수 있겠군요. ^^

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




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







[최초 등록일: ]
[최종 수정일: 5/16/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)
13382정성태6/25/20233475.NET Framework: 2130. C# - Win32 API를 이용한 윈도우 계정 정보 (예: 마지막 로그온 시간)파일 다운로드1
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/20233206오류 유형: 868. docker - build 시 "CANCELED ..." 뜨는 문제
13377정성태6/22/20237078오류 유형: 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/20233413개발 환경 구성: 680. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 - TLS 1.2 지원
13369정성태6/13/20233236개발 환경 구성: 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
1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...