무료 Gemini API 키를 사용해 챗봇 만드는 팁

발행: (2026년 2월 28일 오전 08:50 GMT+9)
4 분 소요
원문: Dev.to

Source: Dev.to

Overview

Gemini API는 Google의 가장 강력한 AI 모델에 비용 효율적인 접근을 제공합니다. 이 가이드는 챗봇을 구축하기 위한 아키텍처와 구현 단계를 설명하며, API 키를 안전하게 보호하는 방법을 다룹니다.

Architecture

ComponentDescription
Client사용자가 React/HTML 인터페이스에 프롬프트를 입력합니다.
Server (Backend)Django 또는 Node.js 환경이 프롬프트를 받아 비밀 API 키를 첨부하고 Gemini API에 요청을 전달합니다.
Gemini APIGoogle이 자연어 요청을 처리하고 JSON 응답을 반환합니다.
Display백엔드가 응답 텍스트를 프론트엔드로 보내어 채팅 버블에 표시합니다.

Setup

  1. Google AI Studio에서 API 키를 획득합니다.

  2. Python 환경을 만들고 필요한 라이브러리를 설치합니다:

    pip install -q -U google-generativeai
  3. API 키를 .env 파일에 저장하고, 실수로 노출되지 않도록 해당 파일을 **.gitignore**에 추가합니다.

Initializing the Model

# service.py or views.py
import google.generativeai as genai
import os

# Securely load your API key
genai.configure(api_key=os.environ["GEMINI_API_KEY"])

# Initialize the model (Gemini 2.5 Flash is recommended for speed)
model = genai.GenerativeModel('gemini-2.5-flash')

Creating a Chat Session

표준 프롬프트‑응답 흐름은 stateless합니다. 대화 기록을 유지하려면 .start_chat() 메서드를 사용합니다.

# Start a chat session with an empty history
chat = model.start_chat(history=[])

def get_chatbot_response(user_input: str) -> str:
    """Send a message to the model and return the text response."""
    response = chat.send_message(user_input, stream=False)
    return response.text

Safety Settings

Gemini에는 괴롭힘 및 위험한 콘텐츠에 대한 내장 필터가 포함되어 있습니다. 모델이 과도하게 제한적일 경우 구성에서 해당 설정을 조정할 수 있습니다.

System Instructions (Persona)

챗봇에 일관된 페르소나를 부여하려면 시스템 지시문을 정의합니다:

system_prompt = (
    "You are a professional first‑aid assistant. "
    "Provide clear, step‑by‑step emergency instructions."
)

# Example of initializing with a system instruction
model = genai.GenerativeModel(
    'gemini-2.5-flash',
    system_instruction=system_prompt
)

Error Handling

API 호출을 try‑except 블록으로 감싸서 요청 제한, 할당량 오류, 네트워크 타임아웃 등을 처리합니다.

def safe_get_response(user_input: str) -> str:
    try:
        return get_chatbot_response(user_input)
    except Exception as e:
        # Log the error and return a friendly message
        print(f"Error: {e}")
        return "Sorry, I'm experiencing technical difficulties. Please try again later."

Security Best Practices

  • 프론트엔드(JavaScript)에서 Gemini API를 직접 호출하지 마세요. 브라우저에 API 키가 노출되면 누구든지 키를 탈취하고 할당량을 소모할 수 있습니다.
  • 항상 백엔드를 통해 요청을 라우팅하고, API 키는 환경 변수에 안전하게 보관합니다.
  • .env 파일을 버전 관리에서 제외(.gitignore)하십시오.

이 가이드를 따라 하면 무료 Gemini API 키를 사용해 기능적이고 안전한 챗봇을 구축할 수 있습니다.

0 조회
Back to Blog

관련 글

더 보기 »