시작하기

시작하기

이 가이드는 레거시 generateContent API 사용을 시작하도록 도와줘요. 새 프로젝트·애플리케이션에는 Gemini 모델·에이전트로 빌드하는 가장 간단하고 좋은 방법인 새 Interactions API를 강력히 권장해요.

참고: 코딩 에이전트를 쓰나요? API Development Skills를 설치해 에이전트가 최신 API 패턴을 유지하도록 도와주세요.

이 퀵스타트는 라이브러리 설치, 첫 요청, 응답 스트리밍, 멀티 턴 대화 구축, 표준 generateContent 메서드로 도구 사용하는 방법을 보여줘요.

출처: 원문

본문

API 키 받기

Gemini API를 사용하려면 요청 인증, 보안 한도 강제, 계정 사용량 추적을 위한 API 키가 필요해요.

  • Google AI Studio는 새 사용자에게 프로젝트와 API 키를 자동으로 만들어 줘요. API keys 페이지에서 복사할 수 있어요.
  • 새 키가 필요하면 AI Studio에서 Create API key를 클릭하고 대화상자에 따라 새 키-프로젝트 쌍을 추가하세요.

Create a Gemini API Key

키를 환경 변수로 설정하세요.

export GEMINI_API_KEY="YOUR_API_KEY"

유료 등급으로 업그레이드

유료 등급으로 업그레이드하면 속도 제한이 높아지고 Cloud Billing 설정이 필요해요.

  • AI Studio API keys 또는 Projects 페이지에서 Set up billing을 클릭하세요.
  • Cloud Billing 대화상자에 따라 결제 계정을 만들거나 연결하고, 결제 수단을 추가하고, 유료 크레딧으로 최소 $5(또는 통화 환산액)를 선불 충전하세요.
  • Google AI Studio의 Dashboard > Usage에서 API 사용량을 확인하세요.

자세한 내용은 Billing 페이지를 참고하세요.

Google GenAI SDK 설치

Python — Python 3.9+를 사용해 다음 pip 명령으로 google-genai 패키지를 설치하세요.

pip install -q -U google-genai

JavaScript — Node.js v18+를 사용해 다음 npm 명령으로 Google Gen AI SDK for TypeScript and JavaScript를 설치하세요.

npm install @google/genai

텍스트 생성

models.generate_content 메서드로 텍스트 응답을 생성해요.

from google import genai

client = genai.Client()

response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents="Explain how AI works in a few words"
)

print(response.text)
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});

async function main() {
  const response = await ai.models.generateContent({
    model: "gemini-3.8-flash",
    contents: "Explain how AI works in a few words",
  });

  console.log(response.text);
}

main();
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent" \
  -H "x-goog-api-key: YOUR_API_KEY" \
  -H 'Content-Type: application/json' \
  -X POST \
  -d '{
    "contents": [
      {
        "parts": [
          {
            "text": "Explain how AI works in a few words"
          }
        ]
      }
    ]
  }'

응답 스트리밍

기본적으로 모델은 전체 생성 과정이 완료된 후에만 응답을 반환해요. 더 빠르고 대화형인 경험을 위해, 생성될 때 응답 청크를 스트리밍할 수 있어요.

response = client.models.generate_content_stream(
    model="gemini-3.8-flash",
    contents="Explain how AI works in detail"
)

for chunk in response:
    print(chunk.text, end="", flush=True)
async function main() {
  const responseStream = await ai.models.generateContentStream({
    model: "gemini-3.8-flash",
    contents: "Explain how AI works in detail",
  });

  for await (const chunk of responseStream) {
    process.stdout.write(chunk.text);
  }
}

main();
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:streamGenerateContent" \
  -H "x-goog-api-key: YOUR_API_KEY" \
  -H 'Content-Type: application/json' \
  --no-buffer \
  -X POST \
  -d '{
    "contents": [
      {
        "parts": [
          {
            "text": "Explain how AI works in detail"
          }
        ]
      }
    ]
  }'

