Gemini 中文指南
获取 API 密钥 ↗

迁移到 Google GenAI SDK

↓ 下载 MarkdownInteractions API

从 Gemini 2.0 版本开始,2024, 后期我们引入了一组新的库,称为 Google GenAI SDK。它通过以下方式提供了改进的开发人员体验 更新的客户端架构, 和 简化过渡 开发人员和企业工作流程之间。

Google GenAI SDK 现已投入使用 正式发布 (GA) 跨所有支持的平台。如果您正在使用我们的其中之一 遗留库,我们强烈建议您迁移。

本指南提供了迁移代码之前和之后的示例,以帮助您入门。

安装 #

之前

shell
pip install -U -q "google-generativeai"

之后

shell
pip install -U -q "google-genai"

API访问 #

旧的 SDK 使用各种临时方法在幕后隐式处理 API 客户端。这使得管理客户端和凭据变得困难。现在,您通过中央进行交互 Client 对象。这个 Client 对象充当各种 API 服务的单个入口点(例如, models, chats, files, tunings),促进不同 API 调用的一致性并简化凭证和配置管理。

之前(不太集中的 API 访问)

对于大多数 API 调用,旧的 SDK 没有显式使用顶级客户端对象。您将直接实例化并与之交互 GenerativeModel 对象。

python
import google.generativeai as genai

# Directly create and use model objects
model = genai.GenerativeModel('gemini-3.8-flash')
response = model.generate_content(...)
chat = model.start_chat(...)

之后(集中式客户端对象)

python
from google import genai

# Create a single client object
client = genai.Client(http_options={"api_version": "v1beta"})

# Access API methods through services on the client object
response = client.models.generate_content(...)
chat = client.chats.create(...)
my_file = client.files.upload(...)
tuning_job = client.tunings.tune(...)

认证 #

旧库和新库都使用 API 密钥进行身份验证。你可以 创造 您的 API 密钥位于 Google AI Studio 中。

之前

旧的 SDK 隐式处理 API 客户端对象。

python
import google.generativeai as genai

genai.configure(api_key=...)

之后

使用Google GenAI SDK,您首先创建一个API客户端,用于调用API。新的 SDK 将从中获取您的 API 密钥 GEMINI_API_KEY 环境变量(如果您不将环境变量传递给客户端)。

shell
export GEMINI_API_KEY="YOUR_API_KEY"
python
from google import genai

client = genai.Client() # Set the API key using the GEMINI_API_KEY env var.
                      # Alternatively, you could set the API key explicitly:
                      # client = genai.Client(api_key="YOUR_API_KEY")

生成内容 #

文本 #

之前

以前没有客户端对象,您可以直接通过以下方式访问 API GenerativeModel 对象。

python
import google.generativeai as genai

model = genai.GenerativeModel('gemini-3.8-flash')
response = model.generate_content(
  'Tell me a story in 300 words'
)
print(response.text)

之后

新的 Google GenAI SDK 通过以下方式提供对所有 API 方法的访问: Client 对象。除了一些有状态的特殊情况(chat 和 live-api sessions),这些都是无状态函数。为了实用性和统一性,返回的对象是 pydantic 类。

python
from google import genai
client = genai.Client()

response = client.models.generate_content(
  model='gemini-3.8-flash',
  contents='Tell me a story in 300 words.'
)
print(response.text)

print(response.model_dump_json(
  exclude_none=True, indent=4))

图像 #

之前

python
import google.generativeai as genai

model = genai.GenerativeModel('gemini-3.8-flash')
response = model.generate_content([
    'Tell me a story based on this image',
    Image.open(image_path)
])
print(response.text)

之后

新型 SDK 中存在许多相同的便利功能。例如, PIL.Image 对象会自动转换。

python
from google import genai
from PIL import Image

client = genai.Client()

response = client.models.generate_content(
  model='gemini-3.8-flash',
  contents=[
      'Tell me a story based on this image',
      Image.open(image_path)
  ]
)
print(response.text)

流式输出 #

之前

python
import google.generativeai as genai

response = model.generate_content(
    "Write a cute story about cats.",
    stream=True)
for chunk in response:
    print(chunk.text)

之后

python
from google import genai

client = genai.Client()

for chunk in client.models.generate_content_stream(
  model='gemini-3.8-flash',
  contents='Tell me a story in 300 words.'
):
    print(chunk.text)

配置 #

之前

python
import google.generativeai as genai

