チャットの完了により、AI エージェントとの会話の前後をシミュレートできます。 これはもちろん、チャット ボットの作成に役立ちますが、ビジネス プロセスを完了したり、コードを生成したりできる自律的なエージェントの作成にも使用できます。 OpenAI、Google、Mistral、Facebook などが提供する主要なモデルの種類として、チャットの完了はセマンティック カーネル プロジェクトに追加する最も一般的な AI サービスです。
チャット完了モデルを選択する場合は、次の点を考慮する必要があります。
- モデルはどのモダリティ (テキスト、画像、オーディオなど) をサポートしていますか?
- 関数呼び出しをサポートしていますか?
- トークンを受け取って生成する速度はどのくらいですか?
- 各トークンのコストはどのくらいですか?
重要
上記のすべての質問のうち、最も重要なのは、モデルが関数呼び出しをサポートしているかどうかです。 そうでない場合は、モデルを使用して既存のコードを呼び出すことができなくなります。 OpenAI、Google、Mistral、Amazon の最新モデルのほとんどは、関数呼び出しをサポートしています。 ただし、小さな言語モデルからのサポートはまだ限られています。
ローカル環境の設定
一部の AI サービスはローカルでホストでき、一部のセットアップが必要になる場合があります。 これをサポートするユーザー向けの手順を次に示します。
Docker を使用して Ollama をローカルで実行するには、次のコマンドを使用して、CPU を使用してコンテナーを開始します。
docker run -d -v "c:\temp\ollama:/root/.ollama" -p 11434:11434 --name ollama ollama/ollama
Docker を使用して Ollama をローカルで実行するには、次のコマンドを使用して、GPU を使用してコンテナーを開始します。
docker run -d --gpus=all -v "c:\temp\ollama:/root/.ollama" -p 11434:11434 --name ollama ollama/ollama
コンテナーが開始されたら、Docker コンテナーのターミナル ウィンドウを起動します 。たとえば、docker desktop を使用している場合は、アクションから Open in Terminal
を選択します。
このターミナルから必要なモデルをダウンロードします。たとえば、ここでは phi3 モデルをダウンロードしています。
ollama pull phi3
使用する ONNX モデルを含むリポジトリを複製します。
git clone https://huggingface.co/microsoft/Phi-3-mini-4k-instruct-onnx
必要なパッケージのインストール
カーネルにチャットの完了を追加する前に、必要なパッケージをインストールする必要があります。 AI サービス プロバイダーごとにインストールする必要があるパッケージを次に示します。
dotnet add package Microsoft.SemanticKernel.Connectors.AzureOpenAI
dotnet add package Microsoft.SemanticKernel.Connectors.OpenAI
dotnet add package Microsoft.SemanticKernel.Connectors.MistralAI --prerelease
dotnet add package Microsoft.SemanticKernel.Connectors.Google --prerelease
dotnet add package Microsoft.SemanticKernel.Connectors.HuggingFace --prerelease
dotnet add package Microsoft.SemanticKernel.Connectors.AzureAIInference --prerelease
dotnet add package Microsoft.SemanticKernel.Connectors.Ollama --prerelease
dotnet add package Microsoft.SemanticKernel.Connectors.Amazon --prerelease
注
Anthropic モデルは、Amazon Bedrock プラットフォームで利用できます。 Anthropic モデルを使用するには、Amazon コネクタ パッケージをインストールする必要があります。
dotnet add package Microsoft.SemanticKernel.Connectors.Amazon --prerelease
dotnet add package Microsoft.SemanticKernel.Connectors.Onnx --prerelease
OpenAI チャット入力候補 API (LLM Studio など) をサポートする他の AI サービス プロバイダーの場合は、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();
using Microsoft.SemanticKernel;
IKernelBuilder kernelBuilder = Kernel.CreateBuilder();
kernelBuilder.AddOpenAIChatCompletion(
modelId: "gpt-4",
apiKey: "YOUR_API_KEY",
orgId: "YOUR_ORG_ID", // Optional
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();
重要
Mistral チャット完了コネクタは現在試験段階です。 これを使用するには、 #pragma warning disable SKEXP0070
を追加する必要があります。
using Microsoft.SemanticKernel;
#pragma warning disable SKEXP0070
IKernelBuilder kernelBuilder = Kernel.CreateBuilder();
kernelBuilder.AddMistralChatCompletion(
modelId: "NAME_OF_MODEL",
apiKey: "API_KEY",
endpoint: new Uri("YOUR_ENDPOINT"), // Optional
serviceId: "SERVICE_ID", // Optional; for targeting specific services within Semantic Kernel
httpClient: new HttpClient() // Optional; for customizing HTTP client
);
Kernel kernel = kernelBuilder.Build();
重要
Google チャット完了コネクタは現在試験段階です。 これを使用するには、 #pragma warning disable SKEXP0070
を追加する必要があります。
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Connectors.Google;
#pragma warning disable SKEXP0070
IKernelBuilder kernelBuilder = Kernel.CreateBuilder();
kernelBuilder.AddGoogleAIGeminiChatCompletion(
modelId: "NAME_OF_MODEL",
apiKey: "API_KEY",
apiVersion: GoogleAIVersion.V1, // Optional
serviceId: "SERVICE_ID", // Optional; for targeting specific services within Semantic Kernel
httpClient: new HttpClient() // Optional; for customizing HTTP client
);
Kernel kernel = kernelBuilder.Build();
重要
Hugging Face チャット完了コネクタは現在試験段階です。 これを使用するには、 #pragma warning disable SKEXP0070
を追加する必要があります。
using Microsoft.SemanticKernel;
#pragma warning disable SKEXP0070
IKernelBuilder kernelBuilder = Kernel.CreateBuilder();
kernelBuilder.AddHuggingFaceChatCompletion(
model: "NAME_OF_MODEL",
apiKey: "API_KEY",
endpoint: new Uri("YOUR_ENDPOINT"), // Optional
serviceId: "SERVICE_ID", // Optional; for targeting specific services within Semantic Kernel
httpClient: new HttpClient() // Optional; for customizing HTTP client
);
Kernel kernel = kernelBuilder.Build();
重要
Azure AI 推論チャット完了コネクタは、現在試験段階です。 これを使用するには、 #pragma warning disable SKEXP0070
を追加する必要があります。
using Microsoft.SemanticKernel;
#pragma warning disable SKEXP0070
IKernelBuilder kernelBuilder = Kernel.CreateBuilder();
kernelBuilder.AddAzureAIInferenceChatCompletion(
modelId: "NAME_OF_MODEL",
apiKey: "API_KEY",
endpoint: new Uri("YOUR_ENDPOINT"), // Optional
serviceId: "SERVICE_ID", // Optional; for targeting specific services within Semantic Kernel
httpClient: new HttpClient() // Optional; for customizing HTTP client
);
Kernel kernel = kernelBuilder.Build();
重要
Ollama チャット完了コネクタは現在試験段階です。 これを使用するには、 #pragma warning disable SKEXP0070
を追加する必要があります。
using Microsoft.SemanticKernel;
#pragma warning disable SKEXP0070
IKernelBuilder kernelBuilder = Kernel.CreateBuilder();
kernelBuilder.AddOllamaChatCompletion(
modelId: "NAME_OF_MODEL", // E.g. "phi3" if phi3 was downloaded as described above.
endpoint: new Uri("YOUR_ENDPOINT"), // E.g. "http://localhost:11434" if Ollama has been started in docker as described above.
serviceId: "SERVICE_ID" // Optional; for targeting specific services within Semantic Kernel
);
Kernel kernel = kernelBuilder.Build();
重要
Anthropic に必要な Bedrock チャット完了コネクタは、現在試験段階です。 これを使用するには、 #pragma warning disable SKEXP0070
を追加する必要があります。
using Microsoft.SemanticKernel;
#pragma warning disable SKEXP0070
IKernelBuilder kernelBuilder = Kernel.CreateBuilder();
kernelBuilder.AddBedrockChatCompletionService(
modelId: "NAME_OF_MODEL",
bedrockRuntime: amazonBedrockRuntime, // Optional; An instance of IAmazonBedrockRuntime, used to communicate with Azure Bedrock.
serviceId: "SERVICE_ID" // Optional; for targeting specific services within Semantic Kernel
);
Kernel kernel = kernelBuilder.Build();
重要
Bedrock チャット完了コネクタは現在試験段階です。 これを使用するには、 #pragma warning disable SKEXP0070
を追加する必要があります。
using Microsoft.SemanticKernel;
#pragma warning disable SKEXP0070
IKernelBuilder kernelBuilder = Kernel.CreateBuilder();
kernelBuilder.AddBedrockChatCompletionService(
modelId: "NAME_OF_MODEL",
bedrockRuntime: amazonBedrockRuntime, // Optional; An instance of IAmazonBedrockRuntime, used to communicate with Azure Bedrock.
serviceId: "SERVICE_ID" // Optional; for targeting specific services within Semantic Kernel
);
Kernel kernel = kernelBuilder.Build();
重要
ONNX チャット完了コネクタは現在試験段階です。 これを使用するには、 #pragma warning disable SKEXP0070
を追加する必要があります。
using Microsoft.SemanticKernel;
#pragma warning disable SKEXP0070
IKernelBuilder kernelBuilder = Kernel.CreateBuilder();
kernelBuilder.AddOnnxRuntimeGenAIChatCompletion(
modelId: "NAME_OF_MODEL", // E.g. phi-3
modelPath: "PATH_ON_DISK", // Path to the model on disk e.g. C:\Repos\huggingface\microsoft\Phi-3-mini-4k-instruct-onnx\cpu_and_mobile\cpu-int4-rtn-block-32
serviceId: "SERVICE_ID", // Optional; for targeting specific services within Semantic Kernel
jsonSerializerOptions: customJsonSerializerOptions // Optional; for providing custom serialization settings for e.g. function argument / result serialization and parsing.
);
Kernel kernel = kernelBuilder.Build();
OpenAI チャット入力候補 API (LLM Studio など) をサポートする他の AI サービス プロバイダーの場合は、次のコードを使用して、既存の OpenAI チャット完了コネクタを再利用できます。
重要
OpenAI コネクタでのカスタム エンドポイントの使用は、現在試験段階です。 これを使用するには、 #pragma warning disable SKEXP0010
を追加する必要があります。
using Microsoft.SemanticKernel;
#pragma warning disable SKEXP0010
IKernelBuilder kernelBuilder = Kernel.CreateBuilder();
kernelBuilder.AddOpenAIChatCompletion(
modelId: "NAME_OF_MODEL",
apiKey: "API_KEY",
endpoint: new Uri("YOUR_ENDPOINT"), // Used to point to your service
serviceId: "SERVICE_ID", // Optional; for targeting specific services within Semantic Kernel
httpClient: new HttpClient() // Optional; for customizing HTTP client
);
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;
var builder = Host.CreateApplicationBuilder(args);
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
);
builder.Services.AddTransient((serviceProvider)=> {
return new Kernel(serviceProvider);
});
重要
Mistral チャット完了コネクタは現在試験段階です。 これを使用するには、 #pragma warning disable SKEXP0070
を追加する必要があります。
using Microsoft.SemanticKernel;
var builder = Host.CreateApplicationBuilder(args);
#pragma warning disable SKEXP0070
builder.Services.AddMistralChatCompletion(
modelId: "NAME_OF_MODEL",
apiKey: "API_KEY",
endpoint: new Uri("YOUR_ENDPOINT"), // Optional
serviceId: "SERVICE_ID" // Optional; for targeting specific services within Semantic Kernel
);
builder.Services.AddTransient((serviceProvider)=> {
return new Kernel(serviceProvider);
});
重要
Google チャット完了コネクタは現在試験段階です。 これを使用するには、 #pragma warning disable SKEXP0070
を追加する必要があります。
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Connectors.Google;
var builder = Host.CreateApplicationBuilder(args);
#pragma warning disable SKEXP0070
builder.Services.AddGoogleAIGeminiChatCompletion(
modelId: "NAME_OF_MODEL",
apiKey: "API_KEY",
apiVersion: GoogleAIVersion.V1, // Optional
serviceId: "SERVICE_ID" // Optional; for targeting specific services within Semantic Kernel
);
builder.Services.AddTransient((serviceProvider)=> {
return new Kernel(serviceProvider);
});
重要
Hugging Face チャット完了コネクタは現在試験段階です。 これを使用するには、 #pragma warning disable SKEXP0070
を追加する必要があります。
using Microsoft.SemanticKernel;
var builder = Host.CreateApplicationBuilder(args);
#pragma warning disable SKEXP0070
builder.Services.AddHuggingFaceChatCompletion(
model: "NAME_OF_MODEL",
apiKey: "API_KEY",
endpoint: new Uri("YOUR_ENDPOINT"), // Optional
serviceId: "SERVICE_ID" // Optional; for targeting specific services within Semantic Kernel
);
builder.Services.AddTransient((serviceProvider)=> {
return new Kernel(serviceProvider);
});
重要
Azure AI 推論チャット完了コネクタは、現在試験段階です。 これを使用するには、 #pragma warning disable SKEXP0070
を追加する必要があります。
using Microsoft.SemanticKernel;
var builder = Host.CreateApplicationBuilder(args);
#pragma warning disable SKEXP0070
builder.Services.AddAzureAIInferenceChatCompletion(
modelId: "NAME_OF_MODEL",
apiKey: "API_KEY",
endpoint: new Uri("YOUR_ENDPOINT"), // Optional
serviceId: "SERVICE_ID" // Optional; for targeting specific services within Semantic Kernel
);
builder.Services.AddTransient((serviceProvider)=> {
return new Kernel(serviceProvider);
});
重要
Ollama チャット完了コネクタは現在試験段階です。 これを使用するには、 #pragma warning disable SKEXP0070
を追加する必要があります。
using Microsoft.SemanticKernel;
var builder = Host.CreateApplicationBuilder(args);
#pragma warning disable SKEXP0070
builder.Services.AddOllamaChatCompletion(
modelId: "NAME_OF_MODEL", // E.g. "phi3" if phi3 was downloaded as described above.
endpoint: new Uri("YOUR_ENDPOINT"), // E.g. "http://localhost:11434" if Ollama has been started in docker as described above.
serviceId: "SERVICE_ID" // Optional; for targeting specific services within Semantic Kernel
);
builder.Services.AddTransient((serviceProvider)=> {
return new Kernel(serviceProvider);
});
重要
Anthropic に必要な Bedrock チャット完了コネクタは、現在試験段階です。 これを使用するには、 #pragma warning disable SKEXP0070
を追加する必要があります。
using Microsoft.SemanticKernel;
var builder = Host.CreateApplicationBuilder(args);
#pragma warning disable SKEXP0070
builder.Services.AddBedrockChatCompletionService(
modelId: "NAME_OF_MODEL",
bedrockRuntime: amazonBedrockRuntime, // Optional; An instance of IAmazonBedrockRuntime, used to communicate with Azure Bedrock.
serviceId: "SERVICE_ID" // Optional; for targeting specific services within Semantic Kernel
);
builder.Services.AddTransient((serviceProvider)=> {
return new Kernel(serviceProvider);
});
重要
Bedrock チャット完了コネクタは現在試験段階です。 これを使用するには、 #pragma warning disable SKEXP0070
を追加する必要があります。
using Microsoft.SemanticKernel;
var builder = Host.CreateApplicationBuilder(args);
#pragma warning disable SKEXP0070
builder.Services.AddBedrockChatCompletionService(
modelId: "NAME_OF_MODEL",
bedrockRuntime: amazonBedrockRuntime, // Optional; An instance of IAmazonBedrockRuntime, used to communicate with Azure Bedrock.
serviceId: "SERVICE_ID" // Optional; for targeting specific services within Semantic Kernel
);
builder.Services.AddTransient((serviceProvider)=> {
return new Kernel(serviceProvider);
});
重要
ONNX チャット完了コネクタは現在試験段階です。 これを使用するには、 #pragma warning disable SKEXP0070
を追加する必要があります。
using Microsoft.SemanticKernel;
var builder = Host.CreateApplicationBuilder(args);
#pragma warning disable SKEXP0070
builder.Services.AddOnnxRuntimeGenAIChatCompletion(
modelId: "NAME_OF_MODEL", // E.g. phi-3
modelPath: "PATH_ON_DISK", // Path to the model on disk e.g. C:\Repos\huggingface\microsoft\Phi-3-mini-4k-instruct-onnx\cpu_and_mobile\cpu-int4-rtn-block-32
serviceId: "SERVICE_ID", // Optional; for targeting specific services within Semantic Kernel
jsonSerializerOptions: customJsonSerializerOptions // Optional; for providing custom serialization settings for e.g. function argument / result serialization and parsing.
);
builder.Services.AddTransient((serviceProvider)=> {
return new Kernel(serviceProvider);
});
OpenAI チャット入力候補 API (LLM Studio など) をサポートする他の AI サービス プロバイダーの場合は、次のコードを使用して、既存の OpenAI チャット完了コネクタを再利用できます。
重要
OpenAI コネクタでのカスタム エンドポイントの使用は、現在試験段階です。 これを使用するには、 #pragma warning disable SKEXP0010
を追加する必要があります。
using Microsoft.SemanticKernel;
var builder = Host.CreateApplicationBuilder(args);
#pragma warning disable SKEXP0010
builder.Services.AddOpenAIChatCompletion(
modelId: "NAME_OF_MODEL",
apiKey: "API_KEY",
endpoint: new Uri("YOUR_ENDPOINT"), // Used to point to your service
serviceId: "SERVICE_ID", // Optional; for targeting specific services within Semantic Kernel
httpClient: new HttpClient() // Optional; for customizing HTTP client
);
builder.Services.AddTransient((serviceProvider)=> {
return new Kernel(serviceProvider);
});
スタンドアロン インスタンスの作成
最後に、サービスのインスタンスを直接作成して、後でカーネルに追加するか、カーネルまたはサービス プロバイダーに挿入することなく、コードで直接使用することができます。
using Microsoft.SemanticKernel.Connectors.AzureOpenAI;
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
);
using Microsoft.SemanticKernel.Connectors.OpenAI;
OpenAIChatCompletionService chatCompletionService = new (
modelId: "gpt-4",
apiKey: "YOUR_API_KEY",
organization: "YOUR_ORG_ID", // Optional
httpClient: new HttpClient() // Optional; if not provided, the HttpClient from the kernel will be used
);
重要
Mistral チャット完了コネクタは現在試験段階です。 これを使用するには、 #pragma warning disable SKEXP0070
を追加する必要があります。
using Microsoft.SemanticKernel.Connectors.MistralAI;
#pragma warning disable SKEXP0070
MistralAIChatCompletionService chatCompletionService = new (
modelId: "NAME_OF_MODEL",
apiKey: "API_KEY",
endpoint: new Uri("YOUR_ENDPOINT"), // Optional
httpClient: new HttpClient() // Optional; for customizing HTTP client
);
重要
Google チャット完了コネクタは現在試験段階です。 これを使用するには、 #pragma warning disable SKEXP0070
を追加する必要があります。
using Microsoft.SemanticKernel.Connectors.Google;
#pragma warning disable SKEXP0070
GoogleAIGeminiChatCompletionService chatCompletionService = new (
modelId: "NAME_OF_MODEL",
apiKey: "API_KEY",
apiVersion: GoogleAIVersion.V1, // Optional
httpClient: new HttpClient() // Optional; for customizing HTTP client
);
重要
Hugging Face チャット完了コネクタは現在試験段階です。 これを使用するには、 #pragma warning disable SKEXP0070
を追加する必要があります。
using Microsoft.SemanticKernel.Connectors.HuggingFace;
#pragma warning disable SKEXP0070
HuggingFaceChatCompletionService chatCompletionService = new (
model: "NAME_OF_MODEL",
apiKey: "API_KEY",
endpoint: new Uri("YOUR_ENDPOINT") // Optional
);
重要
Azure AI 推論チャット完了コネクタは、現在試験段階です。 これを使用するには、 #pragma warning disable SKEXP0070
を追加する必要があります。
using Microsoft.SemanticKernel.Connectors.AzureAIInference;
#pragma warning disable SKEXP0070
AzureAIInferenceChatCompletionService chatCompletionService = new (
modelId: "YOUR_MODEL_ID",
apiKey: "YOUR_API_KEY",
endpoint: new Uri("YOUR_ENDPOINT"), // Used to point to your service
httpClient: new HttpClient() // Optional; if not provided, the HttpClient from the kernel will be used
);
重要
Ollama チャット完了コネクタは現在試験段階です。 これを使用するには、 #pragma warning disable SKEXP0070
を追加する必要があります。
using Microsoft.SemanticKernel.ChatCompletion;
using OllamaSharp;
#pragma warning disable SKEXP0070
using var ollamaClient = new OllamaApiClient(
uriString: "YOUR_ENDPOINT" // E.g. "http://localhost:11434" if Ollama has been started in docker as described above.
defaultModel: "NAME_OF_MODEL" // E.g. "phi3" if phi3 was downloaded as described above.
);
IChatCompletionService chatCompletionService = ollamaClient.AsChatCompletionService();
重要
Anthropic に必要な Bedrock チャット完了コネクタは、現在試験段階です。 これを使用するには、 #pragma warning disable SKEXP0070
を追加する必要があります。
using Microsoft.SemanticKernel.Connectors.Amazon;
#pragma warning disable SKEXP0070
BedrockChatCompletionService chatCompletionService = new BedrockChatCompletionService(
modelId: "NAME_OF_MODEL",
bedrockRuntime: amazonBedrockRuntime // Optional; An instance of IAmazonBedrockRuntime, used to communicate with Azure Bedrock.
);
重要
Bedrock チャット完了コネクタは現在試験段階です。 これを使用するには、 #pragma warning disable SKEXP0070
を追加する必要があります。
using Microsoft.SemanticKernel.Connectors.Amazon;
#pragma warning disable SKEXP0070
BedrockChatCompletionService chatCompletionService = new BedrockChatCompletionService(
modelId: "NAME_OF_MODEL",
bedrockRuntime: amazonBedrockRuntime // Optional; An instance of IAmazonBedrockRuntime, used to communicate with Azure Bedrock.
);
重要
ONNX チャット完了コネクタは現在試験段階です。 これを使用するには、 #pragma warning disable SKEXP0070
を追加する必要があります。
using Microsoft.SemanticKernel.Connectors.Onnx;
#pragma warning disable SKEXP0070
OnnxRuntimeGenAIChatCompletionService chatCompletionService = new OnnxRuntimeGenAIChatCompletionService(
modelId: "NAME_OF_MODEL", // E.g. phi-3
modelPath: "PATH_ON_DISK", // Path to the model on disk e.g. C:\Repos\huggingface\microsoft\Phi-3-mini-4k-instruct-onnx\cpu_and_mobile\cpu-int4-rtn-block-32
jsonSerializerOptions: customJsonSerializerOptions // Optional; for providing custom serialization settings for e.g. function argument / result serialization and parsing.
);
OpenAI チャット入力候補 API (LLM Studio など) をサポートする他の AI サービス プロバイダーの場合は、次のコードを使用して、既存の OpenAI チャット完了コネクタを再利用できます。
重要
OpenAI コネクタでのカスタム エンドポイントの使用は、現在試験段階です。 これを使用するには、 #pragma warning disable SKEXP0010
を追加する必要があります。
using Microsoft.SemanticKernel.Connectors.OpenAI;
#pragma warning disable SKEXP0010
OpenAIChatCompletionService chatCompletionService = new (
modelId: "gpt-4",
apiKey: "YOUR_API_KEY",
organization: "YOUR_ORG_ID", // Optional
endpoint: new Uri("YOUR_ENDPOINT"), // Used to point to your service
httpClient: new HttpClient() // Optional; if not provided, the HttpClient from the kernel will be used
);
チャット完了サービスを作成するには、必要なモジュールをインストールしてインポートし、サービスのインスタンスを作成する必要があります。 各 AI サービス プロバイダーのチャット完了サービスをインストールして作成する手順を次に示します。
必要なパッケージのインストール
セマンティック カーネル パッケージには、Azure OpenAI を使用するために必要なすべてのパッケージが付属しています。 Azure OpenAI を使用するために追加のパッケージは必要ありません。
セマンティック カーネル パッケージには、OpenAI を使用するために必要なすべてのパッケージが付属しています。 OpenAI を使用するために追加のパッケージは必要ありません。
pip install semantic-kernel[azure]
pip install semantic-kernel[anthropic]
pip install semantic-kernel[aws]
pip install semantic-kernel[google]
pip install semantic-kernel[google]
pip install semantic-kernel[mistralai]
pip install semantic-kernel[ollama]
pip install semantic-kernel[onnx]
チャット完了サービスの作成
ヒント
OpenAIChatCompletion
、AzureChatCompletion
、およびAzureAIInferenceChatCompletion
サービスを使用すると、instruction_role
キーワード引数を構成できます。 このパラメーターは、システム命令をモデルに提示する方法を制御し、 "system"
または "developer"
を受け入れます。 推論モデルを使用する場合は、 instruction_role="developer"
を設定する必要があります。
ChatHistory
で見つかったsystem
ロール メッセージは、要求がモデルに送信される前に、developer
ロールに自動的にマップされます。
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
chat_completion_service = AzureChatCompletion(
deployment_name="my-deployment",
api_key="my-api-key",
endpoint="my-api-endpoint", # Used to point to your service
service_id="my-service-id", # Optional; for targeting specific services within Semantic Kernel
)
# You can do the following if you have set the necessary environment variables or created a .env file
chat_completion_service = AzureChatCompletion(service_id="my-service-id")
注
サービスでは、Microsoft Entra 認証 もサポートされています。 API キーを指定しない場合、サービスは Entra トークンを使用して認証を試みます。
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
chat_completion_service = OpenAIChatCompletion(
ai_model_id="my-deployment",
api_key="my-api-key",
service_id="my-service-id", # Optional; for targeting specific services within Semantic Kernel
)
# You can do the following if you have set the necessary environment variables or created a .env file
chat_completion_service = OpenAIChatCompletion(service_id="my-service-id")
from semantic_kernel.connectors.ai.azure_ai_inference import AzureAIInferenceChatCompletion
chat_completion_service = AzureAIInferenceChatCompletion(
ai_model_id="my-deployment",
api_key="my-api-key",
endpoint="my-api-endpoint", # Used to point to your service
service_id="my-service-id", # Optional; for targeting specific services within Semantic Kernel
)
# You can do the following if you have set the necessary environment variables or created a .env file
chat_completion_service = AzureAIInferenceChatCompletion(ai_model_id="my-deployment", service_id="my-service-id")
# You can also use an Azure OpenAI deployment with the Azure AI Inference service
from azure.ai.inference.aio import ChatCompletionsClient
from azure.identity.aio import DefaultAzureCredential
chat_completion_service = AzureAIInferenceChatCompletion(
ai_model_id="my-deployment",
client=ChatCompletionsClient(
endpoint=f"{str(endpoint).strip('/')}/openai/deployments/{deployment_name}",
credential=DefaultAzureCredential(),
credential_scopes=["https://cognitiveservices.azure.com/.default"],
),
)
注
サービスでは、Microsoft Entra 認証 もサポートされています。 API キーを指定しない場合、サービスは Entra トークンを使用して認証を試みます。
from semantic_kernel.connectors.ai.anthropic import AnthropicChatCompletion
chat_completion_service = AnthropicChatCompletion(
chat_model_id="model-id",
api_key="my-api-key",
service_id="my-service-id", # Optional; for targeting specific services within Semantic Kernel
)
from semantic_kernel.connectors.ai.bedrock import BedrockChatCompletion
chat_completion_service = BedrockChatCompletion(
model_id="model-id",
service_id="my-service-id", # Optional; for targeting specific services within Semantic Kernel
)
注
Amazon Bedrock は API キーを受け入れていません。 環境を構成するには、この ガイドの に従ってください。
from semantic_kernel.connectors.ai.google.google_ai import GoogleAIChatCompletion
chat_completion_service = GoogleAIChatCompletion(
gemini_model_id="model-id",
api_key="my-api-key",
service_id="my-service-id", # Optional; for targeting specific services within Semantic Kernel
)
ヒント
ユーザーは、Google AI Studio または Google Vertex プラットフォームを介して Google の Gemini モデルにアクセスできます。 環境を構成するには、この ガイドの に従ってください。
from semantic_kernel.connectors.ai.google.vertex_ai import VertexAIChatCompletion
chat_completion_service = VertexAIChatCompletion(
project_id="my-project-id",
gemini_model_id="model-id",
service_id="my-service-id", # Optional; for targeting specific services within Semantic Kernel
)
ヒント
ユーザーは、Google AI Studio または Google Vertex プラットフォームを介して Google の Gemini モデルにアクセスできます。 環境を構成するには、この ガイドの に従ってください。
from semantic_kernel.connectors.ai.mistral_ai import MistralAIChatCompletion
chat_completion_service = MistralAIChatCompletion(
ai_model_id="model-id",
api_key="my-api-key",
service_id="my-service-id", # Optional; for targeting specific services within Semantic Kernel
)
from semantic_kernel.connectors.ai.ollama import OllamaChatCompletion
chat_completion_service = OllamaChatCompletion(
ai_model_id="model-id",
service_id="my-service-id", # Optional; for targeting specific services within Semantic Kernel
)
ヒント
Ollamaの詳細について知り、必要なソフトウェアをからでダウンロードしてください。
from semantic_kernel.connectors.ai.onnx import OnnxGenAIChatCompletion
chat_completion_service = OnnxGenAIChatCompletion(
template="phi3v",
ai_model_path="model-path",
service_id="my-service-id", # Optional; for targeting specific services within Semantic Kernel
)
すぐに完了サービスの使用を開始するか、チャット完了サービスをカーネルに追加できます。 次のコードを使用して、カーネルにサービスを追加できます。
from semantic_kernel import Kernel
# Initialize the kernel
kernel = Kernel()
# Add the chat completion service created above to the kernel
kernel.add_service(chat_completion_service)
チャット完了サービスのインスタンスを直接作成し、カーネルに追加するか、カーネルに挿入せずにコード内で直接使用することができます。 次のコードは、チャット完了サービスを作成し、カーネルに追加する方法を示しています。
import com.azure.ai.openai.OpenAIAsyncClient;
import com.azure.ai.openai.OpenAIClientBuilder;
import com.microsoft.semantickernel.Kernel;
import com.microsoft.semantickernel.services.chatcompletion.ChatCompletionService;
// Create the client
OpenAIAsyncClient client = new OpenAIClientBuilder()
.credential(azureOpenAIClientCredentials)
.endpoint(azureOpenAIClientEndpoint)
.buildAsyncClient();
// Create the chat completion service
ChatCompletionService openAIChatCompletion = OpenAIChatCompletion.builder()
.withOpenAIAsyncClient(client)
.withModelId(modelId)
.build();
// Initialize the kernel
Kernel kernel = Kernel.builder()
.withAIService(ChatCompletionService.class, openAIChatCompletion)
.build();
import com.azure.ai.openai.OpenAIAsyncClient;
import com.azure.ai.openai.OpenAIClientBuilder;
import com.microsoft.semantickernel.Kernel;
import com.microsoft.semantickernel.services.chatcompletion.ChatCompletionService;
// Create the client
OpenAIAsyncClient client = new OpenAIClientBuilder()
.credential(openAIClientCredentials)
.buildAsyncClient();
// Create the chat completion service
ChatCompletionService openAIChatCompletion = OpenAIChatCompletion.builder()
.withOpenAIAsyncClient(client)
.withModelId(modelId)
.build();
// Initialize the kernel
Kernel kernel = Kernel.builder()
.withAIService(ChatCompletionService.class, openAIChatCompletion)
.build();
チャット完了サービスの取得
チャット完了サービスをカーネルに追加したら、get サービス メソッドを使用してそれらを取得できます。 カーネルからチャット完了サービスを取得する方法の例を次に示します。
var chatCompletionService = kernel.GetRequiredService<IChatCompletionService>();
from semantic_kernel.connectors.ai.chat_completion_client_base import ChatCompletionClientBase
# Retrieve the chat completion service by type
chat_completion_service = kernel.get_service(type=ChatCompletionClientBase)
# Retrieve the chat completion service by id
chat_completion_service = kernel.get_service(service_id="my-service-id")
# Retrieve the default inference settings
execution_settings = kernel.get_prompt_execution_settings_from_service_id("my-service-id")
ChatCompletionService chatCompletionService = kernel.getService(ChatCompletionService.class);
ヒント
カーネルで他のサービスを使用する必要がない場合は、チャット完了サービスをカーネルに追加する必要はありません。 チャット完了サービスは、コード内で直接使用できます。
チャット完了サービスの使用
チャット完了サービスが完成したら、それを使用して AI エージェントからの応答を生成できます。 チャット完了サービスを使用するには、主に次の 2 つの方法があります。
-
ストリーミング以外の: サービスが応答全体を生成するのを待ってから、ユーザーに返します。
-
ストリーミング: 応答の個々の部分が生成されると、ユーザーに返されます。
開始する前に、カーネルにサービスを登録していない場合は、チャット完了サービスを使用する実行設定インスタンスを手動で作成する必要があります。
from semantic_kernel.connectors.ai.open_ai import OpenAIChatPromptExecutionSettings
execution_settings = OpenAIChatPromptExecutionSettings()
from semantic_kernel.connectors.ai.open_ai import OpenAIChatPromptExecutionSettings
execution_settings = OpenAIChatPromptExecutionSettings()
from semantic_kernel.connectors.ai.azure_ai_inference import AzureAIInferenceChatPromptExecutionSettings
execution_settings = AzureAIInferenceChatPromptExecutionSettings()
from semantic_kernel.connectors.ai.anthropic import AnthropicChatPromptExecutionSettings
execution_settings = AnthropicChatPromptExecutionSettings()
from semantic_kernel.connectors.ai.bedrock import BedrockChatPromptExecutionSettings
execution_settings = BedrockChatPromptExecutionSettings()
from semantic_kernel.connectors.ai.google.google_ai import GoogleAIChatPromptExecutionSettings
execution_settings = GoogleAIChatPromptExecutionSettings()
from semantic_kernel.connectors.ai.google.vertex_ai import VertexAIChatPromptExecutionSettings
execution_settings = VertexAIChatPromptExecutionSettings()
from semantic_kernel.connectors.ai.mistral_ai import MistralAIChatPromptExecutionSettings
execution_settings = MistralAIChatPromptExecutionSettings()
from semantic_kernel.connectors.ai.ollama import OllamaChatPromptExecutionSettings
execution_settings = OllamaChatPromptExecutionSettings()
from semantic_kernel.connectors.ai.onnx import OnnxGenAIPromptExecutionSettings
execution_settings = OnnxGenAIPromptExecutionSettings()
チャット完了サービスを使用して応答を生成する 2 つの方法を次に示します。
非ストリーミング チャットの完了
ストリーミング以外のチャットの完了を使用するには、次のコードを使用して、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_service.get_chat_message_content(
chat_history=history,
settings=execution_settings,
)
ChatHistory history = new ChatHistory();
history.addUserMessage("Hello, how are you?");
InvocationContext optionalInvocationContext = null;
List<ChatMessageContent<?>> response = chatCompletionService.getChatMessageContentsAsync(
history,
kernel,
optionalInvocationContext
);
ストリーミング チャットの完了
ストリーミング チャットの完了を使用するには、次のコードを使用して、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_service.get_streaming_chat_message_content(
chat_history=history,
settings=execution_settings,
)
async for chunk in response:
print(chunk, end="")
注
Java 用セマンティック カーネルでは、ストリーミング応答モデルはサポートされていません。
次のステップ
セマンティック カーネル プロジェクトにチャット完了サービスを追加したので、AI エージェントとの会話の作成を開始できます。 チャット完了サービスの使用の詳細については、次の記事を参照してください。