Panduan memulai Gemini API

Panduan memulai ini menunjukkan cara menginstal library kami dan membuat permintaan Gemini API pertama Anda.

Sebelum memulai

Anda memerlukan kunci Gemini API. Jika belum memilikinya, Anda dapat mendapatkannya secara gratis di Google AI Studio.

Menginstal Google GenAI SDK

Python

Dengan menggunakan Python 3.9+, instal paket google-genai menggunakan perintah pip berikut:

pip install -q -U google-genai

JavaScript

Dengan menggunakan Node.js v18+, instal Google Gen AI SDK untuk TypeScript dan JavaScript menggunakan perintah npm berikut:

npm install @google/genai

Go

Instal google.golang.org/genai di direktori modul Anda menggunakan perintah go get:

go get google.golang.org/genai

Java

Jika menggunakan Maven, Anda dapat menginstal google-genai dengan menambahkan kode berikut ke dependensi Anda:

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

Apps Script

  1. Untuk membuat project Apps Script baru, buka script.new.
  2. Klik Project tanpa judul.
  3. Ganti nama project Apps Script AI Studio, lalu klik Ganti Nama.
  4. Tetapkan kunci API Anda
    1. Di sebelah kiri, klik Setelan Project Ikon untuk setelan project.
    2. Di bagian Script Properties, klik Add script property.
    3. Untuk Property, masukkan nama kunci: GEMINI_API_KEY.
    4. Untuk Nilai, masukkan nilai untuk kunci API.
    5. Klik Simpan properti skrip.
  5. Ganti konten file Code.gs dengan kode berikut:

Membuat permintaan pertama Anda

Berikut adalah contoh yang menggunakan metode generateContent untuk mengirim permintaan ke Gemini API menggunakan model Gemini 2.5 Flash.

Jika Anda menetapkan kunci API sebagai variabel lingkungan GEMINI_API_KEY, kunci tersebut akan diambil secara otomatis oleh klien saat menggunakan library Gemini API. Jika tidak, Anda harus meneruskan kunci API sebagai argumen saat melakukan inisialisasi klien.

Perhatikan bahwa semua contoh kode dalam dokumen Gemini API mengasumsikan bahwa Anda telah menetapkan variabel lingkungan GEMINI_API_KEY.

Python

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

Go

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

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

Apps Script

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

REST

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

"Berpikir" diaktifkan secara default di banyak contoh kode kami

Banyak contoh kode di situs ini menggunakan model Gemini 2.5 Flash, yang mengaktifkan fitur "pemikiran" secara default untuk meningkatkan kualitas respons. Perlu diperhatikan bahwa hal ini dapat meningkatkan waktu respons dan penggunaan token. Jika Anda memprioritaskan kecepatan atau ingin meminimalkan biaya, Anda dapat menonaktifkan fitur ini dengan menetapkan anggaran pemikiran ke nol, seperti yang ditunjukkan pada contoh di bawah. Untuk mengetahui detail selengkapnya, lihat panduan pemikiran.

Python

from google import genai
from google.genai import types

client = genai.Client()

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

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, err := genai.NewClient(ctx, nil)
  if err != nil {
      log.Fatal(err)
  }

  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" \
  -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"
          }
        ]
      }
    ]
    "generationConfig": {
      "thinkingConfig": {
        "thinkingBudget": 0
      }
    }
  }'

Apps Script

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

Langkah berikutnya

Setelah membuat permintaan API pertama, Anda dapat mempelajari panduan berikut yang menunjukkan cara kerja Gemini: