Gemini API クイックスタート — Python/TypeScriptで始める
Gemini API で最初のレスポンスを受け取るまでは、実のところ数分です。迷うとすればAPIキーの取得先とSDKの選び方くらいで、詰まるのはその先——ストリーミングやエラー処理を足していく段階になります。
Python と TypeScript/JavaScript の両方で、キーの取得から最初のリクエスト、そして実用に耐える形に整えるまでを順番に進めます。
前提条件
本ガイドを進める前に、以下の準備が必要です:
- Googleアカウント
- APIキー(Google AI Studioから取得可能)
- Python 3.9以上またはNode.js 16以上
- テキストエディタまたはIDE
ステップ1:APIキーの取得
Google AI Studioからのキー取得
- aistudio.google.comにアクセス
- 左側メニューから「APIキー」を選択
- 「新しいAPIキーを作成」をクリック
- プロジェクトを選択(または新規作成)
- 生成されたキーをコピーして安全に保管
キーの環境変数設定
取得したAPIキーを環境変数に設定することで、ソースコード内にキーを埋め込まずに管理できます。
Linux/Mac:
export GEMINI_API_KEY="your-api-key-here"Windows (PowerShell):
$env:GEMINI_API_KEY="your-api-key-here"Python環境変数設定(.envファイル):
GEMINI_API_KEY=your-api-key-here
ステップ2:Python SDKのセットアップ
インストール
pip install google-genaiこのコマンドで、Google GenAI SDK for Pythonがインストールされます。
必要なライブラリのインポート
from google import genai
import osステップ3:Python での基本実装
シンプルなテキスト生成
最も基本的な例として、テキストプロンプトに対する応答を生成します:
from google import genai
import os
# APIキーの設定
api_key = os.getenv("GEMINI_API_KEY")
client = genai.Client(api_key=api_key)
# テキスト生成
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="日本の首都は?"
)
print(response.text)実行すると、AIから「日本の首都は東京です。」といった応答が返されます。
モデルの選択
複数のモデルから選択できます:
# 高精度が必要な場合
response = client.models.generate_content(
model="gemini-2.5-pro",
contents="複雑なコード設計について相談したい"
)
# 高速レスポンスが必要な場合
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="簡単な質問です"
)ストリーミング対応
長い応答を部分ごとに取得する場合、ストリーミングを使用します:
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="日本の歴史について1000字で説明してください",
stream=True
)
for chunk in response:
print(chunk.text, end="", flush=True)ストリーミングを使用することで、ユーザーが長く待つ必要がなくなり、より良いUX体験が提供できます。
Temperature と Top P の設定
生成テキストの創造性や確定性を制御できます:
from google.genai import types
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="面白いジョークを5個作成してください",
config=types.GenerateContentConfig(
temperature=1.0, # 創造的
top_p=0.95, # 核サンプリング
max_output_tokens=1000
)
)Safety Settings
不適切なコンテンツの生成を制限できます:
from google.genai import types
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="プログラミング学習ガイド",
config=types.GenerateContentConfig(
safety_settings=[
types.SafetySetting(
category=types.HarmCategory.HARM_CATEGORY_HATE_SPEECH,
threshold=types.HarmBlockThreshold.BLOCK_ONLY_HIGH
),
types.SafetySetting(
category=types.HarmCategory.HARM_CATEGORY_VIOLENCE,
threshold=types.HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE
)
]
)
)エラーハンドリング
APIの呼び出しは失敗する可能性があります。適切なエラーハンドリングは必須です:
from google import genai
import os
api_key = os.getenv("GEMINI_API_KEY")
client = genai.Client(api_key=api_key)
try:
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="テスト"
)
print(response.text)
except genai.APIError as e:
print(f"APIエラーが発生しました: {e}")
except Exception as e:
print(f"予期しないエラー: {e}")ステップ4:TypeScript/JavaScript SDK のセットアップ
インストール
npm install @google/generative-aiまたは yarn を使用:
yarn add @google/generative-aiステップ5:TypeScript での基本実装
シンプルなテキスト生成
import { GoogleGenerativeAI } from "@google/generative-ai";
const apiKey = process.env.GEMINI_API_KEY;
const genAI = new GoogleGenerativeAI(apiKey!);
async function generateText() {
const model = genAI.getGenerativeModel({
model: "gemini-2.5-flash"
});
const prompt = "日本の首都は?";
const result = await model.generateContent(prompt);
const response = result.response;
console.log(response.text());
}
generateText();ストリーミング対応(TypeScript)
async function streamGenerateText() {
const model = genAI.getGenerativeModel({
model: "gemini-2.5-flash"
});
const prompt = "日本の歴史について1000字で説明してください";
const result = await model.generateContentStream(prompt);
for await (const chunk of result.stream) {
const chunkText = chunk.text();
process.stdout.write(chunkText);
}
}
streamGenerateText();Configuration オプション(TypeScript)
async function generateWithConfig() {
const model = genAI.getGenerativeModel({
model: "gemini-2.5-pro"
});
const result = await model.generateContent({
contents: [
{
role: "user",
parts: [
{
text: "面白いアイデアを10個提案してください"
}
]
}
],
generationConfig: {
temperature: 1.0,
topP: 0.95,
maxOutputTokens: 2000
},
safetySettings: [
{
category: "HARM_CATEGORY_HATE_SPEECH",
threshold: "BLOCK_ONLY_HIGH"
}
]
});
console.log(result.response.text());
}
generateWithConfig();エラーハンドリング(TypeScript)
async function generateWithErrorHandling() {
const model = genAI.getGenerativeModel({
model: "gemini-2.5-flash"
});
try {
const result = await model.generateContent("テスト");
console.log(result.response.text());
} catch (error) {
if (error instanceof Error) {
console.error(`エラーが発生しました: ${error.message}`);
} else {
console.error("予期しないエラーが発生しました");
}
}
}
generateWithErrorHandling();画像入力の処理
Python での画像処理
from google import genai
import base64
import os
api_key = os.getenv("GEMINI_API_KEY")
client = genai.Client(api_key=api_key)
# ファイルパスから画像を読み込む
image_path = "sample_image.jpg"
with open(image_path, "rb") as f:
image_data = base64.standard_b64encode(f.read()).decode("utf-8")
response = client.models.generate_content(
model="gemini-2.5-flash",
contents=[
"この画像について詳しく説明してください",
{
"inline_data": {
"mime_type": "image/jpeg",
"data": image_data
}
}
]
)
print(response.text)TypeScript での画像処理
import fs from "fs";
import path from "path";
async function analyzeImage() {
const model = genAI.getGenerativeModel({
model: "gemini-2.5-flash"
});
const imagePath = "sample_image.jpg";
const imageBuffer = fs.readFileSync(imagePath);
const base64Image = imageBuffer.toString("base64");
const result = await model.generateContent([
"この画像について詳しく説明してください",
{
inlineData: {
mimeType: "image/jpeg",
data: base64Image
}
}
]);
console.log(result.response.text());
}
analyzeImage();マルチターン会話
Python でのチャット実装
def chat_with_gemini():
client = genai.Client(api_key=os.getenv("GEMINI_API_KEY"))
model = client.models.get_model("models/gemini-2.5-flash")
chat = model.start_chat()
while True:
user_input = input("あなた: ")
if user_input.lower() == "終了":
break
response = chat.send_message(user_input)
print(f"Gemini: {response.text}\n")
chat_with_gemini()TypeScript でのチャット実装
async function chatWithGemini() {
const model = genAI.getGenerativeModel({
model: "gemini-2.5-flash"
});
const chat = model.startChat();
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const prompt = () => {
rl.question("あなた: ", async (input: string) => {
if (input.toLowerCase() === "終了") {
rl.close();
return;
}
const result = await chat.sendMessage(input);
console.log(`Gemini: ${result.response.text()}\n`);
prompt();
});
};
prompt();
}
chatWithGemini();レート制限への対応
APIには使用制限があります。適切な対応を実装しましょう:
import time
def call_with_retry(client, model, contents, max_retries=3):
for attempt in range(max_retries):
try:
response = client.models.generate_content(
model=model,
contents=contents
)
return response
except Exception as e:
if "429" in str(e): # Rate limit
wait_time = 2 ** attempt
print(f"レート制限中。{wait_time}秒待機します...")
time.sleep(wait_time)
else:
raise
response = call_with_retry(
client,
"gemini-2.5-flash",
"テストプロンプト"
)ベストプラクティス
- APIキーの管理:絶対にソースコードにキーを埋め込まない
- エラーハンドリング:すべての API 呼び出しを try-catch で囲む
- ストリーミングの活用:長い応答ではストリーミングを使用
- キャッシング:同じプロンプトの繰り返し呼び出しを避ける
- タイムアウト設定:無限待機を防ぐ
まとめ
Gemini APIは、シンプルながら強力なAPIです。PythonとTypeScriptの両方で簡単に統合でき、プロトタイプから本番運用まで幅広い用途に対応します。
本ガイドで基本を習得したら、より高度な機能や特定用途への最適化に進むことをお勧めします。次のステップとして、Function Callingなどの高度な機能については、本サイトの関連記事をご参照ください。