멀티 턴 대화

멀티 턴 대화를 위해 SDK는 대화 이력을 자동 관리하는 상태 저장 chats 헬퍼를 제공해 멀티 턴 채팅 경험을 구축해요.

chat = client.chats.create(model="gemini-3.8-flash")

response1 = chat.send_message("I have 2 dogs in my house.")
print("Response 1:", response1.text)

response2 = chat.send_message("How many paws are in my house?")
print("Response 2:", response2.text)
async function main() {
  const chat = ai.chats.create({ model: "gemini-3.8-flash" });

  let response = await chat.sendMessage({ message: "I have 2 dogs in my house." });
  console.log("Response 1:", response.text);

  response = await chat.sendMessage({ message: "How many paws are in my house?" });
  console.log("Response 2:", response.text);
}

main();
# REST is stateless. You must pass the full conversation history in the request.
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent" \
  -H "x-goog-api-key: YOUR_API_KEY" \
  -H 'Content-Type: application/json' \
  -X POST \
  -d '{
    "contents": [
      {
        "role": "user",
        "parts": [{"text": "I have 2 dogs in my house."}]
      },
      {
        "role": "model",
        "parts": [{"text": "That is nice! Two dogs mean you have plenty of company."}]
      },
      {
        "role": "user",
        "parts": [{"text": "How many paws are in my house?"}]
      }
    ]
  }'

도구 사용하기

Google Search로 응답을 접지해 실시간 웹 콘텐츠에 접근함으로써 모델의 능력을 확장해요. 모델이 언제 검색할지 자동 결정하고, 쿼리를 실행하고, 응답을 종합해요.

from google import genai
from google.genai import types

config = types.GenerateContentConfig(
    tools=[types.Tool(google_search=types.GoogleSearch())]
)

response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents="Who won the euro 2024?",
    config=config
)

print(response.text)

metadata = response.candidates[0].grounding_metadata
if metadata.web_search_queries:
    print("\nSearch queries executed:")
    for query in metadata.web_search_queries:
        print(f" - {query}")

if metadata.grounding_chunks:
    print("\nSources:")
    for chunk in metadata.grounding_chunks:
        print(f" - [{chunk.web.title}]({chunk.web.uri})")
async function main() {
  const response = await ai.models.generateContent({
    model: "gemini-3.8-flash",
    contents: "Who won the euro 2024?",
    config: {
      tools: [{ googleSearch: {} }]
    }
  });

  console.log(response.text);

  const metadata = response.candidates[0]?.groundingMetadata;
  if (metadata?.webSearchQueries) {
    console.log("\nSearch queries executed:");
    for (const query of metadata.webSearchQueries) {
      console.log(` - ${query}`);
    }
  }
  if (metadata?.groundingChunks) {
    console.log("\nSources:");
    for (const chunk of metadata.groundingChunks) {
      console.log(` - [${chunk.web.title}](${chunk.web.uri})`);
    }
  }
}

main();
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent" \
  -H "x-goog-api-key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -X POST \
  -d '{
    "contents": [
      {
        "parts": [
          {"text": "Who won the euro 2024?"}
        ]
      }
    ],
    "tools": [
      {
        "google_search": {}
      }
    ]
  }'

Gemini API는 다른 내장 도구도 지원해요.

  • 코드 실행: 모델이 복잡한 수학 문제를 풀기 위해 Python 코드를 작성·실행하게 해 줘요.
  • URL context: 제공한 특정 웹 페이지 URL에 응답을 근거 지을 수 있게 해 줘요.
  • 파일 검색: 파일을 업로드하고 시맨틱 검색으로 그 콘텐츠에 응답을 근거 지을 수 있게 해 줘요.
  • Google Maps: 위치 데이터에 응답을 근거 지고, 장소·길찾기·지도를 검색할 수 있게 해 줘요.
  • 컴퓨터 사용: 모델이 가상 컴퓨터 화면·키보드·마우스와 상호작용해 작업을 수행하게 해 줘요.

커스텀 함수 호출

함수 호출로 모델을 커스텀 도구·API에 연결해요. 모델이 함수를 언제 호출할지 결정하고 애플리케이션이 실행할 functionCall을 응답에 반환해요.

이 예제는 mock 온도 함수를 선언하고 모델이 이를 호출하려는지 확인해요.

from google import genai
from google.genai import types

weather_function = {
    "name": "get_current_temperature",
    "description": "Gets the current temperature for a given location.",
    "parameters": {
        "type": "object",
        "properties": {
            "location": {
                "type": "string",
                "description": "The city name, e.g. San Francisco",
            },
        },
        "required": ["location"],
    },
}

tools = types.Tool(function_declarations=[weather_function])
config = types.GenerateContentConfig(tools=[tools])

contents = ["What's the temperature in London?"]

response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents=contents,
    config=config,
)

part = response.candidates[0].content.parts[0]
if part.function_call:
    fc = part.function_call
    print(f"Model requested function: {fc.name} with args {fc.args}")

    mock_result = {"temperature": "15C", "condition": "Cloudy"}

    contents.append(response.candidates[0].content)

    fn_response_part = types.Part.from_function_response(
        name=fc.name,
        response=mock_result,
        id=fc.id
    )
    contents.append(types.Content(role="user", parts=[fn_response_part]))

    final_response = client.models.generate_content(
        model="gemini-3.8-flash",
        contents=contents,
        config=config,
    )
    print("Final Response:", final_response.text)
import { GoogleGenAI, Type } from '@google/genai';

async function main() {
  const weatherFunction = {
    name: 'get_current_temperature',
    description: 'Gets the current temperature for a given location.',
    parameters: {
      type: Type.OBJECT,
      properties: {
        location: {
          type: Type.STRING,
          description: 'The city name, e.g. San Francisco',
        },
      },
      required: ['location'],
    },
  };

  const contents = [{
    role: 'user',
    parts: [{ text: "What's the temperature in London?" }]
  }];

  const response = await ai.models.generateContent({
    model: 'gemini-3.8-flash',
    contents: contents,
    config: {
      tools: [{ functionDeclarations: [weatherFunction] }],
    },
  });

  if (response.functionCalls && response.functionCalls.length > 0) {
    const fc = response.functionCalls[0];
    console.log(`Model requested function: ${fc.name}`);

    const mockResult = { temperature: "15C", condition: "Cloudy" };

    contents.push(response.candidates[0].content);

    contents.push({
      role: 'user',
      parts: [{
        functionResponse: {
          name: fc.name,
          response: mockResult,
          id: fc.id
        }
      }]
    });

    const finalResponse = await ai.models.generateContent({
      model: 'gemini-3.8-flash',
      contents: contents,
      config: {
        tools: [{ functionDeclarations: [weatherFunction] }],
      },
    });
    console.log("Final Response:", finalResponse.text);
  }
}

main();
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent" \
  -H "x-goog-api-key: YOUR_API_KEY" \
  -H 'Content-Type: application/json' \
  -X POST \
  -d '{
    "contents": [
      {
        "role": "user",
        "parts": [{"text": "What'\''s the temperature in London?"}]
      }
    ],
    "tools": [
      {
        "functionDeclarations": [
          {
            "name": "get_current_temperature",
            "description": "Gets the current temperature for a given location.",
            "parameters": {
              "type": "object",
              "properties": {
                "location": {
                  "type": "string",
                  "description": "The city name, e.g. San Francisco"
                }
              },
              "required": ["location"]
            }
          }
        ]
      }
    ]
  }'

다음 단계

이제 Gemini API를 시작했으니, 더 고급 애플리케이션을 빌드하기 위해 다음 가이드를 살펴보세요.

더 알아보기 (Learn more)