Study Programming/Google AI기초공부(with CloudSkillBoost)

[Imagen 3/4] Build an application to send Chat Prompts using the Gemini model (Gemini 모델을 사용하여 채팅 프롬프트를 보내는 애플리케이션을 구축)

네모메모 2025. 9. 19. 15:58
반응형
 

 

Build an application to send Chat Prompts using the Gemini model 

(Gemini 모델을 사용하여 채팅 프롬프트를 보내는 애플리케이션을 구축)

 

 

 


목적

Vertex AI의 생성 AI(genAI 또는 gen AI라고도 함)를 사용하면 Google의 대규모 생성 AI 모델을 활용하여 AI 기반 애플리케이션에 사용하기 위해 테스트, 조정 및 배포할 수 있습니다. 이 랩에서는 다음을 수행합니다.

  • Vertex AI(Google Cloud AI 플랫폼)에 연결: Vertex AI SDK를 사용하여 Google AI 서비스에 연결하는 방법을 알아보세요.
  • 사전 훈련된 생성 AI 모델 로드 - 제미니: 처음부터 모델을 구축하지 않고도 강력하고 사전 훈련된 AI 모델을 사용하는 방법을 알아보세요.
  • AI 모델에 텍스트 보내기: AI가 처리할 수 있도록 입력을 제공하는 방법을 알아보세요.
  • AI에서 채팅 응답 추출: AI 모델에서 생성된 채팅 응답을 처리하고 해석하는 방법을 알아보세요.
  • AI 애플리케이션 구축의 기본 사항을 이해합니다. 소프트웨어 프로젝트에 AI를 통합하는 핵심 개념에 대한 통찰력을 얻습니다.

 


 

Working with Vertex AI Python SDK

- 이번 과정도  이전과정처럼 랩을 시작하면 왼쪽에는 코드 편집기가, 오른쪽에는 랩 지침이 분할 창으로 표시됩니다.

+) projectId와 location도 이전과정과 같이 버튼 클릭 시 다시 보여집니다

 

 


1. Synchronous Send Message

과정1-1.  Synchronous Non-Streaming (스트림을 사용하지 않고 채팅 응답)

: 스트리밍은 프롬프트가 생성되는 즉시 응답을 수신하는 방식
  - 즉, 모델이 출력 토큰을 생성하는 즉시 출력 토큰이 전송됩니다. 
  - 프롬프트에 대한 비스트리밍 응답은 모든 출력 토큰이 생성된 후에만 전송됩니다.

1. 파일 > 새 파일 클릭
2. 제공된 코드 조각을 복붙
3. `SendChatwithoutStream.py`이름으로 파일 > 저장

from google import genai
from google.genai.types import HttpOptions, ModelContent, Part, UserContent

import logging
from google.cloud import logging as gcp_logging

# ------  Below cloud logging code is for Qwiklab's internal use, do not edit/remove it. --------
# Initialize GCP logging
gcp_logging_client = gcp_logging.Client()
gcp_logging_client.setup_logging()

client = genai.Client(
    vertexai=True,
    project='"project-id"',
    location='"REGION"',
    http_options=HttpOptions(api_version="v1")
)
chat = client.chats.create(
    model="gemini-2.0-flash-001",
    history=[
        UserContent(parts=[Part(text="Hello")]),
        ModelContent(
            parts=[Part(text="Great to meet you. What would you like to know?")],
        ),
    ],
)
response = chat.send_message("What are all the colors in a rainbow?")
print(response.text)

response = chat.send_message("Why does it appear when it rains?")
print(response.text)

 

ㄴ> [ send_message 메소드의 파라미터 ]

send_message(
    content: content_types.ContentType,
    *,
    generation_config: generation_types.GenerationConfigType = None,
    safety_settings: safety_types.SafetySettingOptions = None,
    stream: bool = False,
    tools: (content_types.FunctionLibraryType | None) = None,
    tool_config: (content_types.ToolConfigType | None) = None,
    request_options: (helper_types.RequestOptionsType | None) = None
) -> generation_types.GenerateContentResponse

 


    
4. 터미널의 코드 편집기 창에서 아래 명령을 실행하여 Python 파일을 실행하면 출력을 볼 수 있습니다.

/usr/bin/python3 /SendChatwithoutStream.py

 


과정1-2.  Synchronous Streaming (스트림을 사용하여 채팅 응답)

1. 파일 > 새 파일을 클릭
2. 제공된 코드 조각을 복붙

from google import genai
from google.genai.types import HttpOptions

import logging
from google.cloud import logging as gcp_logging

# ------  Below cloud logging code is for Qwiklab's internal use, do not edit/remove it. --------
# Initialize GCP logging
gcp_logging_client = gcp_logging.Client()
gcp_logging_client.setup_logging()

client = genai.Client(
    vertexai=True,
    project='"project-id"',
    location='"REGION"',
    http_options=HttpOptions(api_version="v1")
)
chat = client.chats.create(model="gemini-2.0-flash-001")
response_text = ""

for chunk in chat.send_message_stream("What are all the colors in a rainbow?"):
    print(chunk.text, end="")
    response_text += chunk.text


ㄴ> send_message_stream() 메소드

 


3.  `SendChatwithStream.py`이름 으로 파일 > 저장


4. 터미널의 코드 편집기 창에서 아래 명령을 실행하여 Python 파일을 실행하면 출력을 볼 수 있습니다.

/usr/bin/python3 /SendChatwithStream.py

 

 

 

 


예제는 아니지만 추가해보는 비교용으로 추가해 본 비동기 과정

 

2. Asynchronous Send Message

  - client.aio.chats.create() 메소드 + asyncio의 async/await 구문 사용
  - asyncio는 async/await 구문이란?
     ㄴ> 동시성 코드를 작성할 수 있게 해주는 모듈로, asyncio를 사용하면 단일 스레드 작업을 병렬로 처리할 수 있다.

 

과정2-1.  Asynchronous Non-Streaming  (스트림을 사용하지 않고 채팅 응답)

chat = client.aio.chats.create(model='gemini-2.0-flash-001')

response = await chat.send_message('tell me a story')print(response.text)

 

과정2-2.  Asynchronous Streaming  (스트림을 사용하여 채팅 응답)

chat = client.aio.chats.create(model='gemini-2.0-flash-001')
async for chunk in await chat.send_message_stream('tell me a story'):
    print(chunk.text, end='') # end='' is optional, for demo purposes.

 

 

 

 

 


출처

https://googleapis.github.io/python-genai/#generate-image

 

Google Gen AI SDK documentation

Next Submodules

googleapis.github.io

 

 

https://www.cloudskillsboost.google/course_templates/1076/labs/584320

 

Introduction to Building Real-World AI Applications with Gemini and Imagen - Gemini 모델을 사용하여 채팅 프롬프트

이 실습에서는 Google의 Vertex AI SDK를 사용하여 강력한 Gemini 생성형 AI 모델과 상호작용하는 방법을 알아봅니다. 이를 통해 텍스트 기반 채팅 프롬프트를 입력으로 보내고 맞춤형 스트리밍 및 비스

www.cloudskillsboost.google

 

반응형