Krótkie wprowadzenie do interfejsu Gemini API

Z tego przewodnika dowiesz się, jak zainstalować nasze biblioteki i wysłać pierwsze żądanie do interfejsu Gemini API.

Zanim zaczniesz

Musisz mieć klucz interfejsu Gemini API. Jeśli jeszcze go nie masz, możesz pobrać go bezpłatnie w Google AI Studio.

Instalowanie pakietu Google GenAI SDK

Python

Korzystając z Pythona 3.9 lub nowszego, zainstaluj google-genai za pomocą tego polecenia pip:

pip install -q -U google-genai

JavaScript

Jeśli używasz Node.js w wersji 18 lub nowszej, zainstaluj pakiet SDK Google Gen AI dla TypeScript i JavaScript za pomocą tego polecenia npm:

npm install @google/genai

Przeczytaj

Zainstaluj pakiet google.golang.org/genai w katalogu modułu za pomocą polecenia go get:

go get google.golang.org/genai

Java

Jeśli używasz Maven, możesz zainstalować google-genai, dodając do zależności poniższy kod:

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

Google Apps Script

  1. Aby utworzyć nowy projekt Apps Script, otwórz script.new.
  2. Kliknij Projekt bez nazwy.
  3. Zmień nazwę projektu Apps Script na AI Studio i kliknij Zmień nazwę.
  4. Ustaw klucz interfejsu API.
    1. Po lewej stronie kliknij Ustawienia projektu Ikona ustawień projektu.
    2. W sekcji Właściwości skryptu kliknij Dodaj właściwość skryptu.
    3. W polu Właściwość wpisz nazwę klucza: GEMINI_API_KEY.
    4. W polu Wartość wpisz wartość klucza interfejsu API.
    5. Kliknij Zapisz właściwości skryptu.
  5. Zastąp zawartość pliku Code.gs tym kodem:

Wysyłanie pierwszej prośby

Oto przykład, który używa metody generateContent do wysłania żądania do interfejsu Gemini API przy użyciu modelu Gemini 2.5 Flash.

Jeśli ustawisz klucz interfejsu API jako zmienną środowiskową GEMINI_API_KEY, zostanie on automatycznie pobrany przez klienta podczas korzystania z bibliotek Gemini API. W przeciwnym razie podczas inicjowania klienta musisz przekazać klucz interfejsu API jako argument.

Pamiętaj, że wszystkie przykłady kodu w dokumentacji interfejsu Gemini API zakładają, że masz ustawioną zmienną środowiskową 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();

Przeczytaj

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

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

W wielu naszych przykładowych fragmentach kodu funkcja „Myślenie” jest domyślnie włączona.

Wiele przykładów kodu na tej stronie korzysta z modelu Gemini 2.5 Flash, który ma domyślnie włączoną funkcję „myślenia”, co poprawia jakość odpowiedzi. Pamiętaj, że może to wydłużyć czas odpowiedzi i zwiększyć zużycie tokenów. Jeśli priorytetem jest dla Ciebie szybkość lub chcesz zminimalizować koszty, możesz wyłączyć tę funkcję, ustawiając budżet na myślenie na zero, jak pokazano w przykładach poniżej. Więcej informacji znajdziesz w przewodniku po myśleniu.

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

Przeczytaj

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

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

Co dalej?

Skoro udało Ci się wysłać pierwsze żądanie do interfejsu API, możesz zapoznać się z tymi przewodnikami, które pokazują Gemini w działaniu: