gemini

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Gemini API

Gemini API

Use Google Gemini API via REST for text generation, multimodal analysis, image generation, and more.
通过REST接口使用Google Gemini API,实现文本生成、多模态分析、图像生成等功能。

Prerequisites

前置条件

  • Environment variable
    GOOGLE_API_KEY
    must be set
  • API endpoint:
    https://generativelanguage.googleapis.com/v1beta
  • 必须设置环境变量
    GOOGLE_API_KEY
  • API端点:
    https://generativelanguage.googleapis.com/v1beta

Available Models

可用模型

ModelUse Case
gemini-2.5-flash
Fast text generation (default)
gemini-2.5-pro
High quality text generation
gemini-3-flash-preview
Latest flash model
gemini-3-pro-preview
Latest pro model
gemini-2.5-flash-image
Image generation (Nano Banana)
gemini-3-pro-image-preview
Advanced image generation with thinking & search
模型使用场景
gemini-2.5-flash
快速文本生成(默认)
gemini-2.5-pro
高质量文本生成
gemini-3-flash-preview
最新Flash模型
gemini-3-pro-preview
最新Pro模型
gemini-2.5-flash-image
图像生成(Nano Banana)
gemini-3-pro-image-preview
具备思维与搜索能力的高级图像生成

Workflow

工作流程

Phase 1: Determine Task Type

阶段1:确定任务类型

Based on user request, identify which capability to use:
  • Text Generation: Basic prompts, chat, Q&A
  • Multimodal Analysis: Analyze images, videos, or audio
  • Image Generation: Create or edit images (Nano Banana)
  • Function Calling: Execute custom functions
  • Search Grounding: Real-time web search integration
根据用户请求,确定要使用的功能:
  • 文本生成:基础提示词、对话、问答
  • 多模态分析:分析图像、视频或音频
  • 图像生成:创建或编辑图像(Nano Banana)
  • 函数调用:执行自定义函数
  • 搜索grounding:实时网页搜索集成

Phase 2: Execute API Call

阶段2:执行API调用

Use the appropriate curl command based on task type.

根据任务类型使用对应的curl命令。

1. Text Generation

1. 文本生成

Basic Prompt

基础提示词

bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts": [{"text": "Your prompt here"}]
      }]
    }'
bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts": [{"text": "Your prompt here"}]
      }]
    }'

With Configuration

带配置参数

bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts": [{"text": "Your prompt here"}]
      }],
      "generationConfig": {
        "temperature": 0.9,
        "maxOutputTokens": 2000,
        "stopSequences": ["END"]
      }
    }'
bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts": [{"text": "Your prompt here"}]
      }],
      "generationConfig": {
        "temperature": 0.9,
        "maxOutputTokens": 2000,
        "stopSequences": ["END"]
      }
    }'

Multi-turn Chat

多轮对话

bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [
        {"role": "user", "parts": [{"text": "First message"}]},
        {"role": "model", "parts": [{"text": "Model response"}]},
        {"role": "user", "parts": [{"text": "Follow-up question"}]}
      ]
    }'
bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [
        {"role": "user", "parts": [{"text": "First message"}]},
        {"role": "model", "parts": [{"text": "Model response"}]},
        {"role": "user", "parts": [{"text": "Follow-up question"}]}
      ]
    }'

System Instructions

系统指令

bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "system_instruction": {
        "parts": [{"text": "You are a helpful assistant that speaks like a pirate."}]
      },
      "contents": [{
        "parts": [{"text": "Hello!"}]
      }]
    }'
bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "system_instruction": {
        "parts": [{"text": "You are a helpful assistant that speaks like a pirate."}]
      },
      "contents": [{
        "parts": [{"text": "Hello!"}]
      }]
    }'

JSON Mode Output

JSON格式输出

bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts": [{"text": "List 3 colors as JSON array"}]
      }],
      "generationConfig": {
        "response_mime_type": "application/json"
      }
    }'
bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts": [{"text": "List 3 colors as JSON array"}]
      }],
      "generationConfig": {
        "response_mime_type": "application/json"
      }
    }'

Streaming Response

流式响应

bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse&key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts": [{"text": "Write a long story"}]
      }]
    }'
bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse&key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts": [{"text": "Write a long story"}]
      }]
    }'

Safety Settings

安全设置

bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts": [{"text": "Your prompt"}]
      }],
      "safetySettings": [
        {"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_ONLY_HIGH"},
        {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_ONLY_HIGH"}
      ]
    }'

bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts": [{"text": "Your prompt"}]
      }],
      "safetySettings": [
        {"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_ONLY_HIGH"},
        {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_ONLY_HIGH"}
      ]
    }'

2. Multimodal Analysis

2. 多模态分析

Image Analysis (Base64 Inline)

图像分析(Base64内嵌)

bash
undefined
bash
undefined

First encode image to base64

首先将图片编码为base64

BASE64_IMAGE=$(base64 -w0 image.jpg)
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$GOOGLE_API_KEY"
-H 'Content-Type: application/json'
-X POST
-d '{ "contents": [{ "parts": [ {"text": "Describe this image in detail"}, {"inline_data": {"mime_type": "image/jpeg", "data": "'$BASE64_IMAGE'"}} ] }] }'
undefined
BASE64_IMAGE=$(base64 -w0 image.jpg)
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$GOOGLE_API_KEY"
-H 'Content-Type: application/json'
-X POST
-d '{ "contents": [{ "parts": [ {"text": "Describe this image in detail"}, {"inline_data": {"mime_type": "image/jpeg", "data": "'$BASE64_IMAGE'"}} ] }] }'
undefined

Video Analysis (File API)

视频分析(文件API)

Step 1: Upload Video

步骤1:上传视频

bash
undefined
bash
undefined

Get upload URL

获取上传URL

UPLOAD_URL=$(curl -s "https://generativelanguage.googleapis.com/upload/v1beta/files?key=$GOOGLE_API_KEY"
-H "X-Goog-Upload-Protocol: resumable"
-H "X-Goog-Upload-Command: start"
-H "X-Goog-Upload-Header-Content-Length: $(stat -f%z video.mp4)"
-H "X-Goog-Upload-Header-Content-Type: video/mp4"
-H "Content-Type: application/json"
-d '{"file": {"display_name": "video.mp4"}}'
-D - | grep -i "x-goog-upload-url" | cut -d' ' -f2 | tr -d '\r')
UPLOAD_URL=$(curl -s "https://generativelanguage.googleapis.com/upload/v1beta/files?key=$GOOGLE_API_KEY"
-H "X-Goog-Upload-Protocol: resumable"
-H "X-Goog-Upload-Command: start"
-H "X-Goog-Upload-Header-Content-Length: $(stat -f%z video.mp4)"
-H "X-Goog-Upload-Header-Content-Type: video/mp4"
-H "Content-Type: application/json"
-d '{"file": {"display_name": "video.mp4"}}'
-D - | grep -i "x-goog-upload-url" | cut -d' ' -f2 | tr -d '\r')

Upload file

上传文件

curl "$UPLOAD_URL"
-H "X-Goog-Upload-Offset: 0"
-H "X-Goog-Upload-Command: upload, finalize"
-H "Content-Type: video/mp4"
--data-binary @video.mp4
undefined
curl "$UPLOAD_URL"
-H "X-Goog-Upload-Offset: 0"
-H "X-Goog-Upload-Command: upload, finalize"
-H "Content-Type: video/mp4"
--data-binary @video.mp4
undefined

Step 2: Query with Video

步骤2:结合视频查询

bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts": [
          {"text": "Describe what happens in this video"},
          {"file_data": {"mime_type": "video/mp4", "file_uri": "FILE_URI_FROM_UPLOAD"}}
        ]
      }]
    }'
bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts": [
          {"text": "Describe what happens in this video"},
          {"file_data": {"mime_type": "video/mp4", "file_uri": "FILE_URI_FROM_UPLOAD"}}
        ]
      }]
    }'

Audio Analysis

音频分析

Similar to video, upload via File API then query:
bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts": [
          {"text": "Transcribe and summarize this audio"},
          {"file_data": {"mime_type": "audio/mp3", "file_uri": "FILE_URI_FROM_UPLOAD"}}
        ]
      }]
    }'

