核心是語意核心中最重要的元件。 最簡單的是核心是相依性插入容器,可管理執行 AI 應用程式所需的所有服務和外掛程式。 如果您將所有服務和外掛程式提供給核心,AI 會視需要順暢地使用這些服務與外掛程式。
核心在正中央
因為核心具有執行原生程式代碼和 AI 服務所需的所有服務和外掛程式,所以語意核心 SDK 內幾乎每個元件都會使用它來為您的代理程式提供動力。 這表示如果您在 Semantic Kernel 中執行任何提示或程式碼,則核心一律可供擷取必要的服務和外掛程式。
在 Semantic Kernel 中,核心是所有事物的中心
這極其強大,因為這意味著您作為開發人員,擁有一個集中位置來設定,並且最重要的是監控您的 AI 代理程式。 例如,當您從核心叫用提示時。 當您這樣做時,核心會...
- 選取最佳的 AI 服務以執行提示。
- 使用範本來建立提示。
- 將提示傳送至 AI 服務。
- 接收並剖析回應。
- 最後,將 LLM 的回應傳回至您的應用程式。
在整個程式中,您可以建立每個步驟所觸發的事件和中間件。 這表示您可以執行記錄、提供狀態更新給使用者,以及最重要的負責任 AI 等動作。 皆出自一處。
使用服務和外掛程式建置核心
在建置核心之前,您應該先瞭解存在的兩種元件類型:
| 元件 | 描述 |
|---|---|
| 服務 | 這些是由 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# 中使用相依性插入的更多範例,請參閱 概念範例。
下一步
既然您已瞭解核心,您可以瞭解可新增至該核心的所有不同 AI 服務。