AI

Gemini API 이용하기

ardoh 2025. 5. 3. 15:51

https://gdg.community.dev/events/details/google-gdg-on-campus-kookmin-university-seoul-south-korea-presents-build-with-aipre-solution-challenge/

 

Build with AI(Pre-Solution Challenge) | Google Developer Groups

In-person Event - Build with AI: Gemini로 시작하는 AI 입문 세션 AI가 처음인 Solution Challenge 참가자&참가 희망자들을 위한 기초 세션입니다. Google의 최신 AI 모델인 Gemini를 활용해 AI의 기본 개념과 실습을

gdg.community.dev

 

 

!pip install google-genai # Python에서 간편하게 사용할 수 있도록 도와주는 공식 라이브러리

from google import genai
from google.genai import types

client = genai.Client(api_key='Google AI Studio 에서 발급받은 API key')

MODEL_ID = "gemini-2.5-flash-preview-04-17" # @param ["gemini-2.0-flash-lite","gemini-2.0-flash","gemini-2.5-flash-preview-04-17","gemini-2.5-pro-exp-03-25"] {"allow-input":true, isTemplate: true}

 

 

API 호출

from IPython.display import Markdown

response = client.models.generate_content(
    model=MODEL_ID,
    contents="미국에서 20대에게 가장 인기 있는 sns 1등부터 5등까지 순서대로, 마크다운과 이모티콘을 통해서 가독성 좋게 만들어주세요"
)

Markdown(response.text)

 

채팅

#이전 질문 기억할 수 있도록

from google import genai
from google.genai import types

# 채팅 세션 생성
chat = client.chats.create(model=MODEL_ID)

print("Gemini 챗봇에 오신 것을 환영합니다! 종료하려면 'exit'를 입력하세요.")

while True:
    user_input = input("사용자: ")
    if user_input.lower() in ['exit', 'quit','종료']:
        print("챗봇을 종료합니다.")
        break
    response = chat.send_message(user_input)
    print(f"Gemini: {response.text}\n")

 

이미지 기반

from google import genai
from google.genai import types
from IPython.display import display, Image, Markdown

import requests #링크를 통해서 이미지를 다운로드 하기위해서 사용됨.(get 요청)

image_path = "이미지 경로"

image_bytes = requests.get(image_path).content
image = types.Part.from_bytes(
  data=image_bytes, mime_type="image/jpeg"
)

response = client.models.generate_content(
    model=MODEL_ID,
    contents=["Write a short and engaging blog post based on this picture(say to korean), 마크다운형식으로 이모티콘을 이용하여 이쁘게 정리해주세요", image],
)

display(Image(data=image_bytes))
Markdown(response.text)

 

유튜브 동영상 기반

response = client.models.generate_content(
    model=MODEL_ID,
    contents=types.Content(
        parts=[
            types.Part(text="내용을 요약하고 핵심을 알려주세요. markdown형식으로 이모티몬을 사용해서 출력을 이쁘게 만들어주세요"),
            types.Part(
                file_data=types.FileData(file_uri='유튜브 주소')
            )
        ]
    )
)

Markdown(response.text)

 

Grounding(외부데이터 바탕)을 통해서 구글 검색을 활용하기

from IPython.display import HTML, Markdown

response = client.models.generate_content(
    model=MODEL_ID,
    contents='양귀자 작가의 책 모순의 줄거리 말해줘',
    config={"tools": [{"google_search": {}}]},
)


# print the response
display(Markdown(response.text))
# print the search details
print(f"Search Query: {response.candidates[0].grounding_metadata.web_search_queries}")
# urls used for grounding
print(f"Search Pages: {', '.join([site.web.title for site in response.candidates[0].grounding_metadata.grounding_chunks])}")

display(HTML(response.candidates[0].grounding_metadata.search_entry_point.rendered_content)) # 구글 검색으로 바로 넘어갈 수 있는 ui 생성