次の方法で共有


.NET 向け Semantic Kernel の概要

この記事では、Semantic Kernel の主要な概念と機能について説明します。 Semantic Kernel は、.NET アプリケーションで AI を操作するための、強力で推奨される選択肢です。 以下のセクションでは、次のことを説明します。

  • プロジェクトに Semantic Kernel を追加する方法
  • Semantic Kernel のコア概念

このセクションは、特に .NET のコンテキストにおける Semantic Kernel の入門的概要として役立ちます。 Semantic Kernel に関する包括的な情報とトレーニングについては、次のリソースをご覧ください。

.NET プロジェクトに Semantic Kernel を追加する

Semantic Kernel SDK は、.NET 向けの NuGet パッケージで利用でき、標準のアプリ構成と統合されます。

次のコマンドを使用して Microsoft.SemanticKernel パッケージをインストールします。

dotnet add package Microsoft.SemanticKernel

Note

Microsoft.SemanticKernel は、Semantic Kernel のコア機能を提供しますが、機能を追加する場合は追加のパッケージをインストールする必要があります。 たとえば、メモリ関連の機能にアクセスするためには、Microsoft.SemanticKernel.Plugins.Memory パッケージが提供されます。 詳細については、Semantic Kernel のドキュメントを参照してください。

Semantic Kernel にアクセスして操作する KernelBuilder クラスを使用して、Kernel インスタンスを作成し構成します。 Kernel はサービス、データ、接続を保持し、コードと AI モデル間の統合を調整します。

.NET コンソール アプリで Kernel を構成します。

var builder = Kernel.CreateBuilder();

// Add builder configuration and services

var kernel = builder.Build();

ASP.NET Core アプリでカーネルを構成します。

var builder = WebApplication.CreateBuilder();
builder.Services.AddKernel();

// Add builder configuration and services

var app = builder.Build();

Semantic Kernel について

Semantic Kernel は、OpenAI、Azure OpenAI、Hugging Face などの AI モデルとサービスを、C#、Python、Java などの従来のプログラミング言語と統合して調整するオープンソース SDK です。

Semantic Kernel SDK は、エンタープライズ開発者にとって次の点で役に立ちます。

  • 既存のアプリケーションへの AI 機能の統合を合理化し、エンタープライズ製品のまとまりのあるソリューションを実現します。
  • 複雑さを軽減する抽象化を提供することで、さまざまな AI モデルまたはサービスを操作する学習曲線を最小限に抑えます。
  • AI モデルからの予期しないプロンプトと応答動作を減らすことで、信頼性が向上します。 プロンプトを最適化し、タスクを計画して、制御された予測可能なユーザー エクスペリエンスを作成できます。

Semantic Kernel は、いくつかのコア概念を中心に構築されています。

  • 接続: 外部 AI サービス、データ ソースとのインターフェイス。
  • プラグイン: アプリケーションで使用できるカプセル化された関数。
  • プランナー: ユーザーの動作に基づく、プランと戦略実行の調整。
  • メモリ: AI アプリのコンテキスト管理の抽象化および簡素化。

これらの構成要素については、次のセクションで詳しく説明します。

つながり

Semantic Kernel SDK には、開発者が LLM やその他のサービスを既存のアプリケーションに統合できるようにする一連のコネクタが含まれています。 これらのコネクタは、アプリケーション コードと AI モデルまたはサービスの間のブリッジとして機能します。 Semantic Kernel は、独自のワークフローと機能の構築に集中できるよう、多くの一般的な接続の問題と課題を処理します。

次のコード スニペットは、Azure OpenAI モデルに Kernel を作成し、接続を追加します。

using Microsoft.SemanticKernel;

// Create kernel
var builder = Kernel.CreateBuilder();

// Add a chat completion service:
builder.Services.AddAzureOpenAIChatCompletion(
    "your-resource-name",
    "your-endpoint",
    "your-resource-key",
    "deployment-model");
var kernel = builder.Build();

プラグイン

Semantic Kernel プラグインは、アプリケーションと AI モデルが使用するためのカプセル化された標準言語関数です。 独自のプラグインを作成することも、SDK によって提供されるプラグインに依存することもできます。 これらのプラグインは、AI モデルの方が適しているタスクを合理化し、従来の C# メソッドと効率的に組み合わせます。 プラグイン関数は、一般にセマンティック関数と、ネイティブ関数の 2 種類に分類されます。

セマンティック関数

