Gemini API 빠른 시작

이 빠른 시작에서는 라이브러리를 설치하고 첫 번째 요청을 만들고, 응답을 스트리밍하고, 멀티턴 대화를 빌드하고, 도구를 사용하는 방법을 보여줍니다.

Gemini API에 요청을 보내는 방법에는 두 가지가 있습니다.

  • (권장) Interactions API는 유형이 지정된 실행 단계를 통해 다단계 도구 사용, 오케스트레이션, 복잡한 추론 흐름을 기본적으로 지원하는 새로운 기본 요소입니다. 앞으로 핵심 Mainline 제품군을 넘어선 새로운 모델과 새로운 에이전트 기능 및 도구는 Interactions API에서만 출시됩니다.
  • generateContent은 모델에서 상태 비저장 응답을 생성하는 방법을 제공합니다. Interactions API를 사용하는 것이 좋지만 generateContent도 완전히 지원됩니다.

이 버전의 빠른 시작에서는 Interactions API를 사용하여 Gemini API에 요청을 보냅니다.

시작하기 전에

Gemini API를 사용하려면 요청을 인증하고, 보안 한도를 적용하고, 계정의 사용량을 추적하는 API 키가 있어야 합니다.

AI Studio에서 무료로 만들어 시작하세요.

Gemini API 키 만들기

Google 생성형 AI SDK 설치

Python

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

pip install -q -U google-genai

자바스크립트

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

npm install @google/genai

텍스트 생성

interactions.create 메서드를 사용하여 텍스트 응답을 생성합니다.

Python

from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3.5-flash",
    input="Explain how AI works in a few words"
)

print(interaction.output_text)

자바스크립트

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});

async function main() {
  const interaction = await ai.interactions.create({
    model: "gemini-3.5-flash",
    input: "Explain how AI works in a few words",
  });

  console.log(interaction.output_text);
}

main();

REST

curl -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -H "Api-Revision: 2026-05-20" \
  -d '{
    "model": "gemini-3.5-flash",
    "input": "Explain how AI works in a few words"
  }'

대답 스트리밍

기본적으로 모델은 전체 생성 프로세스가 완료된 후에만 대답을 반환합니다. 더 빠르고 대화형 환경을 위해 대답 청크가 생성될 때 스트리밍할 수 있습니다.

Python

stream = client.interactions.create(
    model="gemini-3.5-flash",
    input="Explain how AI works in detail",
    stream=True
)

for event in stream:
    if event.event_type == "step.delta":
        if event.delta.type == "text":
            print(event.delta.text, end="", flush=True)

자바스크립트

async function main() {
  const stream = await ai.interactions.create({
    model: "gemini-3.5-flash",
    input: "Explain how AI works in detail",
    stream: true,
  });

  for await (const event of stream) {
    if (event.event_type === "step.delta") {
      if (event.delta.type === "text") {
        process.stdout.write(event.delta.text);
      }
    }
  }
}

main();

REST

# Use alt=sse for streaming
curl -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions?alt=sse" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -H "Api-Revision: 2026-05-20" \
  --no-buffer \
  -d '{
    "model": "gemini-3.5-flash",
    "input": "Explain how AI works in detail",
    "stream": true
  }'

멀티턴 대화

Gemini API는 멀티턴 대화를 빌드하기 위한 지원 기능이 기본으로 제공됩니다. 이전 상호작용에서 반환된 idprevious_interaction_id 매개변수로 전달하기만 하면 서버에서 자동으로 대화 기록을 관리합니다.

Python


interaction1 = client.interactions.create(
    model="gemini-3.5-flash",
    input="I have 2 dogs in my house."
)
print("Response 1:", interaction1.output_text)

interaction2 = client.interactions.create(
    model="gemini-3.5-flash",
    input="How many paws are in my house?",
    previous_interaction_id=interaction1.id
)
print("Response 2:", interaction2.output_text)

자바스크립트

async function main() {
  const interaction1 = await ai.interactions.create({
    model: "gemini-3-flash-preview",
    input: "I have 2 dogs in my house.",
  });
  console.log("Response 1:", interaction1.output_text);

  const interaction2 = await ai.interactions.create({
    model: "gemini-3-flash-preview",
    input: "How many paws are in my house?",
    previous_interaction_id: interaction1.id,
  });
  console.log("Response 2:", interaction2.output_text);
}

main();

REST

# Turn 1: Start the conversation
RESPONSE1=$(curl -s -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "Api-Revision: 2026-05-20" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gemini-3-flash-preview",
    "input": "I have 2 dogs in my house."
  }')

# Extract the interaction ID
INTERACTION_ID=$(echo "$RESPONSE1" | jq -r '.id')

# Turn 2: Continue the conversation
curl -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "Api-Revision: 2026-05-20" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d "{
    \"model\": \"gemini-3-flash-preview\",
    \"input\": \"How many paws are in my house?\",
    \"previous_interaction_id\": \"$INTERACTION_ID\"
  }"

도구 사용하기

Google 검색으로 대답을 그라운딩하여 실시간 웹 콘텐츠에 액세스함으로써 모델의 기능을 확장하세요. 모델은 검색 시점을 자동으로 결정하고, 쿼리를 실행하고, 인용과 함께 대답을 합성합니다.

다음 예에서는 Google 검색을 사용 설정하는 방법을 보여줍니다.

Python

interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    input="Who won the euro 2024?",
    tools=[{"type": "google_search"}]
)

print(interaction.output_text)

for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text" and content_block.annotations:
                print("\nCitations:")
                for annotation in content_block.annotations:
                    if annotation.type == "url_citation":
                        print(f"  - [{annotation.title}]({annotation.url})")

자바스크립트

async function main() {
  const interaction = await ai.interactions.create({
    model: "gemini-3-flash-preview",
    input: "Who won the euro 2024?",
    tools: [{ type: "google_search" }]
  });

  console.log(interaction.output_text);

  for (const step of interaction.steps) {
    if (step.type === 'model_output') {
      for (const contentBlock of step.content) {
        if (contentBlock.type === 'text' && contentBlock.annotations) {
          console.log("\nCitations:");
          for (const annotation of contentBlock.annotations) {
            if (annotation.type === 'url_citation') {
              console.log(`  - [${annotation.title}](${annotation.url})`);
            }
          }
        }
      }
    }
  }
}

main();

REST

curl -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "Api-Revision: 2026-05-20" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-3-flash-preview",
    "input": "Who won the euro 2024?",
    "tools": [{"type": "google_search"}]
  }'

Gemini API는 다음과 같은 다른 기본 제공 도구도 지원합니다.

  • 코드 실행: 모델이 Python 코드를 작성하고 실행하여 복잡한 수학 문제를 해결할 수 있습니다.
  • URL 컨텍스트: 사용자가 제공한 특정 웹페이지 URL을 기반으로 대답을 생성할 수 있습니다.
  • 파일 검색: 파일을 업로드하고 시맨틱 검색을 사용하여 콘텐츠에서 대답을 그라운딩할 수 있습니다.
  • Google 지도: 위치 데이터에 기반한 대답을 제공하고 장소, 길찾기, 지도를 검색할 수 있습니다.
  • 컴퓨터 사용: 모델이 가상 컴퓨터 화면, 키보드, 마우스와 상호작용하여 작업을 실행할 수 있습니다.

맞춤 함수 호출

함수 호출을 사용하여 모델을 맞춤 도구 및 API에 연결합니다. 모델은 함수를 호출할 시기를 결정하고 애플리케이션이 실행할 인수가 포함된 function_call 단계를 반환합니다.

이 예시에서는 모의 온도 함수를 선언하고 모델이 이 함수를 호출하려고 하는지 확인합니다.

Python

import json

weather_function = {
    "type": "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"],
    },
}

interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    input="What's the temperature in London?",
    tools=[weather_function],
)

fc_step = None
for step in interaction.steps:
    if step.type == "function_call":
        fc_step = step
        break

if fc_step:
    print(f"Model requested function: {fc_step.name} with args {fc_step.arguments}")

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

    final_interaction = client.interactions.create(
        model="gemini-3-flash-preview",
        input=[
            {
                "type": "function_result",
                "name": fc_step.name,
                "call_id": fc_step.id,
                "result": [{"type": "text", "text": json.dumps(mock_result)}],
            }
        ],
        tools=[weather_function],
        previous_interaction_id=interaction.id,
    )
    print("Final Response:", final_interaction.output_text)

자바스크립트

async function main() {
  const weatherFunction = {
    type: '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'],
    },
  };

  const interaction = await ai.interactions.create({
    model: 'gemini-3-flash-preview',
    input: "What's the temperature in London?",
    tools: [weatherFunction],
  });

  const fcStep = interaction.steps.find(s => s.type === 'function_call');
  if (fcStep) {
    console.log(`Model requested function: ${fcStep.name}`);

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

    const finalInteraction = await ai.interactions.create({
      model: 'gemini-3-flash-preview',
      input: [{
        type: 'function_result',
        name: fcStep.name,
        call_id: fcStep.id,
        result: [{ type: 'text', text: JSON.stringify(mockResult) }]
      }],
      tools: [weatherFunction],
      previous_interaction_id: interaction.id,
    });

    console.log("Final Response:", finalInteraction.output_text);
  }
}

main();

REST

curl -X POST \
  "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "Api-Revision: 2026-05-20" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-3-flash-preview",
    "input": "What'\''s the temperature in London?",
    "tools": [{
      "type": "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"}
        },
        "required": ["location"]
      }
    }]
  }'

다음 단계

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