前提
Google AI StudioのGemini APIのページのGet API Keyで、APIキーを発行・取得済みであること
手順
コンソールアプリケーションの作成
dotnet new console -n GeminiSemanticKernelConsoleApp
プロジェクトディレクトリに移動
cd GeminiSemanticKernelConsoleApp
必要なパッケージのインストール
dotnet add package Microsoft.SemanticKernel
dotnet add package Microsoft.SemanticKernel.Connectors.Google --prerelease
Program.cs
を以下に変更
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.OpenAI;
Console.WriteLine(
"============= Google AI - Gemini Chat Completion =============");
string geminiApiKey = "APIキーをここに記述";
string geminiModelId = "gemini-1.5-flash";
if (geminiApiKey is null || geminiModelId is null)
{
Console.WriteLine("Gemini credentials not found. Skipping example.");
return;
}
#pragma warning disable SKEXP0070
Kernel kernel = Kernel.CreateBuilder()
.AddGoogleAIGeminiChatCompletion(
modelId: geminiModelId,
apiKey: geminiApiKey)
.Build();
#pragma warning restore SKEXP0070
Console.WriteLine("======== Simple Chat ========");
var systemMessage = """
You are an expert in finance and economics.
""";
var chatHistory = new ChatHistory(systemMessage);
var chat = kernel.GetRequiredService<IChatCompletionService>();
OpenAIPromptExecutionSettings settings = new()
{
MaxTokens = 100,
};
while (true)
{
// your message
Console.Write("user: ");
var input = Console.ReadLine() ?? "";
if (input == "exit") { break; }
chatHistory.AddUserMessage(input);
// bot assistant message
var reply = await chat.GetChatMessageContentAsync(chatHistory, settings);
chatHistory.Add(reply);
Console.WriteLine($"{reply.Role}: {reply.Content}");
}