与视频分析类似,先通过文件API上传,再进行查询:
bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts": [
          {"text": "Transcribe and summarize this audio"},
          {"file_data": {"mime_type": "audio/mp3", "file_uri": "FILE_URI_FROM_UPLOAD"}}
        ]
      }]
    }'

3. Image Generation (Nano Banana)

3. 图像生成(Nano Banana)

Basic Image Generation

基础图像生成

bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-image:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{"parts": [{"text": "Create a photorealistic image of a cat wearing a hat"}]}],
      "generationConfig": {
        "responseModalities": ["TEXT", "IMAGE"]
      }
    }'
bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-image:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{"parts": [{"text": "Create a photorealistic image of a cat wearing a hat"}]}],
      "generationConfig": {
        "responseModalities": ["TEXT", "IMAGE"]
      }
    }'

With Aspect Ratio Control

宽高比控制

Supported ratios:
1:1
,
2:3
,
3:2
,
3:4
,
4:3
,
4:5
,
5:4
,
9:16
,
16:9
,
21:9
bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-image:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{"parts": [{"text": "Create a landscape scene"}]}],
      "generationConfig": {
        "responseModalities": ["IMAGE"],
        "imageConfig": {
          "aspectRatio": "16:9"
        }
      }
    }'
支持的比例:
1:1
,
2:3
,
3:2
,
3:4
,
4:3
,
4:5
,
5:4
,
9:16
,
16:9
,
21:9
bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-image:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{"parts": [{"text": "Create a landscape scene"}]}],
      "generationConfig": {
        "responseModalities": ["IMAGE"],
        "imageConfig": {
          "aspectRatio": "16:9"
        }
      }
    }'

Image Editing (Character Consistency)

图像编辑(角色一致性)

bash
BASE64_IMAGE=$(base64 -w0 original.jpg)

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-image:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts": [
          {"text": "Put this character in a tropical forest"},
          {"inline_data": {"mime_type": "image/jpeg", "data": "'$BASE64_IMAGE'"}}
        ]
      }],
      "generationConfig": {
        "responseModalities": ["TEXT", "IMAGE"]
      }
    }'
bash
BASE64_IMAGE=$(base64 -w0 original.jpg)

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-image:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts": [
          {"text": "Put this character in a tropical forest"},
          {"inline_data": {"mime_type": "image/jpeg", "data": "'$BASE64_IMAGE'"}}
        ]
      }],
      "generationConfig": {
        "responseModalities": ["TEXT", "IMAGE"]
      }
    }'

High Resolution (Pro Model - 2K/4K)

高分辨率(Pro模型 - 2K/4K)

bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3-pro-image-preview:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{"parts": [{"text": "A photo of an oak tree in all four seasons"}]}],
      "generationConfig": {
        "responseModalities": ["TEXT", "IMAGE"],
        "imageConfig": {
          "aspectRatio": "1:1",
          "imageSize": "4K"
        }
      }
    }'
bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3-pro-image-preview:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{"parts": [{"text": "A photo of an oak tree in all four seasons"}]}],
      "generationConfig": {
        "responseModalities": ["TEXT", "IMAGE"],
        "imageConfig": {
          "aspectRatio": "1:1",
          "imageSize": "4K"
        }
      }
    }'

Image Generation with Search Grounding (Pro)

结合搜索grounding的图像生成(Pro模型)

bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3-pro-image-preview:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{"parts": [{"text": "Visualize the current weather forecast for Tokyo as a chart"}]}],
      "generationConfig": {
        "responseModalities": ["TEXT", "IMAGE"],
        "imageConfig": {
          "aspectRatio": "16:9"
        }
      },
      "tools": [{"google_search": {}}]
    }'
bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3-pro-image-preview:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{"parts": [{"text": "Visualize the current weather forecast for Tokyo as a chart"}]}],
      "generationConfig": {
        "responseModalities": ["TEXT", "IMAGE"],
        "imageConfig": {
          "aspectRatio": "16:9"
        }
      },
      "tools": [{"google_search": {}}]
    }'

Multi-Image Fusion

多图像融合

bash
BASE64_IMG1=$(base64 -w0 image1.jpg)
BASE64_IMG2=$(base64 -w0 image2.jpg)

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-image:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts": [
          {"text": "Combine these two characters in a fantasy world"},
          {"inline_data": {"mime_type": "image/jpeg", "data": "'$BASE64_IMG1'"}},
          {"inline_data": {"mime_type": "image/jpeg", "data": "'$BASE64_IMG2'"}}
        ]
      }],
      "generationConfig": {
        "responseModalities": ["TEXT", "IMAGE"]
      }
    }'

bash
BASE64_IMG1=$(base64 -w0 image1.jpg)
BASE64_IMG2=$(base64 -w0 image2.jpg)

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-image:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts": [
          {"text": "Combine these two characters in a fantasy world"},
          {"inline_data": {"mime_type": "image/jpeg", "data": "'$BASE64_IMG1'"}},
          {"inline_data": {"mime_type": "image/jpeg", "data": "'$BASE64_IMG2'"}}
        ]
      }],
      "generationConfig": {
        "responseModalities": ["TEXT", "IMAGE"]
      }
    }'

4. Function Calling

4. 函数调用

Define and Call Functions

定义并调用函数

bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "role": "user",
        "parts": [{"text": "What movies are playing in Mountain View?"}]
      }],
      "tools": [{
        "function_declarations": [{
          "name": "find_movies",
          "description": "Find movies playing in theaters",
          "parameters": {
            "type": "object",
            "properties": {
              "location": {"type": "string", "description": "City and state"},
              "genre": {"type": "string", "description": "Movie genre"}
            },
            "required": ["location"]
          }
        }]
      }]
    }'
bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "role": "user",
        "parts": [{"text": "What movies are playing in Mountain View?"}]
      }],
      "tools": [{
        "function_declarations": [{
          "name": "find_movies",
          "description": "Find movies playing in theaters",
          "parameters": {
            "type": "object",
            "properties": {
              "location": {"type": "string", "description": "City and state"},
              "genre": {"type": "string", "description": "Movie genre"}
            },
            "required": ["location"]
          }
        }]
      }]
    }'

Provide Function Response

提供函数响应

bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [
        {"role": "user", "parts": [{"text": "What movies are playing in Mountain View?"}]},
        {"role": "model", "parts": [{"functionCall": {"name": "find_movies", "args": {"location": "Mountain View, CA"}}}]},
        {"role": "function", "parts": [{"functionResponse": {"name": "find_movies", "response": {"movies": ["Barbie", "Oppenheimer"]}}}]}
      ],
      "tools": [{
        "function_declarations": [{
          "name": "find_movies",
          "description": "Find movies playing in theaters",
          "parameters": {
            "type": "object",
            "properties": {
              "location": {"type": "string"},
              "genre": {"type": "string"}
            },
            "required": ["location"]
          }
        }]
      }]
    }'

bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [
        {"role": "user", "parts": [{"text": "What movies are playing in Mountain View?"}]},
        {"role": "model", "parts": [{"functionCall": {"name": "find_movies", "args": {"location": "Mountain View, CA"}}}]},
        {"role": "function", "parts": [{"functionResponse": {"name": "find_movies", "response": {"movies": ["Barbie", "Oppenheimer"]}}}]}
      ],
      "tools": [{
        "function_declarations": [{
          "name": "find_movies",
          "description": "Find movies playing in theaters",
          "parameters": {
            "type": "object",
            "properties": {
              "location": {"type": "string"},
              "genre": {"type": "string"}
            },
            "required": ["location"]
          }
        }]
      }]
    }'

5. Search Grounding

5. 搜索Grounding

Real-time web search integration:
bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{"parts": [{"text": "What is the current Google stock price?"}]}],
      "tools": [{"google_search": {}}]
    }'
Response includes
groundingMetadata
with sources.

实时网页搜索集成:
bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{"parts": [{"text": "What is the current Google stock price?"}]}],
      "tools": [{"google_search": {}}]
    }'
响应包含带有来源信息的
groundingMetadata

6. Context Caching

6. 上下文缓存

For repeated queries on the same large content:
针对同一大内容的重复查询:

Create Cache

创建缓存

bash
curl "https://generativelanguage.googleapis.com/v1beta/cachedContents?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "model": "models/gemini-2.5-flash",
      "contents": [{"parts": [{"text": "LARGE_DOCUMENT_TEXT_HERE"}]}],
      "ttl": "3600s"
    }'
bash
curl "https://generativelanguage.googleapis.com/v1beta/cachedContents?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "model": "models/gemini-2.5-flash",
      "contents": [{"parts": [{"text": "LARGE_DOCUMENT_TEXT_HERE"}]}],
      "ttl": "3600s"
    }'

Use Cache

使用缓存

bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "cachedContent": "cachedContents/CACHE_ID",
      "contents": [{"parts": [{"text": "Summarize the document"}]}]
    }'

bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "cachedContent": "cachedContents/CACHE_ID",
      "contents": [{"parts": [{"text": "Summarize the document"}]}]
    }'

7. Model Information

7. 模型信息

List All Models

列出所有模型

bash
curl "https://generativelanguage.googleapis.com/v1beta/models?key=$GOOGLE_API_KEY"
bash
curl "https://generativelanguage.googleapis.com/v1beta/models?key=$GOOGLE_API_KEY"

Get Specific Model

获取特定模型信息

bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash?key=$GOOGLE_API_KEY"

bash
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash?key=$GOOGLE_API_KEY"

Response Handling

响应处理

Text Response Structure

文本响应结构

json
{
  "candidates": [{
    "content": {
      "parts": [{"text": "Response text here"}],
      "role": "model"
    },
    "finishReason": "STOP"
  }],
  "usageMetadata": {
    "promptTokenCount": 10,
    "candidatesTokenCount": 50,
    "totalTokenCount": 60
  }
}
json
{
  "candidates": [{
    "content": {
      "parts": [{"text": "Response text here"}],
      "role": "model"
    },
    "finishReason": "STOP"
  }],
  "usageMetadata": {
    "promptTokenCount": 10,
    "candidatesTokenCount": 50,
    "totalTokenCount": 60
  }
}

Image Response Structure

图像响应结构

When using image generation, response includes base64-encoded images:
json
{
  "candidates": [{
    "content": {
      "parts": [
        {"text": "Here is your image:"},
        {"inlineData": {"mimeType": "image/png", "data": "BASE64_IMAGE_DATA"}}
      ]
    }
  }]
}
To save the image:
bash
undefined
使用图像生成功能时,响应包含Base64编码的图像:
json
{
  "candidates": [{
    "content": {
      "parts": [
        {"text": "Here is your image:"},
        {"inlineData": {"mimeType": "image/png", "data": "BASE64_IMAGE_DATA"}}
      ]
    }
  }]
}
保存图像的方法:
bash
undefined

Extract and decode image from response

从响应中提取并解码图像

echo "BASE64_DATA" | base64 -d > output.png

---
echo "BASE64_DATA" | base64 -d > output.png

---

Error Handling

错误处理

ErrorCauseSolution
400Invalid requestCheck JSON syntax
401Invalid API keyVerify GOOGLE_API_KEY
429Rate limitWait and retry
500Server errorRetry with exponential backoff

错误码原因解决方案
400请求无效检查JSON语法
401API密钥无效验证GOOGLE_API_KEY
429触发速率限制等待后重试
500服务器错误使用指数退避策略重试

Best Practices

最佳实践

  1. Use appropriate model: Flash for speed, Pro for quality
  2. Set temperature: Lower (0.1-0.3) for factual, higher (0.7-1.0) for creative
  3. Limit output tokens: Set
    maxOutputTokens
    to avoid excessive responses
  4. Use caching: For repeated queries on large documents
  5. Handle streaming: For long responses, use
    streamGenerateContent
  6. Image generation tips: Use detailed, descriptive prompts for best results
  1. 选择合适的模型:追求速度选Flash,追求质量选Pro
  2. 设置temperature参数:低数值(0.1-0.3)适合事实性内容,高数值(0.7-1.0)适合创意内容
  3. 限制输出token数:设置
    maxOutputTokens
    避免响应过长
  4. 使用缓存:针对大文档的重复查询
  5. 处理流式响应:长响应使用
    streamGenerateContent
    接口
  6. 图像生成技巧:使用详细、描述性的提示词以获得最佳效果