英語で読む

次の方法で共有


カーネルについて

プログラミング言語を選択する

カーネルはセマンティック カーネルの中心的なコンポーネントです。 最も簡単なカーネルは、AI アプリケーションの実行に必要なすべてのサービスとプラグインを管理する依存関係挿入コンテナーです。 すべてのサービスとプラグインをカーネルに提供すると、必要に応じて AI によってシームレスに使用されます。

カーネルが中央にある

カーネルには、ネイティブ コードと AI サービスの両方を実行するために必要なすべてのサービスとプラグインがあるため、セマンティック カーネル SDK 内のほぼすべてのコンポーネントによって使用され、エージェントが機能します。 つまり、セマンティック カーネルでプロンプトまたはコードを実行すると、必要なサービスとプラグインを取得するためにカーネルが常に使用できるようになります。

カーネルはセマンティック カーネルのすべての中心にあります

これは非常に強力です。これは、開発者が AI エージェントを構成し、最も重要に監視できる 1 つの場所を持っていることを意味するためです。 たとえば、カーネルからプロンプトを呼び出すとします。 これを行うと、カーネルは...

  1. プロンプトを実行するための最適な AI サービスを選択します。
  2. 指定されたプロンプト テンプレートを使用してプロンプトをビルドします。
  3. AI サービスにプロンプトを送信します。
  4. 応答を受信して解析します。
  5. 最後に、LLM からの応答をアプリケーションに返します。

このプロセス全体を通して、これらの各手順でトリガーされるイベントとミドルウェアを作成できます。 つまり、ログ記録などのアクションを実行したり、状態の更新をユーザーに提供したり、最も重要な責任を負う AI を提供したりできます。 すべて 1 か所から。

サービスとプラグインを使用してカーネルを構築する

カーネルをビルドする前に、まず、存在する 2 種類のコンポーネントについて理解しておく必要があります。

コンポーネント 説明
サービス これらは、AI サービス (チャット完了など) と、アプリケーションの実行に必要な他のサービス (ログ記録や HTTP クライアントなど) の両方で構成されます。 これは、すべての言語での依存関係の挿入をサポートできるように、.NET のサービス プロバイダー パターンの後にモデル化されました。
プラグイン これらは、作業を実行するために AI サービスとプロンプト テンプレートによって使用されるコンポーネントです。 たとえば、AI サービスでは、プラグインを使用してデータベースからデータを取得したり、外部 API を呼び出してアクションを実行したりできます。

カーネルの作成を開始するには、ファイルの先頭に必要なパッケージをインポートします。

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Plugins.Core;

次に、サービスとプラグインを追加できます。 Azure OpenAI チャットの完了、ロガー、時間プラグインを追加する方法の例を次に示します。

// Create a kernel with a logger and Azure OpenAI chat completion service
var builder = Kernel.CreateBuilder();
builder.AddAzureOpenAIChatCompletion(modelId, endpoint, apiKey);
builder.Services.AddLogging(c => c.AddDebug().SetMinimumLevel(LogLevel.Trace));
builder.Plugins.AddFromType<TimePlugin>();
Kernel kernel = builder.Build();

必要なパッケージをインポートします。

from semantic_kernel import Kernel
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
from semantic_kernel.core_plugins.time_plugin import TimePlugin

次に、カーネルを作成できます。

# Initialize the kernel
kernel = Kernel()

最後に、必要なサービスとプラグインを追加できます。 Azure OpenAI チャットの完了、ロガー、時間プラグインを追加する方法の例を次に示します。

# Add the Azure OpenAI chat completion service
kernel.add_service(AzureChatCompletion(model_id, endpoint, api_key))

# Add a plugin
kernel.add_plugin(
    TimePlugin(),
    plugin_name="TimePlugin",
)

カーネルからの MCP サーバーの作成

セマンティック カーネル インスタンスに登録した関数からの MCP サーバーの作成がサポートされるようになりました。

これを行うには、通常どおりにカーネルを作成し、そこから MCP サーバーを作成できます。

from semantic_kernel import Kernel
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
from semantic_kernel.functions import kernel_function
from semantic_kernel.prompt_template import InputVariable, PromptTemplateConfig

kernel = Kernel()

@kernel_function()
def echo_function(message: str, extra: str = "") -> str:
    """Echo a message as a function"""
    return f"Function echo: {message} {extra}"

kernel.add_service(OpenAIChatCompletion(service_id="default"))
kernel.add_function("echo", echo_function, "echo_function")
kernel.add_function(
    plugin_name="prompt",
    function_name="prompt",
    prompt_template_config=PromptTemplateConfig(
        name="prompt",
        description="This is a prompt",
        template="Please repeat this: {{$message}} and this: {{$extra}}",
        input_variables=[
            InputVariable(
                name="message",
                description="This is the message.",
                is_required=True,
                json_schema='{ "type": "string", "description": "This is the message."}',
            ),
            InputVariable(
                name="extra",
                description="This is extra.",
                default="default",
                is_required=False,
                json_schema='{ "type": "string", "description": "This is the message."}',
            ),
        ],
    ),
)
server = kernel.as_mcp_server(server_name="sk")

上記で作成した server オブジェクトは mcp パッケージから取得されます。たとえば、リソースやその他の機能を追加することで、さらに拡張できます。 その後、たとえば Stdio で使用するためにオンラインにすることができます。

import anyio
from mcp.server.stdio import stdio_server

async def handle_stdin(stdin: Any | None = None, stdout: Any | None = None) -> None:
    async with stdio_server() as (read_stream, write_stream):
        await server.run(read_stream, write_stream, server.create_initialization_options())

anyio.run(handle_stdin)

または SSE を使用する場合:

import uvicorn
from mcp.server.sse import SseServerTransport
from starlette.applications import Starlette
from starlette.routing import Mount, Route

sse = SseServerTransport("/messages/")

async def handle_sse(request):
    async with sse.connect_sse(request.scope, request.receive, request._send) as (read_stream, write_stream):
        await server.run(read_stream, write_stream, server.create_initialization_options())

starlette_app = Starlette(
    debug=True,
    routes=[
        Route("/sse", endpoint=handle_sse),
        Mount("/messages/", app=sse.handle_post_message),
    ],
)

uvicorn.run(starlette_app, host="0.0.0.0", port=8000)

MCP プロンプト用テンプレートの公開

また、次のように MCP プロンプトとして公開することで、さまざまなセマンティック カーネル プロンプト テンプレートを利用することもできます。

from semantic_kernel.prompt_template import InputVariable, KernelPromptTemplate, PromptTemplateConfig

prompt = KernelPromptTemplate(
    prompt_template_config=PromptTemplateConfig(
        name="release_notes_prompt",
        description="This creates the prompts for a full set of release notes based on the PR messages given.",
        template=template,
        input_variables=[
            InputVariable(
                name="messages",
                description="These are the PR messages, they are a single string with new lines.",
                is_required=True,
                json_schema='{"type": "string"}',
            )
        ],
    )
)

server = kernel.as_mcp_server(server_name="sk_release_notes", prompts=[prompt])

カーネルをビルドする

カーネルは、 Kernel.builder()を使用してビルドできます。 これにより、必要な AI サービスとプラグインを追加できます。

Kernel kernel = Kernel.builder()
    .withAIService(ChatCompletionService.class, chatCompletionService)
    .withPlugin(lightPlugin)
    .build();

依存性注入の使用

C# では、依存関係の挿入を使用してカーネルを作成できます。 これを行うには、 ServiceCollection を作成し、サービスとプラグインを追加します。 依存関係挿入を使用してカーネルを作成する方法の例を次に示します。

ヒント

プラグイン コレクションは変更可能であるため、使用するたびに破棄されるように、カーネルを一時的なサービスとして作成することをお勧めします。 カーネルは非常に軽量であるため (サービスとプラグインのコンテナーに過ぎないため)、使用ごとに新しいカーネルを作成することはパフォーマンスの問題ではありません。

using Microsoft.SemanticKernel;

var builder = Host.CreateApplicationBuilder(args);

// Add the OpenAI chat completion service as a singleton
builder.Services.AddOpenAIChatCompletion(
    modelId: "gpt-4",
    apiKey: "YOUR_API_KEY",
    orgId: "YOUR_ORG_ID", // Optional; for OpenAI deployment
    serviceId: "YOUR_SERVICE_ID" // Optional; for targeting specific services within Semantic Kernel
);

// Create singletons of your plugins
builder.Services.AddSingleton(() => new LightsPlugin());
builder.Services.AddSingleton(() => new SpeakerPlugin());

// Create the plugin collection (using the KernelPluginFactory to create plugins from objects)
builder.Services.AddSingleton<KernelPluginCollection>((serviceProvider) => 
    [
        KernelPluginFactory.CreateFromObject(serviceProvider.GetRequiredService<LightsPlugin>()),
        KernelPluginFactory.CreateFromObject(serviceProvider.GetRequiredService<SpeakerPlugin>())
    ]
);

// Finally, create the Kernel service with the service provider and plugin collection
builder.Services.AddTransient((serviceProvider)=> {
    KernelPluginCollection pluginCollection = serviceProvider.GetRequiredService<KernelPluginCollection>();

    return new Kernel(serviceProvider, pluginCollection);
});

ヒント

C# で依存関係の挿入を使用する方法の詳細なサンプルについては、 concept サンプルを参照してください。

次のステップ

カーネルを理解したら、それに追加できるさまざまな AI サービスについて学習できます。