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

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

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

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

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

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

pip install -q -U google-genai

Используя 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
  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.

from google import genai

client = genai.Client(api_key="YOUR_API_KEY")

response = client.models.generate_content(
    model="gemini-2.0-flash", contents="Explain how AI works in a few words"
)
print(response.text)
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.0-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.0-flash",
        genai.Text("Explain how AI works in a few words"),
        nil,
    )
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(result.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.0-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.0-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"
          }
        ]
      }
    ]
  }'

Что дальше?

Теперь, когда вы сделали свой первый запрос к API, вам, возможно, захочется изучить следующие руководства, демонстрирующие Gemini в действии: