精通Gemini 3 Pro API:完整開發者指南

精通Gemini 3 Pro API:完整開發者指南

文章目录

  • Gemini 3 Pro的獨特之處是什麼?
  • 入門指南:首次呼叫Gemini 3 Pro API
  • Gemini 3 Pro API定價
  • 瞭解Gemini 3 Pro的新引數
  • 思考級別引數
  • 媒體解析度控制
  • 溫度設定
  • 跟我一起構建:Gemini 3 Pro API實戰示例
  • 演示 1:構建智慧程式碼分析器
  • 演示 2:多模態文件智慧
  • 高階功能:超越基本提示
  • 思維簽名:維護推理上下文
  • 上下文快取最佳化成本
  • 批次API:大規模處理
  • 小結

精通Gemini 3 Pro API:完整開發者指南

谷歌最近釋出了其最智慧的模型,該模型能夠跨多種模態進行建立、推理和理解。Google Gemini 3 Pro 不僅僅是一次小幅更新,它實際上是人工智慧能力的一次重大飛躍。這款模型擁有尖端的推理、多模態理解和智慧體功能,將成為改變開發者建立智慧應用方式的關鍵因素。藉助全新的 Gemini 3 Pro API,開發者現在可以建立比以往任何時候都更智慧、更動態的系統。

如果您正在構建複雜的 AI 工作流程、處理多模態資料或開發能夠自主管理多步驟任務的智慧體系統,本指南將教您如何透過其 API 使用 Gemini 3 Pro。

Gemini 3 Pro的獨特之處是什麼?

我們暫且不談技術細節,先來探討一下這款模型為何在開發者中引起如此熱議。經過一段時間的開發,谷歌 Gemini 3 Pro 模型如今已躋身 AI 基準測試榜首,Elo 評分高達 1501 分。它的設計不僅旨在提供極致效能,更著重於為開發者打造卓越的體驗。

主要特性包括:

  • 高階推理:該模型現在能夠以極其精細的思維解決複雜的多步驟問題。
  • 海量上下文視窗:高達 100 萬個詞元的輸入上下文,足以支援輸入完整的程式碼庫、完整的書籍或長影片內容。
  • 多模態處理:能夠流暢地同時處理文字、影像、影片、PDF 和程式碼。
  • 智慧體工作流:執行多步驟任務,模型能夠協調、檢查並調整其作為機器人的行動。
  • 動態思維:根據具體情況,模型可以逐步解決問題,也可以直接給出答案。

您可以在以下文章中瞭解更多關於 Gemini 3 Pro 型號及其功能的資訊:Gemini 3 Pro

入門指南:首次呼叫Gemini 3 Pro API

步驟 1:獲取API金鑰

前往 Google AI Studio 並使用您的 Google 帳戶登入。然後,點選右上角的個人資料圖示,並選擇“Get API key”選項。如果是首次使用,請選擇“Create API key in new project”;否則,請匯入現有金鑰。請立即備份 API 金鑰,因為您將無法再次檢視它。

步驟 2:安裝SDK

選擇您偏好的語言,並使用以下命令安裝官方 SDK:

Python:

pip install google-genai

Node.js/JavaScript:

npm install @google/genai

步驟 3:設定環境變數

將您的 API 金鑰安全地儲存在環境變數中:

export GEMINI_API_KEY="your-api-key-here"

Gemini 3 Pro API定價

Gemini 3 Pro API 採用按需付費模式,費用主要根據您輸入(提示)和模型輸出(響應)所消耗的 tokens 數量計算。

定價層級的關鍵決定因素是請求的上下文視窗長度。上下文視窗越長,模型可以同時處理的資訊就越多(例如大型文件或較長的對話歷史記錄),因此費用也越高。

以下費率適用於透過 Gemini API 呼叫的 geomini-3-pro-preview 模型,並以每百萬令牌 (1M) 為單位計費

功能 (Feature) 免費層級 (Free Tier) 付費層級 (Paid Tier) (每 100 萬 token,單位:美元)
輸入價格 (Input price) 免費(每日用量有限制) $2.00 (提示詞 ≤ 200k token)<br>$4.00 (提示詞 > 200k token)
輸出價格 (含思維 token)<br>(Output price including thinking tokens) 免費(每日用量有限制) $12.00 (提示詞 ≤ 200k token)<br>$18.00 (提示詞 > 200k token)
上下文快取價格 (Context caching price) 不可用 $0.20 – $0.40 / 100 萬 token (取決於提示詞大小)<br>$4.50 / 100 萬 token / 小時 (儲存價格)
Google 搜尋 grounding (Grounding with Google Search) 不可用 1,500 次/天 (免費)<br>即將推出: $14 / 1,000 次搜尋查詢
Google 地圖 grounding (Grounding with Google Maps) 不可用 不可用

瞭解Gemini 3 Pro的新引數

API 引入了多個革命性的引數,其中之一是“思考級別”引數,它賦予請求者非常精細的完全控制權。

思考級別引數

這個新引數很可能是最重要的引數。您不再需要猜測模型應該“思考”到什麼程度,而是可以完全由您控制:

  • thinking_level: “low”:適用於分類、問答或聊天等基本任務。延遲極低,成本也更低,非常適合高吞吐量應用。
  • thinking_level: “high”(預設值):適用於複雜的推理任務。模型需要更長時間,但輸出結果將包含更嚴謹的論證。這是解決問題和進行分析的最佳時機。

提示:請勿將 thinking_level 與舊的 thinking_budget 引數一起使用,因為它們不相容,會導致 400 錯誤。

媒體解析度控制

在分析影像、PDF 文件或影片時,您現在可以調節分析視覺輸入時的虛擬處理器使用率:

  • 影像:media_resolution_high 可獲得最佳質量(每影像 1120 個標記)。
  • PDF:media_resolution_medium  用於文件理解(每幀 560 個標記)。
  • 影片: media_resolution_low  用於動作識別(每幀 70 個標記),media_resolution_high 用於對話密集型文字(每幀 280 個標記)。

這使您可以自行最佳化質量和標記使用率。

溫度設定

您可能會對以下功能感興趣:您可以將溫度設定為預設值 1.0。與以往型號通常會有效利用溫度調整不同,Gemini 3 的推理是圍繞此預設設定進行最佳化的。降低溫度可能會導致奇怪的迴圈或降低更復雜任務的效能。

跟我一起構建:Gemini 3 Pro API實戰示例

演示 1:構建智慧程式碼分析器

讓我們使用一個實際用例來構建一個程式。我們將建立一個系統,該系統首先分析程式碼,識別差異,然後使用 Gemini 3 Pro 的高階推理功能提出改進建議。

Python實現

import os
from google import genai
# Initialize the Gemini API client with your API key
# You can set this directly or via environment variable
api_key = "api-key"  # Replace with your actual API key
client = genai.Client(api_key=api_key)
def analyze_code(code_snippet: str) -> str:
"""
Analyzes code for discrepancies and suggests improvements using Gemini 3 Pro.
Args:
code_snippet: The code to analyze
Returns:
Analysis and improvement suggestions from the model
"""
response = client.models.generate_content(
model="gemini-3-pro-preview",
contents=[
{
"text": f"""Analyze this code for issues, inefficiencies, and potential improvements.
Provide:
1. Issues found (bugs, logic errors, security concerns)
2. Performance optimizations
3. Code quality improvements
4. Best practices violations
5. Refactored version with explanations
Code to analyze:
{code_snippet}
Be direct and concise in your analysis."""
}
]
)
return response.text
# Example usage
sample_code = """
def calculate_total(items):
total = 0
for i in range(len(items)):
total = total + items[i]['price'] * items[i]['quantity']
return total
def get_user_data(user_id):
import requests
response = requests.get(f"http://api.example.com/user/{user_id}")
data = response.json()
return data
"""
print("=" * 60)
print("GEMINI 3 PRO - SMART CODE ANALYZER")
print("=" * 60)
print("\nAnalyzing code...\n")
# Run the analysis
analysis = analyze_code(sample_code)
print(analysis)
print("\n" + "=" * 60)

輸出:

構建智慧程式碼分析器輸出演示-01 構建智慧程式碼分析器輸出演示-02 構建智慧程式碼分析器輸出演示-03 構建智慧程式碼分析器輸出演示-04

這裡發生了什麼?

  • 由於程式碼審查需要大量的推理,因此我們採用了 thinking_level ("high")
  • 提示簡潔明瞭。Gemini 3 在提示直接的情況下比精心設計的提示更有效。
  • 模型將運用完整的推理能力審查程式碼,並提供包含重要修改和深入分析的響應版本。

演示 2:多模態文件智慧

現在,讓我們來看一個更復雜的用例:分析文件影像並提取結構化資訊。

Python實現

