0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Google Colaboratoryの環境でPythonを使ってGeminiを利用するデモ

Last updated at Posted at 2025-06-06

1. はじめに

AIのAPIは大抵お金がかかります。AIとの通信自体はAPIを使うだけだと思うのでさほど難しくはないのでしょうが、大抵の場合は利用前にクレカ登録したり従量課金したりなどのハードルがあり、特にプロダクトに使う予定がないのであればAIのAPIを使うのは憚られました。
しかし最近、全く無料で(限定的な量ながら)GeminiのAPIを使えることを知り、Colaboratoryで利用してみたので今回は忘備録も兼ねてまとめてみようと思います。

目次

2. APIキーの取得

Google AI Studioというサービスのページでダッシュボードにアクセスします。以下のような画面です。そこで、APIキーを生成します。

image.png

APIキーをコピーしてクリップボードに保持していきましょう。

3. Colaboratoryでキーの設定

Colaboratoryの画面を開くと、左側のメニュー一覧に鍵マークが見えます。そのマークをクリックすると、キーを設定する画面が開けるので、それに値を設定してください。

image.png

セルからアクセスして呼び出したいので、ノートブックアクセスを有効にしておきましょう。

4. APIのよびだし

colaboratoryの環境に、生成AIを使えるようにするライブラリーをインストールします。セルの中でpip installしてください。

!pip install -q -U google-generativeai

import google.generativeai as genai
from google.colab import userdata

# gemini settings
GOOGLE_API_EKY = userdata.get("GOOGLE_API_KEY")
genai.configure(api_key=GOOGLE_API_EKY)
model = genai.GenerativeModel("gemini-1.5-flash")

# invoke gemini api
instruction = 'Please describe what is generative ai?'
response = model.generate_content(instruction)
print(f'e.g.: {response.text}')

Google API Keyを環境変数から取得して、それをgoogle.generativeaiに設定します。今回アクセスするのはgemini-1.5-flashというモデルです。
2025年6月現在、これは特にクレカの登録など必要なく無料で使えるので、試しに使ってみたいときに便利です。

生成AIに、プロンプトに基づいて反応してほしい時は、model.generate_contentメソッドを用います。
文章で説明されていることを想定しているので、レスポンスからtextプロパティを取得してprintしました。

5. Geminiを使って例文を作る

以下は、TOEFL出る単5000から単語を抜き出したもので、これらの単語をランダムに出しながら、もし例文が欲しい場合はGeminiを用いてその場で新たな例文を生成するような形にしています。

import random
import time
import google.generativeai as genai
from google.colab import userdata

# gemini settings
GOOGLE_API_EKY = userdata.get("GOOGLE_API_KEY")
genai.configure(api_key=GOOGLE_API_EKY)
model = genai.GenerativeModel("gemini-1.5-flash")

# vocabulary table
vocabulary_dic = {
  "postulate": "仮定する、主張する", "sleek": "つやつやした、なめらかな", "intrigue": "~の興味を引く",
  "implausible": "信じられない、本当らしくない", "supplant": "~にとって代わる", "diffuse": "~を拡散させる、広める",
  "emanate": "~を発する、出てくる", "discrepancy": "矛盾、食い違い", "elucidate": "~をはっきりさせる、説明する",
  "sturdy": "頑丈な、丈夫な", "commission": "~に委託する、依頼する", "manifestation": "表明、兆候",
  "cast about": "探し回る", "subsidiary": "付随的な、副次的な", "denote": "~を示す、~の印である",
  "repudiate": "~を拒否する、拒絶する", "pore": "v: じっくりみる、熟考する\nn:毛穴、気孔", "mingle with": "~に声をかけて回る",
  "subterfuge": "ごまかし、策略", "prohibitive": "(購入できないほど)法外な、ひどく高い", "forestall": "~を未然に防ぐ",
  "tacit": "暗黙の、無言の", "succulent": "水気の多い", "foul": "~を汚す", "intermittently": "断続的に",
  "compound": "v:(困難などの)度合いを増す、悪化させる\nn:混合物", "constellation": "群れ、集まり", "outstanding": "未解決の、未払の、極めて優れた",
}

local_dic = vocabulary_dic.copy()

# helper functions
def to_next_roop(local_dic, eng):
  time.sleep(0.25)
  del local_dic[eng]
  print_dashed_line()

def print_dashed_line():
  print()
  print("-" * 65)
  print()

# start the process
print("Starting...")
print("If you suspend the test, please print 'e'")
print()

ai_availability = True

while True:
  vocabulary_list = list(local_dic.items())
  if len(vocabulary_list) == 0:
    print("All words have been reviewed!")
    break

  word = random.choice(vocabulary_list)
  eng, jpn = word[0], word[1]

  print(eng)
  print("Are you sure the meaning of this word? If so, just press the enter key. Otherwise, print 'n'")
  res = input().strip().lower()
  print()

  if res == "n":
    print("This is the answer of the problem!")
    print(jpn)
    print()

    if not ai_availability:
      to_next_roop(local_dic, eng)
      continue

    print("Do you want to read a generated example of this word? If so, input 'a'. Otherwise, please just press the enter key.")

    res = input().strip().lower()

    if res != "a":
      to_next_roop(local_dic, eng)
      continue

    try:
      instruction = f'Please write an example sentence using this word: {eng}'
      response = model.generate_content(instruction)
      print(f'e.g.: {response.text}')
    except:
      ai_availability = False
      print("AI is now unavailable. You may reach the usage limitation for gemini free plan.")
    print()

  elif res == "e":
    print("Terminate the test!")
    break

  else:
    print()

  to_next_roop(local_dic, eng)

6. おわりに

Google Colaboratoryを使ってみると、かなりAIのAPIのよびだしが楽で驚きました。
ただ、本格的にAIを使うとすると、セキュリティの問題であるとか、追加的な学習・チューニングであるとかが必要であると聞くので、もっと奥が深いものだと思います。

ただ、自分で使い方を考えて実装まで持っていけたのはよい経験になりました。

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?