이 빠른 시작에서는 라이브러리를 설치하고 첫 번째 Gemini API 요청을 만드는 방법을 보여줍니다.
시작하기 전에
Gemini API 키가 필요합니다. 아직 키가 없다면 Google AI Studio에서 무료로 키를 받으세요.
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
자바
Maven을 사용하는 경우 종속 항목에 다음을 추가하여 google-genai를 설치할 수 있습니다.
<dependencies>
<dependency>
<groupId>com.google.genai</groupId>
<artifactId>google-genai</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
Apps Script
- 새 Apps Script 프로젝트를 만들려면 script.new로 이동하세요.
- 제목 없는 프로젝트를 클릭합니다.
- Apps Script 프로젝트의 이름을 AI Studio로 바꾸고 이름 바꾸기를 클릭합니다.
- API 키를 설정합니다.
- 왼쪽에서 프로젝트 설정
을 클릭합니다.
- 스크립트 속성에서 스크립트 속성 추가를 클릭합니다.
- 속성에 키 이름
GEMINI_API_KEY
를 입력합니다. - 값에 API 키 값을 입력합니다.
- 스크립트 속성 저장을 클릭합니다.
- 왼쪽에서 프로젝트 설정
Code.gs
파일 콘텐츠를 다음 코드로 바꿉니다.
첫 번째 요청하기
다음은 generateContent
메서드를 사용하여 Gemini 2.5 Flash 모델을 통해 Gemini API에 요청을 전송하는 예입니다.
API 키를 환경 변수 GEMINI_API_KEY
로 설정하면 Gemini API 라이브러리를 사용할 때 클라이언트에서 자동으로 선택합니다.
그렇지 않으면 클라이언트를 초기화할 때 API 키를 인수로 전달해야 합니다.
Gemini API 문서의 모든 코드 샘플은 환경 변수 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)
자바스크립트
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())
}
자바
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"
}
]
}
]
}'
많은 코드 샘플에서 '생각'이 기본적으로 사용 설정되어 있습니다.
이 사이트의 많은 코드 샘플은 대답 품질을 향상하기 위해 기본적으로 '사고' 기능이 사용 설정된 Gemini 2.5 Flash 모델을 사용합니다. 이렇게 하면 응답 시간과 토큰 사용량이 늘어날 수 있습니다. 속도를 우선시하거나 비용을 최소화하려면 아래 예와 같이 사고 예산을 0으로 설정하여 이 기능을 사용 중지하면 됩니다. 자세한 내용은 생각 가이드를 참고하세요.
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)
자바스크립트
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);
}
다음 단계
첫 번째 API 요청을 완료했으므로 Gemini의 작동 방식을 보여주는 다음 가이드를 살펴보세요.