mcpField
G
gemini-api

gemini-api

github.com/diskd-ai開発758 回インストール41 週間前に更新
リポジトリ

gemini-api について

Python、JavaScript、REST から Google's Gemini API を利用するスキルです。テキストやマルチモーダル生成、メディア作成、埋め込み、モデル制御を扱います。

主な機能

  1. 01テキスト・画像・動画・音声の生成
  2. 02ストリーミングと複数ターンのチャット
  3. 03PDF 処理と画像編集
  4. 04動画と音楽の生成
  5. 05埋め込みと構造化出力
  6. 06関数呼び出しと思考制御

活用シーン

  1. 01プロンプトやメディアからのテキスト生成
  2. 02PDF 文書の要約と分析
  3. 03画像の作成・編集と動画生成
  4. 04埋め込みを使ったセマンティック検索

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/diskd-ai/gemini-api --skill gemini-api

インストール後、Claude Code で/gemini-apiを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

.gitignore
README.md
references/
image-generation.md
documents.md
embeddings.md
lyria.md
thinking.md
structured-outputs.md
gemini-3.md
function-calling.md
tools.md
veo.md

詳細

Gemini API

Google の Gemini API を使用して、テキスト、画像、動画、音声からテキストを生成します。

モデル

モデルコード入出力コンテキスト思考
Gemini 3 Progemini-3-pro-previewテキスト/画像/動画/音声/PDF -> テキスト1M/64Kあり
Gemini 3 Flashgemini-3-flash-previewテキスト/画像/動画/音声/PDF -> テキスト1M/64Kあり
Gemini 2.5 Progemini-2.5-proテキスト/画像/動画/音声/PDF -> テキスト1M/65Kあり
Gemini 2.5 Flashgemini-2.5-flashテキスト/画像/動画/音声 -> テキスト1M/65Kあり
Nano Bananagemini-2.5-flash-imageテキスト/画像 -> 画像-なし
Nano Banana Progemini-3-pro-image-previewテキスト/画像 -> 画像(最大4K)65K/32Kあり
Veo 3.1veo-3.1-generate-previewテキスト/画像/動画 -> 動画+音声--
Veo 3veo-3-generate-previewテキスト/画像 -> 動画+音声--
Veo 2veo-2.0-generate-001テキスト/画像 -> 動画(音声なし)--
Lyria RealTimelyria-realtime-expテキスト -> 音楽(ストリーミング)--
Embeddingsgemini-embedding-001テキスト -> 埋め込み2Kなし

無料枠:Flash モデルのみ(API では gemini-3-pro-preview に無料枠はありません)。デフォルトの温度:1.0(Gemini 3 では変更しないでください)。

料金(100万トークンあたり):

  • Gemini 3 Pro:$2/$12(<200k)、$4/$18(>200k)
  • Gemini 3 Flash:$0.50/$3
  • Nano Banana Pro:$2(テキスト)/$0.134(画像)

基本的なテキスト生成

Python
from google import genai

client = genai.Client()
response = client.models.generate_content(
    model="gemini-3-flash-preview",
    contents="How does AI work?"
)
print(response.text)
JavaScript
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});
const response = await ai.models.generateContent({
  model: "gemini-3-flash-preview",
  contents: "How does AI work?",
});
console.log(response.text);
REST
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3-flash-preview:generateContent" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"contents": [{"parts": [{"text": "How does AI work?"}]}]}'

システム指示

response = client.models.generate_content(
    model="gemini-3-flash-preview",
    config=types.GenerateContentConfig(
        system_instruction="You are a helpful assistant."
    ),
    contents="Hello"
)
const response = await ai.models.generateContent({
  model: "gemini-3-flash-preview",
  contents: "Hello",
  config: { systemInstruction: "You are a helpful assistant." },
});

ストリーミング

for chunk in client.models.generate_content_stream(
    model="gemini-3-flash-preview",
    contents="Tell me a story"
):
    print(chunk.text, end="")
const response = await ai.models.generateContentStream({
  model: "gemini-3-flash-preview",
  contents: "Tell me a story",
});
for await (const chunk of response) {
  console.log(chunk.text);
}

マルチターンチャット

chat = client.chats.create(model="gemini-3-flash-preview")
response = chat.send_message("I have 2 dogs.")
print(response.text)
response = chat.send_message("How many paws total?")
print(response.text)
const chat = ai.chats.create({ model: "gemini-3-flash-preview" });
const response = await chat.sendMessage({ message: "I have 2 dogs." });
console.log(response.text);

マルチモーダル(画像)

from PIL import Image

image = Image.open("/path/to/image.png")
response = client.models.generate_content(
    model="gemini-3-flash-preview",
    contents=[image, "Describe this image"]
)
const image = await ai.files.upload({ file: "/path/to/image.png" });
const response = await ai.models.generateContent({
  model: "gemini-3-flash-preview",
  contents: [
    createUserContent([
      "Describe this image",
      createPartFromUri(image.uri, image.mimeType),
    ]),
  ],
});

ドキュメント処理(PDF)

ネイティブのビジョン理解機能を使用して PDF を処理します(最大1000ページ)。

from google.genai import types
import pathlib

filepath = pathlib.Path('document.pdf')
response = client.models.generate_content(
    model="gemini-3-flash-preview",
    contents=[
        types.Part.from_bytes(data=filepath.read_bytes(), mime_type='application/pdf'),
        "Summarize this document"
    ]
)
import * as fs from 'fs';

const response = await ai.models.generateContent({
    model: "gemini-3-flash-preview",
    contents: [
        { text: "Summarize this document" },
        {
            inlineData: {
                mimeType: 'application/pdf',
                data: Buffer.from(fs.readFileSync("document.pdf")).toString("base64")
            }
        }
    ]
});

大容量の PDF の場合は、Files API を使用します(48時間保存):

uploaded_file = client.files.upload(file=pathlib.Path('large.pdf'))
response = client.models.generate_content(
    model="gemini-3-flash-preview",
    contents=[uploaded_file, "Summarize this document"]
)

Files API、複数の PDF、ベストプラクティスについては、references/documents.md をご覧ください。


画像生成(Nano Banana)

会話形式で画像を生成、編集します。

response = client.models.generate_content(
    model="gemini-2.5-flash-image",
    contents="Create a picture of a sunset over mountains",
)

for part in response.parts:
    if part.inline_data is not None:
        part.as_image().save("generated.png")
const response = await ai.models.generateContent({
  model: "gemini-2.5-flash-image",
  contents: "Create a picture of a sunset over mountains",
});

for (const part of response.candidates[0].content.parts) {
  if (part.inlineData) {
    const buffer = Buffer.from(part.inlineData.data, "base64");
    fs.writeFileSync("generated.png", buffer);
  }
}

Nano Banana Pro(gemini-3-pro-image-preview):4K 出力、Google Search によるグラウンディング、最大14枚の参照画像、思考シグネチャーを使った会話形式の編集に対応しています。

編集、マルチターン、その他の高度な機能については、references/image-generation.md をご覧ください。 Gemini 3 の画像機能については、references/gemini-3.md をご覧ください。


動画生成(Veo)

Veo を使用して、ネイティブ音声付きの8秒動画を720p、1080p、または4Kで生成します。

import time
from google import genai

client = genai.Client()

operation = client.models.generate_videos(
    model="veo-3.1-generate-preview",
    prompt="A cinematic shot of a majestic lion in the savannah at golden hour",
)

# Poll until complete (video generation is async)
while not operation.done:
    time.sleep(10)
    operation = client.operations.get(operation)

# Download the video
video = operation.response.generated_videos[0]
client.files.download(file=video.video)
video.video.save("lion.mp4")
let operation = await ai.models.generateVideos({
    model: "veo-3.1-generate-preview",
    prompt: "A cinematic shot of a majestic lion in the savannah at golden hour",
});

while (!operation.done) {
    await new Promise(resolve => setTimeout(resolve, 10000));
    operation = await ai.operations.getVideosOperation({ operation });
}

ai.files.download({
    file: operation.response.generatedVideos[0].video,
    downloadPath: "lion.mp4",
});

Veo 3.1 の機能:ポートレート(9:16)、動画の延長(最大148秒)、4K 解像度、セリフ/効果音付きのネイティブ音声。

画像から動画への生成、参照画像、動画の延長、プロンプトガイドについては、references/veo.md をご覧ください。


音楽生成(Lyria RealTime)

動的な調整機能を使って、リアルタイムに連続したインストゥルメンタル音楽を生成します。

import asyncio
from google import genai
from google.genai import types

client = genai.Client()

async def main():
    async with client.aio.live.music.connect(model='models/lyria-realtime-exp') as session:
        # Set prompts and config
        await session.set_weighted_prompts(
            prompts=[types.WeightedPrompt(text='minimal techno', weight=1.0)]
        )
        await session.set_music_generation_config(
            config=types.LiveMusicGenerationConfig(bpm=90, temperature=1.0)
        )

        # Start streaming
        await session.play()

        # Receive audio chunks
        async for message in session.receive():
            if message.server_content and message.server_content.audio_chunks:
                audio_data = message.server_content.audio_chunks[0].data
                # Process audio...

asyncio.run(main())
const session = await ai.live.music.connect({
    model: "models/lyria-realtime-exp",
    callbacks: {
        onmessage: (message) => {
            if (message.serverContent?.audioChunks) {
                for (const chunk of message.serverContent.audioChunks) {
                    const audioBuffer = Buffer.from(chunk.data, "base64");
                    // Process audio...
                }
            }
        },
    },
});

await session.setWeightedPrompts({
    weightedPrompts: [{ text: "minimal techno", weight: 1.0 }],
});

await session.setMusicGenerationConfig({
    musicGenerationConfig: { bpm: 90, temperature: 1.0 },
});

await session.play();

出力:48kHz ステレオ 16-bit PCM。インストゥルメンタルのみ。BPM、スケール、密度、明るさを設定できます。

音楽の調整、設定、プロンプトガイドについては、references/lyria.md をご覧ください。


埋め込み

意味的類似性の判定、検索、分類に使用するテキスト埋め込みを生成します。

result = client.models.embed_content(
    model="gemini-embedding-001",
    contents="What is the meaning of life?"
)
print(result.embeddings)
const response = await ai.models.embedContent({
    model: 'gemini-embedding-001',
    contents: 'What is the meaning of life?',
});
console.log(response.embeddings);

タスクタイプ:SEMANTIC_SIMILARITY、CLASSIFICATION、CLUSTERING、RETRIEVAL_DOCUMENT、RETRIEVAL_QUERY

出力次元数:768、1536、3072(デフォルト)

バッチ処理、タスクタイプ、正規化については、references/embeddings.md をご覧ください。


Thinking(Gemini 3)

thinking_level で推論の深さを制御します。minimal(Flash のみ)、low、medium(Flash のみ)、high(デフォルト)を指定できます。

from google.genai import types

response = client.models.generate_content(
    model="gemini-3-flash-preview",
    contents="Solve this math problem...",
    config=types.GenerateContentConfig(
        thinking_config=types.ThinkingConfig(thinking_level="high")
    ),
)
import { ThinkingLevel } from "@google/genai";

const response = await ai.models.generateContent({
  model: "gemini-3-flash-preview",
  contents: "Solve this math problem...",
  config: { thinkingConfig: { thinkingLevel: ThinkingLevel.HIGH } },
});

注:thinking_level と従来の thinking_budget は併用できません(400 エラーが返されます)。

Gemini 2.5 では、代わりに thinking_budget(0~32768)を使用してください。詳しくは references/thinking.md をご覧ください。

Gemini 3 の機能(思考シグネチャ、メディア解像度など)の詳細については、references/gemini-3.md をご覧ください。


構造化出力

スキーマに準拠した JSON レスポンスを生成します。

from pydantic import BaseModel
from typing import List

class Recipe(BaseModel):
    name: str
    ingredients: List[str]

