Semantic Kernel：Kernel内核


現在、Semantic KernelはOpenAI、Azure OpenAI、Gemini、HuggingFace、MistralAIなどのLLMをサポートしており、今後もさらに充実していくことでしょう。

まず、対応するLLMパッケージを導入する必要があり、具体的なプロジェクトファイルは以下の通りです：

```xml
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net9.0</TargetFramework>
    <RootNamespace>Demo01_Kernel</RootNamespace>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.0-preview.4.24266.19" />
    <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="9.0.0-preview.4.24266.19" />
    <PackageReference Include="Microsoft.SemanticKernel" Version="1.14.1" />
    <PackageReference Include="Microsoft.SemanticKernel.Connectors.Google" Version="1.14.1-alpha" />
    <PackageReference Include="Microsoft.SemanticKernel.Connectors.HuggingFace" Version="1.14.1-preview" />
    <PackageReference Include="Microsoft.SemanticKernel.Connectors.MistralAI" Version="1.14.1-alpha" />
  </ItemGroup>
</Project>
```

SKはLLMのSDKとして機能し、Kernelを通じて展開されます。これはasp.net coreに似ており、まずKernelを使ってBuilderを作成し、BuilderのServicesに各種サービスを追加し、最終的にBuildしてKernelを取得し、各種機能を実装する流れです。

```csharp
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using Microsoft.Extensions.Options;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using Microsoft.SemanticKernel.Services;
using System.Diagnostics.CodeAnalysis;
using System.Net.NetworkInformation;

var chatModelId = "gpt-4o";
var key = File.ReadAllText(@"C:\GPT\key.txt");
var endpoint = "";

#pragma warning disable SKEXP0010
#pragma warning disable SKEXP0070
var builder = Kernel.CreateBuilder()
    .AddOpenAIChatCompletion(chatModelId, key);
    //.AddAzureOpenAIChatCompletion(chatModelId, endpoint, key)
    //.AddGoogleAIGeminiChatCompletion(chatModelId, key)
    //.AddHuggingFaceChatCompletion(chatModelId, apiKey: key)
    //.AddMistralChatCompletion(chatModelId, key)
    //builder.Services.AddSingleton<IAIServiceSelector>(new GptAIServiceSelector());
    //ServiceSelectorの追加
builder.Services.AddScoped<IAIServiceSelector, MyAIServiceSelector>();
    //カスタムサービスの追加
builder.Services.AddScoped<IMyService, MyService>();
    //ログサービスの追加
builder.Services.AddLogging(c => c
    .AddConsole()
    //.AddJsonConsole()
    .SetMinimumLevel(LogLevel.Information));
Kernel kernel = builder.Build();

var logger = kernel.LoggerFactory.CreateGroup("logger");
var prompt = "こんにちは、何を手伝えますか";
var result = await kernel.InvokePromptAsync(prompt);
var message = @$"戻り値：{result.GetValue<string>()}";
logger.LogInformation(message);

class MyAIServiceSelector : IAIServiceSelector
{
    private readonly IMyService _myService;
    private readonly ILogger<GptAIServiceSelector> _logger;
    public GptAIServiceSelector(IMyService myService, ILogger<GptAIServiceSelector> logger)
    {
        _myService = myService;
        _logger = logger;
    }
    public bool TrySelectAIService<T>(
        Kernel kernel, KernelFunction function, KernelArguments arguments,
        [NotNullWhen(true)] out T? service, out PromptExecutionSettings? serviceSettings) where T : class, IAIService
    {
        _myService.Print();
        foreach (var serviceToCheck in kernel.GetAllServices<T>())
        {
            var serviceModelId = serviceToCheck.GetModelId();
            var endpoint = serviceToCheck.GetEndpoint();
            if (!string.IsNullOrEmpty(serviceModelId))
            {
                _logger.LogInformation($"使用モデル: {serviceModelId} {endpoint}");
                _logger.LogInformation($"サービスタイプ: {serviceToCheck.GetType().Name}");
                service = serviceToCheck;
                serviceSettings = new OpenAIPromptExecutionSettings();
                return true;
            }
        }
        service = null;
        serviceSettings = null;
        return false;
    }
}

//カスタムサービスの追加
interface IMyService
{
    void Print();
}

class MyService : IMyService
{
    readonly ILogger<MyService> _logger;
    public MyService(ILogger<MyService> logger)
    {
        _logger = logger;
        logger.LogInformation("MyServiceのインスタンス化");
    }
    public void Print()
    {
        _logger.LogWarning("警告開始");
    }
}
```

(Translated by GPT)

元のリンク：https://mp.weixin.qq.com/s?__biz=MzA3NDM1MzIyMQ==&mid=2247488194&idx=1&sn=d91eb02d48f6c60f85e1bbb2ed3568ba&chksm=9f004de8a877c4fee3b15ce4063a55c769b5263a34b535919fedd56f9319560d92be13a0f00c&token=1006949870&lang=zh_CN#rd&wt.mc_id=MVP_325642