model = genai.GenerativeModel(
  'gemini-3.8-flash',
    system_instruction='you are a story teller for kids under 5 years old',
    generation_config=genai.GenerationConfig(
      max_output_tokens=400,
      top_k=2,
      top_p=0.5,
      temperature=0.5,
      response_mime_type='application/json',
      stop_sequences=['\n'],
    )
)
response = model.generate_content('tell me a story in 100 words')

之后

对于新 SDK 中的所有方法,所需参数均作为关键字参数提供。所有可选输入均在 config 论点。配置参数可以指定为 Python 字典或 Config 课程在 google.genai.types 命名空间。为了实用性和统一性,所有定义在 types 模块是 pydantic 类。

python
from google import genai
from google.genai import types

client = genai.Client()

response = client.models.generate_content(
model='gemini-3.8-flash',
contents='Tell me a story in 100 words.',
config=types.GenerateContentConfig(
    system_instruction='you are a story teller for kids under 5 years old',
    max_output_tokens= 400,
    top_k= 2,
    top_p= 0.5,
    temperature= 0.5,
    response_mime_type= 'application/json',
    stop_sequences= ['\n'],
    seed=42,
),
)

安全设置 #

生成带有安全设置的响应:

之前

python
import google.generativeai as genai

model = genai.GenerativeModel('gemini-3.8-flash')
response = model.generate_content(
    'say something bad',
    safety_settings={
        'HATE': 'BLOCK_ONLY_HIGH',
        'HARASSMENT': 'BLOCK_ONLY_HIGH',
  }
)

之后

python
from google import genai
from google.genai import types

client = genai.Client()

response = client.models.generate_content(
  model='gemini-3.8-flash',
  contents='say something bad',
  config=types.GenerateContentConfig(
      safety_settings= [
          types.SafetySetting(
              category='HARM_CATEGORY_HATE_SPEECH',
              threshold='BLOCK_ONLY_HIGH'
          ),
      ]
  ),
)

异步 #

之前

python
import google.generativeai as genai

model = genai.GenerativeModel('gemini-3.8-flash')
response = model.generate_content_async(
    'tell me a story in 100 words'
)

之后

要将新的 SDK 与 asyncio,有一个单独的 async 下每个方法的实现 client.aio.

python
from google import genai

client = genai.Client()

response = await client.aio.models.generate_content(
  model='gemini-3.8-flash',
  contents='Tell me a story in 300 words.'
)

聊天 #

开始聊天并向模特发送消息:

之前

python
import google.generativeai as genai

model = genai.GenerativeModel('gemini-3.8-flash')
chat = model.start_chat()

response = chat.send_message(
    "Tell me a story in 100 words")
response = chat.send_message(
    "What happened after that?")

之后

python
from google import genai

client = genai.Client()

chat = client.chats.create(model='gemini-3.8-flash')

response = chat.send_message(
    message='Tell me a story in 100 words')
response = chat.send_message(
    message='What happened after that?')

函数调用 #

之前

python
import google.generativeai as genai
from enum import Enum

def get_current_weather(location: str) -> str:
    """Get the current whether in a given location.

    Args:
        location: required, The city and state, e.g. San Franciso, CA
        unit: celsius or fahrenheit
    """
    print(f'Called with: {location=}')
    return "23C"

model = genai.GenerativeModel(
    model_name="gemini-3.8-flash",
    tools=[get_current_weather]
)

response = model.generate_content("What is the weather in San Francisco?")
function_call = response.candidates[0].parts[0].function_call

之后

在新的SDK中,默认为自动函数调用。在这里,您禁用它。

python
from google import genai
from google.genai import types

client = genai.Client()

def get_current_weather(location: str) -> str:
  """Get the current whether in a given location.

  Args:
      location: required, The city and state, e.g. San Franciso, CA
      unit: celsius or fahrenheit
  """
  print(f'Called with: {location=}')
  return "23C"

response = client.models.generate_content(
model='gemini-3.8-flash',
contents="What is the weather like in Boston?",
config=types.GenerateContentConfig(
    tools=[get_current_weather],
    automatic_function_calling={'disable': True},
),
)

function_call = response.candidates[0].content.parts[0].function_call

自动函数调用 #

之前

旧版SDK仅支持聊天中自动函数调用。在新的 SDK 中,这是默认行为 generate_content.

python
import google.generativeai as genai

def get_current_weather(city: str) -> str:
  return "23C"

model = genai.GenerativeModel(
  model_name="gemini-3.8-flash",
  tools=[get_current_weather]
)

