티스토리 뷰

Deep Learning

gemini api 사용법

developer0hye 2025. 8. 2. 10:21

 

 

키 발급 필요

https://aistudio.google.com/apikey

 

로그인 - Google 계정

이메일 또는 휴대전화

accounts.google.com

 

  • 키 발급 후 API 키 별도 저장하여 관리 필요, 아래 예제 에서는 api.txt에 해당 API 키가 작성돼있음을 가정
  • 테스트 코드 1. 호출 가능한 모델 출력
from google import genai
import os

# read api.txt
with open("api.txt", "r") as file:
    gemini_api_key = file.read().strip()

os.environ["GEMINI_API_KEY"] = gemini_api_key

# The client gets the API key from the environment variable `GEMINI_API_KEY`.
client = genai.Client()


print("List of models that support generateContent:\n")
for m in client.models.list():
    for action in m.supported_actions:
        if action == "generateContent":
            print(m.name)

print("List of models that support embedContent:\n")
for m in client.models.list():
    for action in m.supported_actions:
        if action == "embedContent":
            print(m.name)

 

나는 무료 유저면 pro아예 못쓸 줄 알았는데 쓸수가 있었다. 물론 사용량은 제한됨.

 

  • 테스트 코드 2. 텍스트 데이터 처리 예제
rom google import genai
import os

# read api.txt
with open("api.txt", "r") as file:
    gemini_api_key = file.read().strip()

os.environ["GEMINI_API_KEY"] = gemini_api_key

# 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)

 

  • 테스트 코드 3. 이미지 데이터 처리 예제, 돌리려면 test.jpg, prompt.txt 필요
from google import genai
from google.genai import types
import os

# read api.txt
with open("api.txt", "r") as file:
    gemini_api_key = file.read().strip()

os.environ["GEMINI_API_KEY"] = gemini_api_key

# read prompt.txt
with open("prompt.txt", "r") as file:
    prompt = file.read().strip()

print(prompt)

# The client gets the API key from the environment variable `GEMINI_API_KEY`.
client = genai.Client()

with open('test.jpg', 'rb') as f:
      image_bytes = f.read()

response = client.models.generate_content(
model='gemini-2.5-flash',
contents=[
    types.Part.from_bytes(
    data=image_bytes,
    mime_type='image/jpeg',
    ),
    prompt
]
)

print(response.text)
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/12   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함