Gemini API 快速入门

本快速入门将向您介绍如何安装我们的并发出您的第一个 Gemini API 请求。

准备工作

您需要一个 Gemini API 密钥。如果您还没有 API 密钥,可以在 Google AI Studio 中免费获取

安装 Google GenAI SDK

Python

使用 Python 3.9 及更高版本时,请使用以下 pip 命令安装 google-genai 软件包

pip install -q -U google-genai 

JavaScript

使用 Node.js v18+,使用以下 npm 命令安装 适用于 TypeScript 和 JavaScript 的 Google Gen AI SDK

npm install @google/genai 

Go

使用 go get 命令在模块目录中安装 google.golang.org/genai

go get google.golang.org/genai 

Java

如果您使用的是 Maven,则可以通过将以下代码添加到依赖项中来安装 google-genai

<dependencies>   <dependency>     <groupId>com.google.genai</groupId>     <artifactId>google-genai</artifactId>     <version>1.0.0</version>   </dependency> </dependencies> 

Apps 脚本

  1. 如需创建新的 Apps 脚本项目,请前往 script.new
  2. 点击 Untitled project
  3. 将 Apps 脚本项目重命名为 AI Studio,然后点击重命名
  4. 设置 API 密钥
    1. 点击左侧的项目设置 项目设置的图标
    2. 脚本属性下,点击添加脚本属性
    3. 对于媒体资源,输入键名称:GEMINI_API_KEY
    4. Value(值)中,输入 API 密钥的值。
    5. 点击保存脚本属性
  5. Code.gs 文件内容替换为以下代码:

提交第一个请求

下面的示例使用 generateContent 方法使用 Gemini 2.5 Flash 模型向 Gemini API 发送请求。

Python

from google import genai  client = genai.Client(api_key="YOUR_API_KEY")  response = client.models.generate_content(     model="gemini-2.5-flash", contents="Explain how AI works in a few words" ) print(response.text) 

JavaScript

import { GoogleGenAI } from "@google/genai";  const ai = new GoogleGenAI({ apiKey: "YOUR_API_KEY" });  async function main() {   const response = await ai.models.generateContent({     model: "gemini-2.5-flash",     contents: "Explain how AI works in a few words",   });   console.log(response.text); }  main(); 

Go

package main  import (     "context"     "fmt"     "log"      "google.golang.org/genai" )  func main() {     ctx := context.Background()     client, err := genai.NewClient(ctx, &genai.ClientConfig{         APIKey:  "YOUR_API_KEY",         Backend: genai.BackendGeminiAPI,     })     if err != nil {         log.Fatal(err)     }      result, err := client.Models.GenerateContent(         ctx,         "gemini-2.5-flash",         genai.Text("Explain how AI works in a few words"),         nil,     )     if err != nil {         log.Fatal(err)     }     fmt.Println(result.Text()) } 

Java

package com.example;  import com.google.genai.Client; import com.google.genai.types.GenerateContentResponse;  public class GenerateTextFromTextInput {   public static void main(String[] args) {     // The client gets the API key from the environment variable `GOOGLE_API_KEY`.     Client client = new Client();      GenerateContentResponse response =         client.models.generateContent(             "gemini-2.5-flash",             "Explain how AI works in a few words",             null);      System.out.println(response.text());   } } 

Apps 脚本

// See https://developers.google.com/apps-script/guides/properties // for instructions on how to set the API key. const apiKey = PropertiesService.getScriptProperties().getProperty('GEMINI_API_KEY'); function main() {   const payload = {     contents: [       {         parts: [           { text: 'Explain how AI works in a few words' },         ],       },     ],   };    const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=${apiKey}`;   const options = {     method: 'POST',     contentType: 'application/json',     payload: JSON.stringify(payload)   };    const response = UrlFetchApp.fetch(url, options);   const data = JSON.parse(response);   const content = data['candidates'][0]['content']['parts'][0]['text'];   console.log(content); } 

REST

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$YOUR_API_KEY" \   -H 'Content-Type: application/json' \   -X POST \   -d '{     "contents": [       {         "parts": [           {             "text": "Explain how AI works in a few words"           }         ]       }     ]   }' 

我们的许多代码示例默认处于“思考”状态

本网站上的许多代码示例都使用 Gemini 2.5 Flash 模型,该模型默认启用了“思考”功能,以提高回答质量。请注意,这可能会增加响应时间和令牌用量。如果您优先考虑速度或希望尽可能降低费用,可以将思考预算设为零来停用此功能,如以下示例所示。如需了解详情,请参阅思考指南

Python

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="Explain how AI works in a few words",     config=types.GenerateContentConfig(         thinking_config=types.ThinkingConfig(thinking_budget=0) # Disables thinking     ), ) print(response.text) 

JavaScript

import { GoogleGenAI } from "@google/genai";  const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });  async function main() {   const response = await ai.models.generateContent({     model: "gemini-2.5-flash",     contents: "Explain how AI works in a few words",     config: {       thinkingConfig: {         thinkingBudget: 0, // Disables thinking       },     }   });   console.log(response.text); }  await main(); 

Go

package main  import (   "context"   "fmt"   "os"   "google.golang.org/genai" )  func main() {    ctx := context.Background()   client, _ := genai.NewClient(ctx, &genai.ClientConfig{       APIKey:  os.Getenv("GEMINI_API_KEY"),       Backend: genai.BackendGeminiAPI,   })    result, _ := client.Models.GenerateContent(       ctx,       "gemini-2.5-flash",       genai.Text("Explain how AI works in a few words"),       &genai.GenerateContentConfig{         ThinkingConfig: &genai.ThinkingConfig{             ThinkingBudget: int32(0), // Disables thinking         },       }   )    fmt.Println(result.Text()) } 

REST

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=$GEMINI_API_KEY" \   -H 'Content-Type: application/json' \   -X POST \   -d '{     "contents": [       {         "parts": [           {             "text": "Explain how AI works in a few words"           }         ]       }     ]     "generationConfig": {       "thinkingConfig": {         "thinkingBudget": 0       }     }   }' 

Apps 脚本

// See https://developers.google.com/apps-script/guides/properties // for instructions on how to set the API key. const apiKey = PropertiesService.getScriptProperties().getProperty('GEMINI_API_KEY');  function main() {   const payload = {     contents: [       {         parts: [           { text: 'Explain how AI works in a few words' },         ],       },     ],   };    const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=${apiKey}`;   const options = {     method: 'POST',     contentType: 'application/json',     payload: JSON.stringify(payload)   };    const response = UrlFetchApp.fetch(url, options);   const data = JSON.parse(response);   const content = data['candidates'][0]['content']['parts'][0]['text'];   console.log(content); } 

后续步骤

现在,您已发出第一个 API 请求,不妨探索以下指南,了解 Gemini 的运作方式: