0
0

Cloud FunctionsでGemini APIを呼び出してみた

Posted at

こんにちは。
業務において、HTTPリクエストをトリガーにGoogle Cloudのサーバレスクラウドコンピューティング「Cloud Functions」上のPythonファイルを実行し、Geminiにプロンプトを投げ、回答をレスポンスするということをおこないました。
備忘録として、実装を簡単にまとめてみようと思います。

Cloud Functionsの概要

Cloud Functionsとは、Google Cloudが提供するサーバレスのクラウドコンピューティングサービスのひとつです。
サーバレスとは、サーバーが必要ないという意味ではなく、サーバーの構築や保守などのメンテナンスが不要という意味です。
指定したイベントをトリガーにサーバーを意識することなく、クラウド上でプログラムを実行できる便利なサービスです。
トリガーとして指定できるものは多数ありますが(Pub/Sub・Cloud Firebaseなど)、今回は外部サービスからのHTTPリクエストをトリガーに指定します。
類似サービスとして、AWSの「Lambda」などがあります。

実装

今回は下記のように実装をしました。

main.py
import functions_framework
import vertexai
from vertexai.generative_models import GenerativeModel, ChatSession

@functions_framework.http
def gemini(request):
    project_id = "gemini-try"
    region = "asia-northeast1"
    data = request.get_json()
    prompt = ""
    if data.get('prompt') is not None:
        prompt = data.get('prompt')

    if prompt == "":
        return 'NG'

    temperature = 0
    if data.get('temperature') is not None:
        temperature = data.get('temperature')

    max_token = 100
    if data.get('max_token') is not None:
        max_token = data.get('max_token')
        max_token = int(max_token)
        
    vertexai.init(project=project_id, location=region)

    config = {"max_output_tokens": max_token, "temperature": temperature}
    system_instruction = "あなたは5歳の男の子です。"
    model = GenerativeModel(
        model_name="gemini-1.5-flash-001",
        system_instruction = [
            system_instruction
        ])

    response = model.generate_content(prompt, generation_config=config)

    return response.text
requirements.txt
functions-framework==3.*
google-cloud-aiplatform==1.51.0 

temperatureとは、生成AIの回答の創造性・ランダム性の指標です。この数値が高いほど、創造性に富んだ回答を出力してくれます。
今回、temperature・max_output_tokenはリクエストのボディーから受け取っておりますが、Cloud Functions上のpyファイルにて設定することも可能です。

System instructionsとは

System instructionsとはGeminiの振る舞いや役割を設定するための指示や制約を定義するものです。
今回はGeminiに「5歳の男の子」というペルソナを与えました。この指示を与えることで、5歳の男の子として回答を返してくれます。

まとめ

APIを介して生成AIモデルの回答を取得できるので、これからますます様々なサービスが生まれてきそうですね。
今回はPythonを採用しましたが、GoやNode.jsでも実装できるそうです

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