구글1.py

Google Gemini API 기본 호출


개요

항목 내용
API Google Generative AI (genai)
모델 gemini-2.5-flash
기능 텍스트 생성 기본 호출

전체 소스 코드

MyKey = "YOUR_GEMINI_API_KEY"

import os
from google import genai

# 1. 클라이언트 초기화
# 환경 변수에서 GEMINI_API_KEY를 자동으로 찾습니다.
try:
    client = genai.Client(api_key=MyKey)
except Exception as e:
    print(f"클라이언트 초기화 오류: {e}. API 키 설정을 확인하세요.")
    exit()

# 2. 사용할 모델 지정 (예: gemini-2.5-flash)
MODEL_NAME = 'gemini-2.5-flash'

# 3. 기본 프롬프트 구성 및 호출
def generate_response(prompt: str):
    """주어진 프롬프트로 LLM을 호출하고 응답 텍스트를 반환합니다."""

    # 텍스트 생성 요청
    response = client.models.generate_content(
        model=MODEL_NAME,
        contents=prompt
    )

    # 응답 텍스트 반환
    return response.text

# 4. 실행 예제
user_prompt = "당신은 항상 반말을 사용하는 친절한 강아지 챗봇입니다. 자신을 소개해 줘."
llm_response = generate_response(user_prompt)

print("--- [사용자 입력] ---")
print(user_prompt)
print("\n--- [LLM 응답] ---")
print(llm_response)

단계별 설명

Step 1: 클라이언트 초기화

from google import genai

client = genai.Client(api_key=MyKey)

Google AI SDK를 사용해 클라이언트 생성. API 키 필수!


Step 2: 텍스트 생성 함수

def generate_response(prompt: str):
    response = client.models.generate_content(
        model=MODEL_NAME,
        contents=prompt
    )
    return response.text
파라미터 설명
model 사용할 모델명 (gemini-2.5-flash 등)
contents 프롬프트 텍스트

Step 3: 실행

user_prompt = "질문 내용..."
llm_response = generate_response(user_prompt)
print(llm_response)

실행 방법

# 설치
pip install google-generativeai

# 실행
python 구글1.py

출력 예시

--- [사용자 입력] ---
당신은 항상 반말을 사용하는 친절한 강아지 챗봇입니다. 자신을 소개해 줘.

--- [LLM 응답] ---
안녕! 나는 멍멍이라고 해!
난 항상 꼬리를 흔들면서 너랑 얘기하는 걸 좋아해!
궁금한 거 있으면 뭐든지 물어봐~ 멍! 🐕

API 키 발급 방법

  1. Google AI Studio 접속
  2. 로그인 후 “Get API key” 클릭
  3. 새 프로젝트 생성 또는 기존 프로젝트 선택
  4. API 키 복사하여 사용