Gemini APIは、かつては pip install google-generativeai で入れる google.generativeai パッケージで使いましたが、2024年末に pip install google-genai で入れる新しいパッケージが出ました。また、Gemini APIはOpenAIとの互換性があり(OpenAI compatibility)、OpenAIのAPIを使うの方法もそのまま使えます。
まずは、APIキー を発行してもらいます。APIキーはコードに直接書き込むこともできますが、次のようにして環境変数に登録しておくと便利です。
export GOOGLE_API_KEY="..."
次に、Gemini API quickstart に従って、Pythonパッケージをインストールします。
pip install --upgrade google-genai
使えるモデル一覧:
from google import genai
client = genai.Client() # 環境変数にAPIキーが設定されていればこれでいい
# client = genai.Client(api_key="...") # あるいは直接指定してもいい
for model in client.models.list():
print(model.name)
簡単な使い方は次の通りです。
from google import genai
client = genai.Client()
response = client.models.generate_content(
model="gemini-2.5-pro",
contents="ここにプロンプトを書く"
)
print(response.text)
より実用的な使い方は次の通りです。思考モデルの場合は thinking_budget が指定できますが、その範囲はモデルによって違います。
from google import genai
from google.genai import types
client = genai.Client()
chat = client.chats.create(
model="gemini-2.5-pro",
config=types.GenerateContentConfig(
temperature=0, # 0-2
# thinking_config=types.ThinkingConfig(thinking_budget=32768) # 128-32768
# thinking_config=types.ThinkingConfig(thinking_budget=-1) # dynamic thinking (default)
)
)
prompt = '''
最初のプロンプト
'''
response = chat.send_message_stream(prompt.strip())
for chunk in response:
print(chunk.text, end="")
prompt = '''
次のプロンプト
'''
response = chat.send_message_stream(prompt.strip())
for chunk in response:
print(chunk.text, end="")
会話履歴は次のようにして取得できます。
for message in chat.get_history():
print(f'role - {message.role}', end=": ")
print(message.parts[0].text)