セマンティック関数は、基本的に、Semantic Kernel が必要に応じてカスタマイズして呼び出すことができる、コードで定義された AI プロンプトです。 これらのプロンプトをテンプレート化して、変数、カスタム プロンプトと入力候補の書式設定などを使用できます。

次のコード スニペットでは、セマンティック関数を定義して登録します。

var userInput = Console.ReadLine();

// Define semantic function inline.
string skPrompt = @"Summarize the provided unstructured text in a sentence that is easy to understand.
                    Text to summarize: {{$userInput}}";

// Register the function
kernel.CreateSemanticFunction(
    promptTemplate: skPrompt, 
    functionName: "SummarizeText",
    pluginName: "SemanticFunctions"
);

ネイティブ関数

ネイティブ関数は、Semantic Kernel が直接呼び出してデータを操作または取得できる C# メソッドです。 LLM プロンプトではなく、従来のコード命令に適した操作を実行します。

次のコード スニペットでは、ネイティブ関数を定義して登録します。

// Define native function
public class NativeFunctions {

    [SKFunction, Description("Retrieve content from local file")]
    public async Task<string> RetrieveLocalFile(string fileName, int maxSize = 5000) 
    {
        string content = await File.ReadAllTextAsync(fileName); 
        if (content.Length <= maxSize) return content;
        return content.Substring(0, maxSize);
    }
}

//Import native function
string plugInName = "NativeFunction";
string functionName = "RetrieveLocalFile";

var nativeFunctions = new NativeFunctions();
kernel.ImportFunctions(nativeFunctions, plugInName);

Planner

プランナーは Semantic Kernel のコア コンポーネントであり、AI モデルとプラグイン間のシームレスな統合を管理するための AI オーケストレーションを提供します。 このレイヤーは、ユーザー要求から実行戦略を立案し、AI 支援型のプランを使用して複雑なタスクを実行するようにプラグインを動的に調整します。

次の擬似コード スニペットを考えてみましょう。

// Native function definition and kernel configuration code omitted for brevity

// Configure and create the plan
string planDefinition = "Read content from a local file and summarize the content.";
SequentialPlanner sequentialPlanner = new SequentialPlanner(kernel);      

string assetsFolder = @"../../assets";
string fileName = Path.Combine(assetsFolder,"docs","06_SemanticKernel", "aci_documentation.txt");

ContextVariables contextVariables = new ContextVariables();
contextVariables.Add("fileName", fileName);

var customPlan = await sequentialPlanner.CreatePlanAsync(planDefinition);

// Execute the plan
KernelResult kernelResult = await kernel.RunAsync(contextVariables, customPlan);
Console.WriteLine($"Summarization: {kernelResult.GetValue<string>()}");

上記のコードでは、ローカル ファイルからコンテンツを読み取り、内容を要約する実行可能なシーケンシャル プランを作成します。 このプランでは、ネイティブ関数を使用してファイルを読み取り、AI モデルを使用して分析する手順を設定します。

メモリ

Semantic Kernel のメモリは、AI アプリケーションのコンテキスト管理を簡略化するために、埋め込みモデル、ベクター データベース、およびその他のデータに対する抽象化を提供します。 メモリは、基になる LLM または Vector DB に依存せず、統一された開発者エクスペリエンスを提供します。 Azure AI Search、Azure Cache for Redis など、さまざまなソースまたはサービスにデータを格納するようにメモリ機能を構成できます。

次のコード スニペットを考えてみます。

var facts = new Dictionary<string,string>();
facts.Add(
    "Azure Machine Learning; https://docs.microsoft.com/en-us/azure/machine-learning/", 
    @"Azure Machine Learning is a cloud service for accelerating and 
    managing the machine learning project lifecycle. Machine learning professionals, 
    data scientists, and engineers can use it in their day-to-day workflows"
);

facts.Add(
    "Azure SQL Service; https://docs.microsoft.com/en-us/azure/azure-sql/", 
    @"Azure SQL is a family of managed, secure, and intelligent products
    that use the SQL Server database engine in the Azure cloud."
);

string memoryCollectionName = "SummarizedAzureDocs";

foreach (var fact in facts) {
    await memoryBuilder.SaveReferenceAsync(
        collection: memoryCollectionName,
        description: fact.Key.Split(";")[1].Trim(),
        text: fact.Value,
        externalId: fact.Key.Split(";")[2].Trim(),
        externalSourceName: "Azure Documentation"
    );
}

上記のコードは、AI モデルと対話してタスクを調整する際にデータを使用できるよう、一連のファクトをメモリに読み込みます。