import base64
import json
from google import genai
# Initialize the Gemini API client
api_key = "api-key-here"  # Replace with your actual API key
client = genai.Client(api_key=api_key)
def analyze_document_image(image_path: str) -> dict:
"""
Analyzes a document image and extracts key information.
Handles images, PDFs, and other document formats.
Args:
image_path: Path to the document image file
Returns:
Dictionary containing extracted document information as JSON
"""
# Read and encode the image
with open(image_path, "rb") as img_file:
image_data = base64.standard_b64encode(img_file.read()).decode()
# Determine the MIME type based on file extension
mime_type = "image/jpeg"  # Default
if image_path.endswith(".png"):
mime_type = "image/png"
elif image_path.endswith(".pdf"):
mime_type = "application/pdf"
elif image_path.endswith(".gif"):
mime_type = "image/gif"
elif image_path.endswith(".webp"):
mime_type = "image/webp"
# Call the Gemini API with multimodal content
response = client.models.generate_content(
model="gemini-3-pro-preview",
contents=[
{
"text": """Extract and structure all information from this document image.
Return the data as JSON with these fields:
- document_type: What type of document is this?
- key_entities: List of important names, dates, amounts, etc.
- main_content: Brief summary of the document's purpose
- action_items: Any tasks or deadlines mentioned
- confidence: How confident you are in the extraction (high/medium/low)
Return ONLY valid JSON, no markdown formatting."""
},
{
"inline_data": {
"mime_type": mime_type,
"data": image_data
}
}
]
)
# Parse the JSON response
try:
result = json.loads(response.text)
return result
except json.JSONDecodeError:
return {
"error": "Failed to parse response",
"raw": response.text
}
# Example usage with a sample document
print("=" * 70)
print("GEMINI 3 PRO - MULTI-MODAL DOCUMENT INTELLIGENCE")
print("=" * 70)
document_path = "Gemini-3-Pro-Model-Card.pdf"  # Change this to your actual document path
try:
print(f"\nAnalyzing document: {document_path}")
print("Processing...\n")
document_info = analyze_document_image(document_path)
print("Extracted Document Information:")
print("-" * 70)
print(json.dumps(document_info, indent=2))
except FileNotFoundError:
print(f"Error: Document file '{document_path}' not found.")
print("Please provide a valid path to a document image (JPG, PNG, PDF, etc.)")
print("\nExample:")
print('  document_info = analyze_document_image("invoice.pdf")')
print('  document_info = analyze_document_image("contract.png")')
print('  document_info = analyze_document_image("receipt.jpg")')
except Exception as e:
print(f"Error processing document: {str(e)}")
print("\n" + "=" * 70)

輸出:

多模態文件智慧輸出演示

關鍵技術:

  • 影像處理:我們使用 base64 格式對圖片進行編碼以便交付。
  • 最高質量選項:對於文字檔案,我們應用 media_resolution_high 以提供完美的 OCR 識別。
  • 有序結果:我們要求提供易於與其他系統連線的 JSON 格式。
  • 錯誤處理:我們採用能夠最大限度減少 JSON 解析錯誤的方式。

高階功能:超越基本提示

思維簽名:維護推理上下文

Gemini 3 Pro 引入了一項名為“思維簽名”的強大功能,它對模型內部推理過程進行加密表示。在使用函式呼叫或多輪對話時,這些模型簽名會在 API 呼叫中保留上下文資訊。

如果您選擇使用官方的 Python 或 Node.js SDK,則思維簽名將自動且不可見地處理。但如果您進行原始 API 呼叫,則需要按原樣返回接收到的思維簽名。

上下文快取最佳化成本

您是否計劃多次傳送類似的請求?利用上下文快取,它可以快取提示的前 2,048 個令牌,從而節省後續請求的成本。如果您需要處理大量文件,並且可以在處理過程中重複使用系統提示,那麼上下文快取將非常實用。

批次API:大規模處理

對於時間要求不高的工作負載,批次 API 可以節省高達 90% 的成本。這對於需要處理大量文件或需要在夜間執行大型分析的工作負載來說非常理想。

小結

Google Gemini 3 Pro 標誌著 AI API 功能的一個轉折點。高階推理、超大上下文視窗和經濟實惠的價格相結合,意味著您現在可以構建以前難以實現的系統。

從小處著手:構建聊天機器人、分析一些文件或自動化一些例行任務。然後,隨著您對 API 的熟悉程度加深,您可以探索更復雜的場景,例如自主代理、程式碼生成和多模態分析。

評論留言