chat = model.start_chat(
  enable_automatic_function_calling=True)
result = chat.send_message("What is the weather in San Francisco?")

之后

python
from google import genai
from google.genai import types
client = genai.Client()

def get_current_weather(city: str) -> str:
    return "23C"

response = client.models.generate_content(
  model='gemini-3.8-flash',
  contents="What is the weather like in Boston?",
  config=types.GenerateContentConfig(
      tools=[get_current_weather]
  ),
)

代码执行 #

代码执行是一个允许模型生成Python代码、运行它并返回结果的工具。

之前

python
import google.generativeai as genai

model = genai.GenerativeModel(
    model_name="gemini-3.8-flash",
    tools="code_execution"
)

result = model.generate_content(
  "What is the sum of the first 50 prime numbers? Generate and run code for "
  "the calculation, and make sure you get all 50.")

之后

python
from google import genai
from google.genai import types

client = genai.Client()

response = client.models.generate_content(
    model='gemini-3.8-flash',
    contents='What is the sum of the first 50 prime numbers? Generate and run '
            'code for the calculation, and make sure you get all 50.',
    config=types.GenerateContentConfig(
        tools=[types.Tool(code_execution=types.ToolCodeExecution)],
    ),
)

搜索事实依据 #

GoogleSearch (Gemini>=2.0) 和 GoogleSearchRetrieval (Gemini < 2.0) 是允许模型检索事实依据的公共网络数据的工具,由 Google 提供支持。

之前

python
import google.generativeai as genai

model = genai.GenerativeModel('gemini-3.8-flash')
response = model.generate_content(
    contents="what is the Google stock price?",
    tools='google_search_retrieval'
)

之后

python
from google import genai
from google.genai import types

client = genai.Client()

response = client.models.generate_content(
    model='gemini-3.8-flash',
    contents='What is the Google stock price?',
    config=types.GenerateContentConfig(
        tools=[
            types.Tool(
                google_search=types.GoogleSearch()
            )
        ]
    )
)

JSON 响应 #

生成 JSON 格式的答案。

之前

通过指定一个 response_schema 和设置 response_mime_type="application/json" 用户可以约束模型产生 JSON 遵循给定结构的响应。

python
import google.generativeai as genai
import typing_extensions as typing

class CountryInfo(typing.TypedDict):
  name: str
  population: int
  capital: str
  continent: str
  major_cities: list[str]
  gdp: int
  official_language: str
  total_area_sq_mi: int

model = genai.GenerativeModel(model_name="gemini-3.8-flash")
result = model.generate_content(
  "Give me information of the United States",
  generation_config=genai.GenerationConfig(
      response_mime_type="application/json",
      response_schema = CountryInfo
  ),
)

之后

新款SDK采用 pydantic 提供模式的类(尽管您可以传递 genai.types.Schema,或同等的 dict)。在可能的情况下,SDK 会解析返回的 JSON,并将结果返回为 response.parsed。如果您提供了 pydantic 类作为 SDK 将转换的模式 JSON 到该类的一个实例。

python
from google import genai
from pydantic import BaseModel

client = genai.Client()

class CountryInfo(BaseModel):
  name: str
  population: int
  capital: str
  continent: str
  major_cities: list[str]
  gdp: int
  official_language: str
  total_area_sq_mi: int

response = client.models.generate_content(
  model='gemini-3.8-flash',
  contents='Give me information of the United States.',
  config={
      'response_mime_type': 'application/json',
      'response_schema': CountryInfo,
  },
)

response.parsed

文件 #

上传 #

上传文件:

之前

python
import requests
import pathlib
import google.generativeai as genai

# Download file
response = requests.get(
    'https://storage.googleapis.com/generativeai-downloads/data/a11.txt')
pathlib.Path('a11.txt').write_text(response.text)

file = genai.upload_file(path='a11.txt')

model = genai.GenerativeModel('gemini-3.8-flash')
response = model.generate_content([
    'Can you summarize this file:',
    my_file
])
print(response.text)

之后

python
import requests
import pathlib
from google import genai

client = genai.Client()

# Download file
response = requests.get(
    'https://storage.googleapis.com/generativeai-downloads/data/a11.txt')
pathlib.Path('a11.txt').write_text(response.text)

my_file = client.files.upload(file='a11.txt')

response = client.models.generate_content(
    model='gemini-3.8-flash',
    contents=[
        'Can you summarize this file:',
        my_file
    ]
)
print(response.text)

