Gemini API 빠른 시작

이 빠른 시작에서는 라이브러리를 설치하고 첫 번째 Gemini API 요청을 실행하는 방법을 보여줍니다.

시작하기 전에

Gemini API 키가 필요합니다. 아직 키가 없다면 Google AI 스튜디오에서 무료로 키를 가져올 수 있습니다.

Google GenAI SDK 설치

Python

Python 3.9 이상을 사용하여 다음 pip 명령어를 사용하여 google-genai 패키지를 설치합니다.

pip install -q -U google-genai

자바스크립트

Node.js v18 이상을 사용하여 다음 npm 명령어를 사용하여 TypeScript 및 JavaScript용 Google Gen AI SDK를 설치합니다.

npm install @google/genai

Go

go get 명령어를 사용하여 모듈 디렉터리에 google.golang.org/genai를 설치합니다.

go get google.golang.org/genai

Apps Script

  1. 새 Apps Script 프로젝트를 만들려면 script.new로 이동합니다.
  2. 제목 없는 프로젝트를 클릭합니다.
  3. Apps Script 프로젝트의 이름을 AI 스튜디오로 바꾸고 이름 바꾸기를 클릭합니다.
  4. API 키 설정
    1. 왼쪽에서 프로젝트 설정 프로젝트 설정의 아이콘을 클릭합니다.
    2. 스크립트 속성에서 스크립트 속성 추가를 클릭합니다.
    3. 속성에 키 이름 GEMINI_API_KEY을 입력합니다.
    4. 에 API 키 값을 입력합니다.
    5. 스크립트 속성 저장을 클릭합니다.
  5. Code.gs 파일 콘텐츠를 다음 코드로 바꿉니다.

첫 번째 요청하기

generateContent 메서드를 사용하여 Gemini API에 요청을 보냅니다.

Python

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

Go

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

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

REST

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가 작동하는 모습을 보여주는 다음 가이드를 살펴보세요.