Semantic KernelのGetting Started
セマンティック カーネルは、AI エージェントを簡単に構築し、AIモデルを C#、Python、または Java コードベースに統合できる、軽量のオープンソース開発キットです。個人的に非常に好きなミドルウェアです。
公式のレポジトリには、動作を確認するためのNotebookが提供されています。本記事ではその手順を記載します。
💻環境
- Windows11
- vscode 1.92.2
 
 
📝手順
- 事前準備
- 設定情報の準備(APIキー、EndPointなど)
 - .NET8.0のインストール
 - Polyglot Notebooksのインストール
 
 - 設定ファイルの作成
 - getting-staredの実施
 
⚙事前準備
- OpenAIおよびAzure OpenAIとも無料ではありません
 
設定情報の準備
- OpenAiのモデルを利用する場合、2種類の方法があります
- OpenAIのAPIを利用する方法(OpenAIプラットフォームのAPIキー)
 - Azure OpenAI Serviceを利用する方法(Azure側の設定情報)
 
 - 上記の違いは↓を参考にしてください
 
- 個人で試す場合は、OpenAIプラットフォームのAPIキーとなります
- APIキーの取得方法で調べればたくさんの記事が出るため、本記事では割愛します
 
 
以下、Azure OpenAI Serviceについて補足します。
Azure OpenAI Service接続情報
- Azure Portal等で使用したいモデルをデプロイします。
 - デプロイ後、デプロイ情報より3つの情報を確認します(モデル:GPT-4o使用)
- model : デプロイ時に自身でつけたモデル名
 - endpoint : https://[model].openai.azure.com/
- .openai.azure.com/以降の文字列は不要
 
 - apikey : コピーボタンでクリップボードに保持
 
 
上記の3つを登録する必要があります
.NET8.0のインストール
下記サイトより、自身の環境に合ったファイルをダウンロードし、インストールします。
Polyglot Notebooksのインストール
Polyglot Notebooksは、vsccodeの拡張機能の1つです。
.NET Interactiveを利用したPolyglot Notebooks 拡張機能により、Visual Studio Code で多言語ノートブックがサポートされます。
拡張機能の検索欄に、"Polyglot Notebook"を入力し、インストールします。

設定ファイルの作成
下記のレポジトリをクローンして、vscodeで開きます。
./dotnet\notebooks\0-AI-settings.ipynbを開きます

自身の利用に合わせて、以下を設定します(Azure OpenAIを利用する場合で記載)

実行していくと、設定ファイルが作成されます。

以上で、接続する準備ができました。
GettingStaredの実施
.\dotnet\notebooks\00-getting-started.ipynbを実施していくだけですが、注釈を記載します。
- 
Step 1: Configure your AI service credentials
// Load some helper functions, e.g. to load values from settings.json #!import config/Settings.cs- 設定ファイルを読み込みます
 
 - 
Step 2: Import Semantic Kernel SDK from NuGet
// Import Semantic Kernel #r "nuget: Microsoft.SemanticKernel, 1.11.1"- SemanticKernelをインポートします
 - 指定が古いため、必要に応じて新しいパッケージを指定してください
 - また、頻繁にアップデートされるため、機能によってはプレスリリース版のみで提供されています
 
 - 
Step 3: Instantiate the Kernel
using Microsoft.SemanticKernel; using Kernel = Microsoft.SemanticKernel.Kernel; //Create Kernel builder var builder = Kernel.CreateBuilder(); // Configure AI service credentials used by the kernel var (useAzureOpenAI, model, azureEndpoint, apiKey, orgId) = Settings.LoadFromFile(); if (useAzureOpenAI) builder.AddAzureOpenAIChatCompletion(model, azureEndpoint, apiKey); else builder.AddOpenAIChatCompletion(model, apiKey, orgId); var kernel = builder.Build();- kernelの生成とコンフィグ
 
 - 
Step 4: Load and Run a Plugin
// FunPlugin directory path var funPluginDirectoryPath = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "..", "..", "prompt_template_samples", "FunPlugin"); // Load the FunPlugin from the Plugins Directory var funPluginFunctions = kernel.ImportPluginFromPromptDirectory(funPluginDirectoryPath); // Construct arguments var arguments = new KernelArguments() { ["input"] = "time travel to dinosaur age" }; // Run the Function called Joke var result = await kernel.InvokeAsync(funPluginFunctions["Joke"], arguments); // Return the result to the Notebook Console.WriteLine(result);- ../../prompt_template_samples/FunPlugin/Joke/を参照する
 - "恐竜時代へのタイムトラベル"を入力に指定
 - Invokeで問い合わせし、resultに結果が格納
 - 結果を表示
 
 - 上記を実施すると下記の結果がとなりました
Why did the time traveler bring a ladder to the dinosaur age? Because he heard the Brachiosaurus had the best "high" fives!なぜタイムトラベラーは恐竜時代にハシゴを持ってきたのか? ブラキオサウルスの「ハイタッチ」が最高だと聞いたからだ! 
補足 - テキストプロンプト
- 
../../prompt_template_samples/FunPlugin/Joke/下には、2つのファイルがあります
- config.json
 - skprompt.txt
 
 - 
プロンプトの設定が記載されています
config.json{ "schema": 1, "description": "Generate a funny joke", "execution_settings": { "default": { "max_tokens": 1000, "temperature": 0.9, "top_p": 0.0, "presence_penalty": 0.0, "frequency_penalty": 0.0 } }, "input_variables": [ { "name": "input", "description": "Joke subject", "default": "" }, { "name": "style", "description": "Give a hint about the desired joke style", "default": "" } ] } - 
プロンプトに渡すひな形が書かれています
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. Incorporate the style suggestion, if provided: {{$style}} +++++ {{$input}} +++++- 上記の条件に、"- Respond in Japanese"を追加することで、日本語のジョークで返してくれます
 
 
さいごに
Semantic KernelのGettingStartedのみの説明になります。
実際に触ればわかるのですが、できることは多岐にわたり、非常に有用な開発キットと感じています。
みなさんが触ってみるきっかけになればと思います。
Discussion