2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Gemini APIを Semantic Kernel で利用してみた【サンプルコード】

Last updated at Posted at 2024-08-25

前提

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}");
}
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?