response = client.models.generate_content(
    model="gemini-3-flash-preview",
    contents="Extract: chocolate chip cookies need flour, sugar, chips",
    config={
        "response_mime_type": "application/json",
        "response_json_schema": Recipe.model_json_schema(),
    },
)
recipe = Recipe.model_validate_json(response.text)
import { z } from "zod";
import { zodToJsonSchema } from "zod-to-json-schema";

const recipeSchema = z.object({
  name: z.string(),
  ingredients: z.array(z.string()),
});

const response = await ai.models.generateContent({
  model: "gemini-3-flash-preview",
  contents: "Extract: chocolate chip cookies need flour, sugar, chips",
  config: {
    responseMimeType: "application/json",
    responseJsonSchema: zodToJsonSchema(recipeSchema),
  },
});

高度なパターンについては、references/structured-outputs.md をご覧ください。


組み込みツール(Gemini 3)

利用可能:Google Search、File Search、Code Execution、URL Context、Function Calling

未対応:Google Maps grounding、Computer Use(これらの機能には Gemini 2.5 を使用してください)

response = client.models.generate_content(
    model="gemini-3-pro-preview",
    contents="What's the latest news on AI?",
    config={"tools": [{"google_search": {}}]},
)
const response = await ai.models.generateContent({
  model: "gemini-3-pro-preview",
  contents: "What's the latest news on AI?",
  config: { tools: [{ googleSearch: {} }] },
});

構造化出力とツールの併用:Gemini 3 では、JSON スキーマと組み込みツール(Google Search、URL Context、Code Execution)を組み合わせて使用できます。詳しくは references/gemini-3.md をご覧ください。

すべてのツールパターンについては、references/tools.md をご覧ください。


Function Calling

モデルを外部ツールや API に接続します。モデルが関数を呼び出すタイミングを判断し、パラメーターを指定します。

from google.genai import types

# Define function
get_weather = {
    "name": "get_weather",
    "description": "Get weather for a location",
    "parameters": {
        "type": "object",
        "properties": {
            "location": {"type": "string", "description": "City name"},
        },
        "required": ["location"],
    },
}

response = client.models.generate_content(
    model="gemini-3-flash-preview",
    contents="What's the weather in Tokyo?",
    config=types.GenerateContentConfig(
        tools=[types.Tool(function_declarations=[get_weather])]
    ),
)

# Check for function call
if response.function_calls:
    fc = response.function_calls[0]
    print(f"Call {fc.name} with {fc.args}")
const response = await ai.models.generateContent({
  model: "gemini-3-flash-preview",
  contents: "What's the weather in Tokyo?",
  config: {
    tools: [{ functionDeclarations: [getWeather] }],
  },
});

if (response.functionCalls) {
  const { name, args } = response.functionCalls[0];
  // Execute function and send result back
}

自動 Function Calling(Python):関数をツールとして直接渡すと、自動的に実行されます。

実行モード、合成呼び出し、マルチモーダルレスポンス、MCP 統合、ベストプラクティスについては、references/function-calling.md をご覧ください。


クイックリファレンス

機能PythonJavaScript
生成generate_content()generateContent()
ストリームgenerate_content_stream()generateContentStream()
チャットchats.create()chats.create()
構造化出力response_json_schema=responseJsonSchema:
画像生成gemini-2.5-flash-imagegemini-2.5-flash-image
動画生成generate_videos()generateVideos()
音楽生成live.music.connect()live.music.connect()
関数呼び出しfunction_declarationsfunctionDeclarations
埋め込みembed_content()embedContent()
Files APIfiles.upload()files.upload()

Gemini 3 固有の機能

Gemini 3 の高度な機能については、references/gemini-3.md をご覧ください。

  • 思考レベル:推論の深さを制御します(minimal、low、medium、high)
  • メディア解像度:マルチモーダル処理を細かく制御します(media_resolution_low から ultra_high まで)
  • 思考シグネチャ:関数呼び出しと画像編集のコンテキストで必要です
  • 構造化出力とツールの併用:JSON スキーマと Google Search、URL Context を組み合わせます
  • マルチモーダル関数レスポンス:ツールのレスポンスに画像を含めて返します

リソース

コメント