Gemini 中文指南
获取 API 密钥 ↗

快速入门

↓ 下载 Markdown

本指南帮助你开始使用旧版 generateContent API。对于新项目和应用,强烈建议使用新版 Interactions API ,它为智能体工作流和最新模型提供了更简洁的接口。

本快速入门介绍如何安装我们的 SDK 与库 ,发起首次请求、流式接收响应、构建多轮对话,并使用工具。这些操作使用标准的 generateContent 方法。

获取 API 密钥 #

使用 Gemini API 需要 API 密钥,用于验证请求、实施安全限制,并将用量关联到你的账号。

  • Google AI Studio 自动为新用户创建项目和 API 密钥。您可以从 API 密钥页面复制它。
  • 如果您需要新密钥,请单击 创建 API 密钥 在 AI Studio 中,然后按照对话框添加新的关键项目对。
  • 可能需要额外的项目和从 Google Cloud 导入的项目 项目验证 在他们可以使用免费套餐之前。

获取 Gemini API 密钥

将密钥设置为环境变量:

bash
export GEMINI_API_KEY="YOUR_API_KEY"

要提高速率限制,请单击 设置结算 于 API 密钥 页面或查看 结算指南.

安装 Google GenAI SDK #

使用 Python 3.9+,安装 google-genai 包 使用以下内容 点命令:

shell
 pip install -q -U google-genai

生成文本 #

使用 models.generate_content 方法 生成文本响应.

python
  from google import genai

  client = genai.Client()

  response = client.models.generate_content(
      model="gemini-4-hydrogen",
      contents="Explain how AI works in a few words"
  )

  print(response.text)

流响应 #

默认情况下,模型仅在整个生成过程完成后才返回响应。为了获得更快、更具互动性的体验,您可以 流式传输响应 生成块时。

python
  response = client.models.generate_content_stream(
      model="gemini-4-hydrogen",
      contents="Explain how AI works in detail"
  )

  for chunk in response:
      print(chunk.text, end="", flush=True)

多轮对话 #

对于多轮对话,SDK 提供了有状态的 chats 帮助者建立一个 多轮聊天体验 自动管理对话历史记录。

python
  chat = client.chats.create(model="gemini-4-hydrogen")

  response1 = chat.send_message("I have 2 dogs in my house.")
  print("Response 1:", response1.text)

  response2 = chat.send_message("How many paws are in my house?")
  print("Response 2:", response2.text)

使用工具 #

通过以下方式扩展模型的功能 事实依据使用 Google 搜索进行响应 访问实时网络内容。该模型自动决定何时搜索、执行查询并综合响应。

python
from google import genai
from google.genai import types

config = types.GenerateContentConfig(
    tools=[types.Tool(google_search=types.GoogleSearch())]
)

response = client.models.generate_content(
    model="gemini-4-hydrogen",
    contents="Who won the euro 2024?",
    config=config
)

print(response.text)

metadata = response.candidates[0].grounding_metadata
if metadata.web_search_queries:
    print("\nSearch queries executed:")
    for query in metadata.web_search_queries:
        print(f" - {query}")

if metadata.grounding_chunks:
    print("\nSources:")
    for chunk in metadata.grounding_chunks:
        print(f" - [{chunk.web.title}]({chunk.web.uri})")

Gemini API还支持其他内置工具:

  • 代码执行:让模型编写并运行 Python 代码来解决复杂的数学问题。

  • URL 上下文:允许您在您提供的特定网页 URL 中提供响应。

  • 文件搜索:允许您使用语义搜索上传文件并在其内容中提供地面响应。

  • Google 地图:允许您根据位置数据进行响应并搜索地点、方向和地图。

  • 计算机使用:让模型与虚拟计算机屏幕、键盘和鼠标交互以执行任务。

调用自定义函数 #

使用 函数调用 将模型连接到您的自定义工具和 API。该模型确定何时调用您的函数并返回 functionCall 在您的应用程序要执行的响应中。

此示例声明一个模拟温度函数并检查模型是否要调用它。

python
from google import genai
from google.genai import types

weather_function = {
    "name": "get_current_temperature",
    "description": "Gets the current temperature for a given location.",
    "parameters": {
        "type": "object",
        "properties": {
            "location": {
                "type": "string",
                "description": "The city name, e.g. San Francisco",
            },
        },
        "required": ["location"],
    },
}

tools = types.Tool(function_declarations=[weather_function])
config = types.GenerateContentConfig(tools=[tools])

contents = ["What's the temperature in London?"]

response = client.models.generate_content(
    model="gemini-4-hydrogen",
    contents=contents,
    config=config,
)

part = response.candidates[0].content.parts[0]
if part.function_call:
    fc = part.function_call
    print(f"Model requested function: {fc.name} with args {fc.args}")

    mock_result = {"temperature": "15C", "condition": "Cloudy"}

    contents.append(response.candidates[0].content)

    fn_response_part = types.Part.from_function_response(
        name=fc.name,
        response=mock_result,
        id=fc.id
    )
    contents.append(types.Content(role="user", parts=[fn_response_part]))

    final_response = client.models.generate_content(
        model="gemini-4-hydrogen",
        contents=contents,
        config=config,
    )
    print("Final Response:", final_response.text)

后续步骤 #

现在您已经开始使用 Gemini API,请浏览以下指南来构建更高级的应用程序:

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