聊天完成

透過聊天完成,您可以模擬與 AI 代理程式的來回交談。 這當然適用於建立聊天機器人,但也可用於建立可完成商務程式、產生程式代碼等的自發代理程式。 作為 OpenAI、Google、Mistral、Facebook 等所提供的主要模型類型,聊天完成是您將新增至語意核心專案的最常見 AI 服務。

挑選聊天完成模型時,您必須考慮下列事項:

  • 模型支援哪些形式(例如文字、影像、音訊等)?
  • 它是否支援呼叫函式?
  • 它接收和產生令牌的速度有多快?
  • 每個令牌的成本是多少?

重要

在上述所有問題中,最重要的是模型是否支援函數呼叫。 如果沒有,您將無法使用模型來呼叫現有的程序代碼。 來自 OpenAI、Google、Mistral 和 Amazon 的大部分最新模型都支援呼叫函式。 不過,小型語言模型的支援仍然有限。

安裝必要的套件

將聊天完成新增至核心之前,您必須安裝必要的套件。 以下是您需要為每個 AI 服務提供者安裝的套件。

dotnet add package Microsoft.SemanticKernel.Connectors.OpenAI

建立聊天完成服務

現在您已安裝必要的套件,您可以建立聊天完成服務。 以下是您可以使用語意核心建立聊天完成服務的幾種方式。

直接新增至核心

若要新增聊天完成服務,您可以使用下列程式代碼將它新增至核心的內部服務提供者。

dotnet add package Microsoft.SemanticKernel.Connectors.OpenAI
using Microsoft.SemanticKernel;

IKernelBuilder kernelBuilder = Kernel.CreateBuilder();
kernelBuilder.AddAzureOpenAIChatCompletion(
    deploymentName: "NAME_OF_YOUR_DEPLOYMENT",
    apiKey: "YOUR_API_KEY",
    endpoint: "YOUR_AZURE_ENDPOINT",
    modelId: "gpt-4", // Optional name of the underlying model if the deployment name doesn't match the model name
    serviceId: "YOUR_SERVICE_ID", // Optional; for targeting specific services within Semantic Kernel
    httpClient: new HttpClient() // Optional; if not provided, the HttpClient from the kernel will be used
);
Kernel kernel = kernelBuilder.Build();

使用相依性插入

如果您使用相依性插入,您可能會想要將 AI 服務直接新增至服務提供者。 如果您想要建立 AI 服務的單一專案,並在暫時性核心中重複使用它們,這會很有説明。

using Microsoft.SemanticKernel;

var builder = Host.CreateApplicationBuilder(args);

builder.Services.AddAzureOpenAIChatCompletion(
    deploymentName: "NAME_OF_YOUR_DEPLOYMENT",
    apiKey: "YOUR_API_KEY",
    endpoint: "YOUR_AZURE_ENDPOINT",
    modelId: "gpt-4", // Optional name of the underlying model if the deployment name doesn't match the model name
    serviceId: "YOUR_SERVICE_ID" // Optional; for targeting specific services within Semantic Kernel
);

builder.Services.AddTransient((serviceProvider)=> {
    return new Kernel(serviceProvider);
});

建立獨立實例

最後,您可以直接建立服務的實例,以便稍後將它們新增至核心,或直接在程式代碼中使用這些實例,而不需要將它們插入核心或服務提供者中。

using Microsoft.SemanticKernel.Connectors.OpenAI;

AzureOpenAIChatCompletionService chatCompletionService = new (
    deploymentName: "NAME_OF_YOUR_DEPLOYMENT",
    apiKey: "YOUR_API_KEY",
    endpoint: "YOUR_AZURE_ENDPOINT",
    modelId: "gpt-4", // Optional name of the underlying model if the deployment name doesn't match the model name
    httpClient: new HttpClient() // Optional; if not provided, the HttpClient from the kernel will be used
);

若要新增聊天完成服務,您可以使用下列程序代碼將它新增至核心。

from semantic_kernel import Kernel
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion

# Initialize the kernel
kernel = Kernel()

# Add the Azure OpenAI chat completion service
kernel.add_service(AzureChatCompletion(
    deployment_name="my-deployment",
    api_key="my-api-key",
    base_url="https://my-deployment.azurewebsites.net", # Used to point to your service
    service_id="my-service-id", # Optional; for targeting specific services within Semantic Kernel
))

您也可以直接建立服務的實例,以便稍後將它們新增至核心,或直接在程式代碼中使用這些實例,而不需將它們插入核心中。

from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion

chat_completion_service = AzureChatCompletion(
    deployment_name="my-deployment",
    api_key="my-api-key",
    base_url="https://my-deployment.azurewebsites.net", # Used to point to your service
    service_id="my-service-id", # Optional; for targeting specific services within Semantic Kernel
)

擷取聊天完成服務

將聊天完成服務新增至核心之後,您可以使用 get 服務方法來擷取它們。 以下是如何從核心擷取聊天完成服務的範例。

var chatCompletionService = kernel.GetRequiredService<IChatCompletionService>();
from semantic_kernel.connectors.ai.chat_completion_client_base import ChatCompletionClientBase

chat_completion_service = kernel.get_service(type=ChatCompletionClientBase)

使用聊天完成服務

現在您已有聊天完成服務,您可以使用它從 AI 代理程式產生回應。 使用聊天完成服務有兩個主要方式:

  • 非串流:您等待服務產生整個回應,再將它傳回給使用者。
  • 串流:產生響應的個別區塊,並在建立時傳回給使用者。

以下是您可以使用聊天完成服務來產生回應的兩種方式。

非串流聊天完成

若要使用非串流聊天完成,您可以使用下列程式代碼從 AI 代理程式產生回應。

ChatHistory history = [];
history.AddUserMessage("Hello, how are you?");

var response = await chatCompletionService.GetChatMessageContentAsync(
    history,
    kernel: kernel
);
chat_history = ChatHistory()
chat_history.add_user_message("Hello, how are you?")

response = (await chat_completion.get_chat_message_contents(
    chat_history=history,
    kernel=kernel,
))[0]

串流聊天完成

若要使用串流聊天完成,您可以使用下列程式代碼從 AI 代理程式產生回應。

ChatHistory history = [];
history.AddUserMessage("Hello, how are you?");

var response = chatCompletionService.GetStreamingChatMessageContentsAsync(
    chatHistory: history,
    kernel: kernel
);

await foreach (var chunk in response)
{
    Console.Write(chunk);
}
chat_history = ChatHistory()
chat_history.add_user_message("Hello, how are you?")

response = chat_completion.get_streaming_chat_message_contents(
    chat_history=history,
    kernel=kernel,
)

async for chunk in response:
    print(chunk)

下一步

既然您已將聊天完成服務新增至語意核心專案,您就可以開始建立與 AI 代理程式的交談。 若要深入瞭解如何使用聊天完成服務,請參閱下列文章: