準備
- APIキーを作る
- 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("何も生成してません");
}
}
参考にさせて頂いた記事