欢迎回来

登录 EAKE AI,继续您的智能之旅

忘记密码?
还没有账号?立即注册

Google Gemini SDK 使用指南

2026-05-07 · Google AI

概述

Google Gen AI Python SDK 为开发者提供了将 Google 生成式模型集成到 Python 应用中的接口,支持 Gemini Developer API 和 Vertex AI API。

安装

pip install google-genai

快速开始

Gemini Developer API

from google import genai
from google.genai import types

client = genai.Client(api_key='GEMINI_API_KEY')

response = client.models.generate_content(
    model='gemini-2.5-flash',
    contents=types.Part.from_text(text='Why is the sky blue?'),
    config=types.GenerateContentConfig(
        temperature=0,
        top_p=0.95,
        top_k=20,
    ),
)
print(response.text)

Vertex AI

from google import genai

client = genai.Client(
    vertexai=True,
    project='your-project-id',
    location='us-central1'
)

环境变量配置

Gemini Developer API

export GEMINI_API_KEY='your-api-key'

Vertex AI

export GOOGLE_GENAI_USE_VERTEXAI=true
export GOOGLE_CLOUD_PROJECT='your-project-id'
export GOOGLE_CLOUD_LOCATION='us-central1'

客户端管理

# 使用上下文管理器自动关闭
with genai.Client() as client:
    response = client.models.generate_content(
        model='gemini-2.5-flash',
        contents='Hello'
    )

# 异步客户端
async with genai.Client().aio as aclient:
    response = await aclient.models.generate_content(
        model='gemini-2.5-flash',
        contents='Hello'
    )

API 版本选择

from google.genai import types

client = genai.Client(
    api_key='GEMINI_API_KEY',
    http_options=types.HttpOptions(api_version='v1')
)

可用模型

模型说明
gemini-2.5-flash快速响应,适合日常任务
gemini-2.5-pro高精度推理,复杂任务
gemini-2.0-flash上一代快速模型

评论区

发表评论