0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

C#でGeminiを使うサンプルコード

Last updated at Posted at 2025-04-05

準備

  1. APIキーを作る
  2. Microsoft.SemanticKernel.Connectors.Google をNugetする.
    プレリリースかもしれないのを注意しよう

注意事項

APIキーは直書きしないほうがいいよ
settingやchatServiceにアクセスするときは警告が出るかもしれないので,

#pragma warning disable SKEXP0070
#pragma warning restore SKEXP0070

で囲ってね

コード

クラス定義例

using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.Google;
using System.Diagnostics;
public static class Gemini1p5f8b
{
    static string geminiModel = "gemini-1.5-flash-8b"; // コスパ良いよこれ
    static string gemini_api_key = "事前につくってね";
#pragma warning disable SKEXP0070
    public static GoogleAIGeminiChatCompletionService chatService = new GoogleAIGeminiChatCompletionService(modelId: geminiModel, apiKey: gemini_api_key);
    public static GeminiPromptExecutionSettings settings = new()
    {
        MaxTokens = 50,
        Temperature = 0.7
    };
#pragma warning restore SKEXP0070
    public static async Task<ChatMessageContent> Genext(this ChatHistory hist) => await chatService.GetChatMessageContentAsync(hist, settings);
}

例の使用例

public static async Task Test()
{
    var chatHistory = new ChatHistory();
    chatHistory.AddUserMessage(new ChatMessageContentItemCollection
    {
         new TextContent("この画像を基に,お話を創作してください."),
         new ImageContent(File.ReadAllBytes(@"C:\Users\omae\Desktop\test.png"),"image/png")
    });
    var reply = await chatHistory.Genext();
    chatHistory.Add(reply);

    foreach(var hist in chatHistory)
    {
        Debug.Print($"{hist.Role}: {hist.Content}");
    }
}

リトライ処理追加版(おまけ)

    public static async Task<ChatMessageContent> GenextWithRetry(this ChatHistory hist, TimeSpan timeout)
    {
        const int retryMax = 4;
        int tryCount = 0;
        while (tryCount++ < retryMax)
        {
            using (var cts = new CancellationTokenSource(timeout))
            {
                try
                {
                    ChatMessageContent generated = await Genext(hist).WaitAsync(cts.Token);
                    ResultCheck(generated);
                    return generated;
                }
                catch (OperationCanceledException)
                {
                    Debug.Print("Timeout occurred, retrying...");
                }
                catch (Exception ex)
                {
                    Debug.Print($"Error occurred: {ex.Message}, retrying...");
                }
            }
#pragma warning disable SKEXP0070
            settings.Temperature = Random.Shared.NextSingle() * 0.5f + 0.6f;
#pragma warning restore SKEXP0070
        }
        throw new Exception("自主的リトライ上限に達しました");
        void ResultCheck(ChatMessageContent result)
        {
            if (result.Content == "") throw new Exception("何も生成してません");
        }
    }

参考にさせて頂いた記事

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?