💎
RubyからGemini(1.5 Pro)を利用する
Google Cloud Vertex AIのGemini APIをRuby(on Rails)から使うメモ。
前提
- Ruby 3.3.3
 - Google CloudプロジェクトマネコンよりVertex AI GeminiのAPIを有効化していること
 - Gemini 1.5 Proを利用する
 
RubyからGeminiのAPIを叩く
SDKはない
チュートリアルを見る限り、RubyのSDKは存在しないと思われる。
そのため、SDKを介さずにAPIリクエストを組み立てる。
上記に次のようなHTTPリクエストする例が載っているため参考にする。
MODEL_ID="gemini-1.5-pro-001"
PROJECT_ID="YOUR_PROJECT_ID"
curl \
  -X POST \
  -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
  -H "Content-Type: application/json" \
  https://us-central1-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/us-central1/publishers/google/models/${MODEL_ID}:streamGenerateContent -d \
  $'{
    "contents": {
      "role": "user",
      "parts": [
        {
        "fileData": {
          "mimeType": "image/png",
          "fileUri": "gs://generativeai-downloads/images/scones.jpg"
          }
        },
        {
          "text": "Describe this picture."
        }
      ]
    }
  }'
クレデンシャルの取得
今回はアクセストークンの取得にアプリケーションデフォルトクレデンシャル(ADC)を使用する。
ローカル環境なら、
gcloud auth application-default login
でADCをセットできる。
リージョン
Geminiは東京リージョン( asia-northeast1 )を使うことができる。
パラメータ
渡せるパラメータは次に掲載されている。
よく使いそうなのは
- max_output_token
 - temperature
 
また、 response_mime_type: "application/json" を指定することでJSON出力にできるので、これも押さえておくとよさそう。
コード
以上より、以下のRubyコードでGemini 1.5 ProのAPIを叩くことができた。
PROJECT_ID = "your-project-id"
LOCATION = "asia-northeast1".freeze
MODEL = "gemini-1.5-pro-001".freeze
API_URL = "https://#{LOCATION}-aiplatform.googleapis.com/v1/projects/#{PROJECT_ID}/locations/#{LOCATION}/publishers/google/models/#{MODEL}:generateContent".freeze
TEMPERATURE = 0.0
MAX_TOKENS = 512
# アクセストークンの取得にADC(アプリケーションデフォルトクレデンシャル)を使用
credentials = Google::Auth.get_application_default
access_token = credentials.fetch_access_token!["access_token"]
uri = URI(API_URL)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri.request_uri)
request["Authorization"] = "Bearer #{access_token}"
request["Content-Type"] = "application/json; charset=utf-8"
request.body = {
  contents: {
    role: "user",
    parts: [
      {
        text: "こんにちは"
      }
    ],
  },
  generation_config: {
    temperature: TEMPERATURE,
    max_output_tokens: MAX_TOKENS,
    response_mime_type: "application/json" # JSON
  }
}.to_json
response = http.request(request)
if response.code.to_i >= 400
  raise "HTTP Request failed with status code: #{response.code} body: #{response.body}"
end
parsed_body = JSON.parse(response.body)
puts parsed_body["candidates"][0]["content"]["parts"][0]["text"]
参考
Discussion