列出并获取 #

列出上传的文件并获取带有文件名的上传文件:

之前

python
import google.generativeai as genai

for file in genai.list_files():
  print(file.name)

file = genai.get_file(name=file.name)

之后

python
from google import genai
client = genai.Client()

for file in client.files.list():
    print(file.name)

file = client.files.get(name=file.name)

删除 #

删除文件:

之前

python
import pathlib
import google.generativeai as genai

pathlib.Path('dummy.txt').write_text(dummy)
dummy_file = genai.upload_file(path='dummy.txt')

file = genai.delete_file(name=dummy_file.name)

之后

python
import pathlib
from google import genai

client = genai.Client()

pathlib.Path('dummy.txt').write_text(dummy)
dummy_file = client.files.upload(file='dummy.txt')

response = client.files.delete(name=dummy_file.name)

上下文缓存 #

上下文缓存允许用户将内容传递给模型一次,缓存输入 token,然后在后续调用中引用缓存的 token 以降低成本。

之前

python
import requests
import pathlib
import google.generativeai as genai
from google.generativeai import caching

# Download file
response = requests.get(
    'https://storage.googleapis.com/generativeai-downloads/data/a11.txt')
pathlib.Path('a11.txt').write_text(response.text)

# Upload file
document = genai.upload_file(path="a11.txt")

# Create cache
apollo_cache = caching.CachedContent.create(
    model="gemini-3.8-flash",
    system_instruction="You are an expert at analyzing transcripts.",
    contents=[document],
)

# Generate response
apollo_model = genai.GenerativeModel.from_cached_content(
    cached_content=apollo_cache
)
response = apollo_model.generate_content("Find a lighthearted moment from this transcript")

之后

python
import requests
import pathlib
from google import genai
from google.genai import types

client = genai.Client(http_options={"api_version": "v1beta"})

# Check which models support caching.
for m in client.models.list():
  for action in m.supported_actions:
    if action == "createCachedContent":
      print(m.name)
      break

# Download file
response = requests.get(
    'https://storage.googleapis.com/generativeai-downloads/data/a11.txt')
pathlib.Path('a11.txt').write_text(response.text)

# Upload file
document = client.files.upload(file='a11.txt')

# Create cache
model='gemini-3.8-flash'
apollo_cache = client.caches.create(
      model=model,
      config={
          'contents': [document],
          'system_instruction': 'You are an expert at analyzing transcripts.',
      },
  )

# Generate response
response = client.models.generate_content(
    model=model,
    contents='Find a lighthearted moment from this transcript',
    config=types.GenerateContentConfig(
        cached_content=apollo_cache.name,
    )
)

计数 token #

统计一次请求中token的数量。

之前

python
import google.generativeai as genai

model = genai.GenerativeModel('gemini-3.8-flash')
response = model.count_tokens(
    'The quick brown fox jumps over the lazy dog.')

之后

python
from google import genai

client = genai.Client()

response = client.models.count_tokens(
    model='gemini-3.8-flash',
    contents='The quick brown fox jumps over the lazy dog.',
)

生成图像 #

生成图像:

之前

python
#pip install https://github.com/google-gemini/generative-ai-python@imagen
import google.generativeai as genai

imagen = genai.ImageGenerationModel(
    "imagen-3.0-generate-001")
gen_images = imagen.generate_images(
    prompt="Robot holding a red skateboard",
    number_of_images=1,
    safety_filter_level="block_low_and_above",
    person_generation="allow_adult",
    aspect_ratio="3:4",
)

之后

python
from google import genai

client = genai.Client()

gen_images = client.models.generate_images(
    model='gemini-2.5-flash-image',
    prompt='Robot holding a red skateboard',
    config=types.GenerateImagesConfig(
        number_of_images= 1,
        safety_filter_level= "BLOCK_LOW_AND_ABOVE",
        person_generation= "ALLOW_ADULT",
        aspect_ratio= "3:4",
    )
)

for n, image in enumerate(gen_images.generated_images):
    pathlib.Path(f'{n}.png').write_bytes(
        image.image.image_bytes)

嵌入内容 #

生成内容嵌入。

之前

python
import google.generativeai as genai

response = genai.embed_content(
  model='models/gemini-embedding-001',
  content='Hello world'
)

之后

python
from google import genai

client = genai.Client()

response = client.models.embed_content(
  model='gemini-embedding-001',
  contents='Hello world',
)

搜索标题、API 名称或正文内容