Microsoft MVP성태의 닷넷 이야기
.NET Framework: 2120. C# - Semantic Kernel의 Skill과 Function 사용 예제 [링크 복사], [링크+제목 복사],
조회: 12090
글쓴 사람
정성태 (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의 Skill과 Function 사용 예제

지난 글에서는,

C# - (OpenAI 기반의) Microsoft Semantic Kernel을 이용한 자연어 처리
; https://www.sysnet.pe.kr/2/0/13345

코드상에서 SemanticFunction을 만들어봤는데요, 이때 사용한 CreateSemanticFunction 함수의 원형을 보면,

public static ISKFunction CreateSemanticFunction(
    this IKernel kernel,
    string promptTemplate,
    string? functionName = null,
    string skillName = "",
    string? description = null,
    int maxTokens = 256,
    double temperature = 0,
    double topP = 0,
    double presencePenalty = 0,
    double frequencyPenalty = 0,
    IEnumerable<string>? stopSequences = null);

반환값이 ISKFunction으로 나오고, 인자로는 promptTemplate과 functionName, skillName 등을 볼 수 있습니다. 그러니까, SemanticFunction은 (Semantic Kernel의 구성요소 중 하나인) Skill과 그것에 속하는 Function을 동적으로 만드는 메서드였던 것입니다.

다시 그때의 코드를 곱씹어 볼까요?

var prompt = @"{{$input}}

One line TLDR with the fewest words.";

var summarize = kernel.CreateSemanticFunction(prompt);

prompt 문자열이 promptTemplate이었고, CreateSemanticFunction은 skillName과 functionName을 단순히 공백으로 설정한 Function을 만든 것입니다.

재미있는 것은, Function과 그것의 묶음인 Skill 구성은 디렉터리와 파일로 구성하는 것도 가능합니다. 이에 대한 예제를 다음의 글 3개에서 볼 수 있는데요,

samples/notebooks/dotnet/00-getting-started.ipynb
; https://github.com/microsoft/semantic-kernel/blob/main/samples/notebooks/dotnet/00-getting-started.ipynb

How to run a semantic skills from file
; https://github.com/microsoft/semantic-kernel/blob/main/samples/notebooks/dotnet/02-running-prompts-from-file.ipynb

Running Semantic Functions Inline
; https://github.com/microsoft/semantic-kernel/blob/main/samples/notebooks/dotnet/03-semantic-function-inline.ipynb

예제에서 소개한 대로 우리도 직접 해볼까요? ^^

이를 위해 Console 프로젝트에 "FunSkill" 디렉터리를 추가하고, 그 하위에 다시 "Joke" 디렉터리를 만든 다음 skprompt.txt라는 파일명으로 다음의 내용을 채워줍니다.

WRITE EXACTLY ONE JOKE or HUMOROUS STORY ABOUT THE TOPIC BELOW

JOKE MUST BE:
- G RATED
- WORKPLACE/FAMILY SAFE
NO SEXISM, RACISM OR OTHER BIAS/BIGOTRY

BE CREATIVE AND FUNNY. I WANT TO LAUGH.
{{$style}}
+++++

{{$input}}
+++++

이렇게 만들어준 (이름이 고정인) skprompt.txt 파일이 바로 CreateSemanticFunction 메서드의 인자로 넘긴 "promptTemplate"에 해당합니다. 그리고 예상할 수 있듯이 "{{$Input}}"에는 kernel.RunAsync로 전달되는 문장이 대체됩니다.

이 상태에서 "FunSkill" 디렉터리는 "Skill" 이름이 되고, 그 하위에 있는 "Joke" 디렉터리는 "Function" 이름이 됩니다. 여기까지 작업하면 솔루션 탐색기에서 다음과 같이 구성됐을 것입니다.

skill_directory_1.png

저 디렉터리/파일 구조가 빌드 후 출력이 함께 되도록 CopyToOutputDirectory도 설정해야 합니다.

<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>
    <Folder Include="FunSkill\Joke\" />
  </ItemGroup>

  <ItemGroup>
    <None Update="FunSkill\Joke\skprompt.txt">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
  </ItemGroup>

</Project>

자, 그럼 준비는 모두 끝났습니다. 이제 다음과 같이 코드를 작성하면 특정 문장에 대해 "G 등급", ... "창의적이고 재미있는..." 농담을 만들어 줍니다.

using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.KernelExtensions;

namespace ConsoleApp1;

internal class Program
{
    // Install-Package Microsoft.SemanticKernel -Pre
    private static async Task<int> Main(string[] args)
    {
        (string apiKey, _) = GetKeyInfo(@"d:\settings\openai_key.txt");

        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 skill = kernel.ImportSemanticSkillFromDirectory(Directory.GetCurrentDirectory(), "FunSkill");

        var result = await kernel.RunAsync("time travel to dinosaur age", skill["Joke"]);
        Console.WriteLine(result);

        return 0;
    }

    private static (string apiKey, string orgName) GetKeyInfo(string filePath)
    {
        string[] keyInfo = File.ReadLines(filePath).ToArray();
        return (keyInfo[0], keyInfo.Length >= 1 ? keyInfo[1] : "");
    }
}

/* 출력 결과
A time traveler went back to the dinosaur age and was amazed by the size of the creatures. He asked one of the dinosaurs, "How do you manage to get around with such short legs?"

The dinosaur replied, "It's easy, I just take my time!"
*/

대충... 느낌이 오시죠? ^^ Semantic Kernel의 github repo에는 이러한 템플릿 Skill 예제를 몇 개 담고 있습니다.

CalendarSkill
    Function: AssistantShowCalendarEvents

ChatSkill
    Function: Chat, ChatFilter, ChatGPT, ChatUser, ChatV2

ChildrensBookSkill
    Function: BookIdeas, CreateBook

ClassificationSkill
    Function: Importance, Question

CodingSkill
    Function: Code, CodePython, CommandLinePython, DOSScript, EmailSearch, Entity

FunSkill
    Function: Execuse, Joke, Limerick

IntentDetectionSkill
    Function: AssistantIntent

MiscSkill
    Function: Continue, ElementAtIndex

QASkill
    Function: AssistantResults, ContextQuery, Form, GitHubMemoryQuery, QNA, Question

SummarizeSkill
    Function: MakeAbstractReadable, Notegen, Summarize, Topics

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

위의 목록을 보고 있으면... 우리가 그동안 프로그래밍에서 만들었던 함수의 개념을, 그대로 "자연어 문장"에 대해 수행할 수 있는 함수로 표현한 듯한 인상을 받습니다.

요즘 ChatGPT에게 던지는 프롬프트의 중요성이 부각되고 있는데요, 결국 Skill/Function은 재사용 가능한 프롬프트 서식이라고 봐도 무방하겠습니다.




CreateSemanticFunction의 나머지 인자는 개별 Function에 해당하는 skprompt.txt 파일과 동일한 위치에 만들어 둔 config.json 파일을 추가해 설정할 수 있습니다. 아래는 FuncSkill/Joke에 있는 예제 json 파일입니다.

{
  "schema": 1,
  "description": "Generate a funny joke",
  "type": "completion",
  "completion": {
    "max_tokens": 1000,
    "temperature": 0.9,
    "top_p": 0.0,
    "presence_penalty": 0.0,
    "frequency_penalty": 0.0
  },
  "input": {
    "parameters": [
      {
        "name": "input",
        "description": "Joke subject",
        "defaultValue": ""
      }
    ]
  }
}

이 파일은 반드시 필요한 것은 아닌데, 내부의 옵션에 대해서는 OpenAI의 제어값에 해당하므로 필요한 경우라면 당연히 설정을 해야 합니다. (개별 의미는 차차 익숙해지는 대로 다뤄보겠습니다.)

마지막으로, "Running Semantic Functions Inline" 에제를 보면, 사실 CreateSemanticFunction은 PromptTemplateConfig, PromptTemplate, SemanticFunctionConfig, RegisterSemanticFunction 조합을 하나로 제공하는 도우미 메서드에 해당한다는 것을 알 수 있습니다.

이 정도면, 얼핏 Semantic Kernel의 기본 사용법이 제법 손에 잡히는 것 같죠?!!! ^^

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




이 글과 관련해서 다음의 문서도 읽어보시고,

Configuring templates
; https://learn.microsoft.com/en-us/semantic-kernel/howto/configuringfunctions

그러고 보니, 지난 글에서 Bing Chat이 내놓은 Semantic Kernel 소개에서,

... 이것은 대규모 언어 모델(Large Language Model, LLM) AI "프롬프트"와 템플릿, 체이닝 및 계획 기능을 제공...

문구 내에 "프롬프트와 템플릿"이 나옵니다. 아마도 저것은 Skill과 Function을 의미하는 듯합니다. ^^




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







[최초 등록일: ]
[최종 수정일: 5/16/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2025-03-28 01시59분
[Deep Research] Model Context Protocol(MCP) 개념 및 이해를 위한 학습 자료
; https://discuss.pytorch.kr/t/deep-research-model-context-protocol-mcp/6594/1

modelcontextprotocol/csharp-sdk
 - The official C# SDK for Model Context Protocol servers and clients, maintained by Microsoft
; https://github.com/modelcontextprotocol/csharp-sdk

Create an MCP Server with .NET and C#
; https://dev.to/mehrandvd/create-an-mcp-server-with-net-and-c-251p

MCP를 달리 생각해 보면, Skill과 Function을 외부 Plug-in 방식으로 분리한 유형으로 봐도 될 듯합니다.
정성태

1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13667정성태7/7/20246622닷넷: 2273. C# - 리눅스 환경에서의 Hyper-V Socket 연동 (AF_VSOCK)파일 다운로드1
13666정성태7/7/20247700Linux: 74. C++ - Vsock 예제 (Hyper-V Socket 연동)파일 다운로드1
13665정성태7/6/20247880Linux: 73. Linux 측의 socat을 이용한 Hyper-V 호스트와의 vsock 테스트파일 다운로드1
13663정성태7/5/20247474닷넷: 2272. C# - Hyper-V Socket 통신(AF_HYPERV, AF_VSOCK)의 VMID Wildcards 유형파일 다운로드1
13662정성태7/4/20247491닷넷: 2271. C# - WSL 2 VM의 VM ID를 알아내는 방법 - Host Compute System API파일 다운로드1
13661정성태7/3/20247413Linux: 72. g++ - 다른 버전의 GLIBC로 소스코드 빌드
13660정성태7/3/20247522오류 유형: 912. Visual C++ - Linux 프로젝트 빌드 오류
13659정성태7/1/20247858개발 환경 구성: 715. Windows - WSL 2 환경의 Docker Desktop 네트워크
13658정성태6/28/20248235개발 환경 구성: 714. WSL 2 인스턴스와 호스트 측의 Hyper-V에 운영 중인 VM과 네트워크 연결을 하는 방법 - 두 번째 이야기
13657정성태6/27/20247911닷넷: 2270. C# - Hyper-V Socket 통신(AF_HYPERV, AF_VSOCK)을 위한 EndPoint 사용자 정의
13656정성태6/27/20248086Windows: 264. WSL 2 VM의 swap 파일 위치
13655정성태6/24/20247850닷넷: 2269. C# - Win32 Resource 포맷 해석파일 다운로드1
13654정성태6/24/20247787오류 유형: 911. shutdown - The entered computer name is not valid or remote shutdown is not supported on the target computer.
13653정성태6/22/20247937닷넷: 2268. C# 코드에서 MAKEINTREOURCE 매크로 처리
13652정성태6/21/20249246닷넷: 2267. C# - Linux 환경에서 (Reflection 없이) DLL AssemblyFileVersion 구하는 방법파일 다운로드2
13651정성태6/19/20248487닷넷: 2266. C# - (Reflection 없이) DLL AssemblyFileVersion 구하는 방법파일 다운로드1
13650정성태6/18/20248410개발 환경 구성: 713. "WSL --debug-shell"로 살펴보는 WSL 2 VM의 리눅스 환경
13649정성태6/18/20247957오류 유형: 910. windbg - !py 확장 명령어 실행 시 "failed to find python interpreter" (2)
13648정성태6/17/20248278오류 유형: 909. C# - DynamicMethod 사용 시 System.TypeAccessException
13647정성태6/16/20249344개발 환경 구성: 712. Windows - WSL 2의 네트워크 통신 방법 - 세 번째 이야기 (같은 IP를 공유하는 WSL 2 인스턴스) [1]
13646정성태6/14/20247758오류 유형: 908. Process Explorer - "Error configuring dump resources: The system cannot find the file specified."
13645정성태6/13/20248197개발 환경 구성: 711. Visual Studio로 개발 시 기본 등록하는 dev tag 이미지로 Docker Desktop k8s에서 실행하는 방법
13644정성태6/12/20248868닷넷: 2265. C# - System.Text.Json의 기본적인 (한글 등에서의) escape 처리 [1]
13643정성태6/12/20248315오류 유형: 907. MySqlConnector 사용 시 System.IO.FileLoadException 오류
13642정성태6/11/20248198스크립트: 65. 파이썬 - asgi 버전(2, 3)에 따라 달라지는 uvicorn 호스팅
13641정성태6/11/20248673Linux: 71. Ubuntu 20.04를 22.04로 업데이트
1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...