В этом кратком руководстве показано, как установить наши библиотеки и сделать первый запрос 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> Скрипт приложений
- Чтобы создать новый проект Apps Script, перейдите в script.new .
- Нажмите Проект без названия .
- Переименуйте проект Apps Script в AI Studio и нажмите «Переименовать» .
- Установите свой ключ API
- Слева нажмите «Настройки проекта» .
.
- В разделе «Свойства скрипта» нажмите «Добавить свойство скрипта» .
- Для Property введите имя ключа:
GEMINI_API_KEY. - В поле Значение введите значение ключа API.
- Нажмите Сохранить свойства скрипта .
- Слева нажмите «Настройки проекта» .
- Замените содержимое файла
Code.gsследующим кодом:
Сделайте свой первый запрос
Вот пример, в котором метод generateContent используется для отправки запроса к API Gemini с использованием модели Gemini 2.5 Flash.
Если вы укажете свой ключ API как переменную окружения GEMINI_API_KEY , он будет автоматически выбран клиентом при использовании библиотек API Gemini . В противном случае вам потребуется передать свой ключ API в качестве аргумента при инициализации клиента.
Обратите внимание, что все примеры кода в документации API Gemini предполагают, что вы установили переменную среды GEMINI_API_KEY .
Питон
from google import genai # The client gets the API key from the environment variable `GEMINI_API_KEY`. client = genai.Client() 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"; // The client gets the API key from the environment variable `GEMINI_API_KEY`. const ai = new GoogleGenAI({}); 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() // The client gets the API key from the environment variable `GEMINI_API_KEY`. client, err := genai.NewClient(ctx, nil) 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 `GEMINI_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'; const options = { method: 'POST', contentType: 'application/json', headers: { 'x-goog-api-key': apiKey, }, 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" \ -H "x-goog-api-key: $GEMINI_API_KEY" \ -H 'Content-Type: application/json' \ -X POST \ -d '{ "contents": [ { "parts": [ { "text": "Explain how AI works in a few words" } ] } ] }' Что дальше?
Теперь, когда вы сделали свой первый запрос к API, вам, возможно, захочется изучить следующие руководства, демонстрирующие Gemini в действии: