Krótkie wprowadzenie do interfejsu Gemini API

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

Zanim zaczniesz

Potrzebujesz klucza interfejsu Gemini API. Jeśli jeszcze go nie masz, możesz uzyskać go bezpłatnie w Google AI Studio.

Instalowanie pakietu Google GenAI SDK

Python

Za pomocą Pythona 3.9 lub nowszego zainstaluj google-genai pakiet, używając tego polecenia pip:

pip install -q -U google-genai

JavaScript

Za pomocą Node.js w wersji 18 lub nowszej zainstaluj pakiet SDK Google Gen AI do TypeScript i JavaScript, używając tego polecenia npm:

npm install @google/genai

Przeczytaj

Zainstaluj pakiet google.golang.org/genai w katalogu modułów, używając polecenia go get:

go get google.golang.org/genai

Java

Jeśli używasz Mavena, możesz zainstalować google-genai, dodając te zależności do swoich zależności:

<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 Rename (Zmień nazwę).
  4. Skonfiguruj 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:

Przesyłanie pierwszej prośby

Oto przykład użycia 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, klient automatycznie go wczyta podczas korzystania z bibliotek interfejsu Gemini API. W przeciwnym razie musisz przekazać klucz API jako argument podczas inicjowania klienta.

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 opcja „Myśl” jest domyślnie włączona.

Wiele przykładów kodu na tej stronie korzysta z modelu Gemini 2.5 Flash, w którym domyślnie włączona jest funkcja myślenia, aby poprawić jakość odpowiedzi. Pamiętaj, że może to wydłużyć czas odpowiedzi i zwiększyć wykorzystanie tokenów. Jeśli stawiasz na 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 procesie myślenia.

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?

Po wysłaniu pierwszego żądania interfejsu API warto zapoznać się z tymi przewodnikami, które pokazują, jak działa Gemini: