Apps Script公式リファレンス: Apps Script Reference |障害・課題追跡: IssueTracker |Google Workspace: Status Dashboard - Summary

2024年5月31日金曜日

Gemini APIでsafetySettingsを指定したい - Adjust safetySettings in Gemini API


Gemini APIを利用しているときに以下のエラーが出て回答を得られないケースがありました。
I encountered the following error while using the Gemini API and was unable to obtain a response in some cases.

TypeError: Cannot read properties of undefined (reading 'parts') 


原因を探っていたところ、safetySettings が関係しているようでした。
While investigating the cause, I found that safetySettings seems to be related.


今回はGemini APIでsafetySettings の変更を試したコードです。
This time, I tried using code to change the safety settings in the Gemini API.


Safety settingsについての詳細は以下の公式ドキュメントを確認してください。
Please refer to the official documentation below for more details on Safety settings.

Safety settings



Google AI Studioで設定する場合
When setting up in Google AI Studio.


①create new prompt > Chat prompt > ②Safety settings > ③Run safety settings



Apps Script

GeminiのAPI keyはスクリプト プロパティにapiKeyとして保存しておきます。
Store the Gemini API key in a script property named 'apiKey'.
以下のコードはおそらくエラーを出します。
The following code will likely produce an error.


Code.gs
function runGeminiApi() {
const text = "examples of unsafe words";

const payload = {
"contents": [{
"parts":[{
"text": text
}]
}],
"safetySettings": [
{
"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
"threshold": "BLOCK_LOW_AND_ABOVE"
},
{
"category": "HARM_CATEGORY_HATE_SPEECH",
"threshold": "BLOCK_LOW_AND_ABOVE"
},
{
"category": "HARM_CATEGORY_HARASSMENT",
"threshold": "BLOCK_LOW_AND_ABOVE"
},
{
"category": "HARM_CATEGORY_DANGEROUS_CONTENT",
"threshold": "BLOCK_LOW_AND_ABOVE"
}
]
};

const options = {
"method": "POST",
"headers": {
"x-goog-api-key": getProp("apiKeyGemini"),
"Content-Type": "application/json"
},
"payload": JSON.stringify(payload)
};

const url = "https://generativelanguage.googleapis.com/v1/models/gemini-pro:generateContent";
const response = UrlFetchApp.fetch(url, options);
Logger.log(response);
const responseText= JSON.parse(response).candidates[0].content.parts[0].text;
return responseText;
}

function getProp(key) {
return PropertiesService.getScriptProperties().getProperty(key);
}


実行ログ - Execution log
16:13:39
お知らせ
実行開始
16:13:44
情報
{ "candidates": [ { "finishReason": "SAFETY", "index": 0, "safetyRatings": [ { "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "probability": "MEDIUM" }, { "category": "HARM_CATEGORY_HATE_SPEECH", "probability": "NEGLIGIBLE" }, { "category": "HARM_CATEGORY_HARASSMENT", "probability": "LOW" }, { "category": "HARM_CATEGORY_DANGEROUS_CONTENT", "probability": "LOW" } ] } ], "usageMetadata": { "promptTokenCount": 4, "totalTokenCount": 4 } }
16:13:44
エラー
TypeError: Cannot read properties of undefined (reading 'parts')

probabilityにMEDIUMやLOWが含まれているため、以下の箇所で content.parts[0].text が存在せずエラーとなっています。
The error occurred because the "probability" field contained values like "MEDIUM" or "LOW," and the "content.parts[0].text" did not exist.

const responseText= JSON.parse(response).candidates[0].content.parts[0].text;


このエラーを回避するには、Code.gs内の "threshold": "BLOCK_LOW_AND_ABOVE" で、BLOCK_LOW_AND_ABOVE を BLOCK_ONLY_HIGH か BLOCK_NONE に変更します。
To avoid this error, change BLOCK_LOW_AND_ABOVE to BLOCK_ONLY_HIGH or BLOCK_NONE in Code.gs.


Tips


HarmBlockThreshold

https://ai.google.dev/api/rest/v1/SafetySetting#harmblockthreshold
HARM_BLOCK_THRESHOLD_UNSPECIFIED
BLOCK_LOW_AND_ABOVE
BLOCK_MEDIUM_AND_ABOVE
BLOCK_ONLY_HIGH
BLOCK_NONE


Reference

GeminiのAPIをApps Scriptで利用したい - Using Gemini API in Apps Script

Safety settings

HarmBlockThreshold

Latest post

Google Apps Scriptの障害時はIssueTrackerを見てみる - Incidents for Apps Script are reported on Issue Tracker

IssueTracker > Apps Script issues https://issuetracker.google.com/savedsearches/566234 Google Apps Scriptの障害時は IssueTracker に課題が上がっていることが...