Краткое руководство по API Gemini

В этом кратком руководстве показано, как установить наши библиотеки и сделать первый запрос API Gemini.

Прежде чем начать

Вам нужен ключ API Gemini. Если у вас его еще нет, вы можете получить его бесплатно в Google AI Studio .

Установите Google GenAI SDK

Питон

Используя Python 3.9+ , установите пакет google-genai с помощью следующей команды pip :

pip install -q -U google-genai

JavaScript

Используя Node.js v18+ , установите Google Gen AI SDK для TypeScript и JavaScript с помощью следующей команды npm :

npm install @google/genai

Идти

Установите google.golang.org/genai в каталог вашего модуля с помощью команды go get :

go get google.golang.org/genai

Ява

Если вы используете Maven, вы можете установить google-genai , добавив следующее в свои зависимости:

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

Скрипт приложений

  1. Чтобы создать новый проект Apps Script, перейдите по адресу script.new .
  2. Нажмите «Проект без названия» .
  3. Переименуйте проект Apps Script в AI Studio и нажмите «Переименовать» .
  4. Установите свой ключ API
    1. Слева нажмите «Настройки проекта» . Значок настроек проекта .
    2. В разделе «Свойства скрипта» нажмите «Добавить свойство скрипта» .
    3. Для свойства введите имя ключа: GEMINI_API_KEY .
    4. В поле Значение введите значение ключа API.
    5. Нажмите Сохранить свойства скрипта .
  5. Замените содержимое файла Code.gs следующим кодом:

Сделайте свой первый запрос

Вот пример, в котором метод generateContent используется для отправки запроса к API Gemini с использованием флэш-модели Gemini 2.5.

Питон

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();

Идти

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())
}

Ява

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());
  }
}

Скрипт приложений

// 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);
}

ОТДЫХ

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 , в которой функция «мышления» включена по умолчанию для повышения качества ответа. Вы должны знать, что это может увеличить время ответа и использование токенов. Если вы отдаете приоритет скорости или хотите минимизировать затраты, вы можете отключить эту функцию, установив бюджет мышления на ноль, как показано в примерах ниже. Для получения более подробной информации см. руководство по мышлению .

Питон

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();

Идти

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())
}

ОТДЫХ

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
      }
    }
  }'

Скрипт приложений

// 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 в действии: