[Google Study Jam X IT’s Study] Build Real World AI Applications with Gemini and Imagen (3)

2025. 9. 19. 17:48·Study/Google Skills

 

 

Build an application to send Chat Prompts using the Gemini model

프롬프트 응답 방식에는 스트리밍 응답과 일반(비스트리밍) 응답이 있다. 스트리밍 응답은 모델이 출력 토큰(몇 글자)를 생성할 때마다 실시간으로 바로 출력한다. 일반 응답은 모든 출력 토큰이 생성된 후에 출력한다.

 

 

Chat responses without using stream:

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)

 

 

연속적으로 채팅할 수 있도록 리팩토링해보았다.

Refactoring Ver.

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

import logging
from google.cloud import logging as gcp_logging

# 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?")],
        ),
    ],
)

print("프롬프트 대화 시작 ('q', 'quit' 입력 또는 Ctrl+C로 종료)")

try:
    while True:
        prompt = input("프롬프트를 작성하세요: ")
        if prompt.strip().lower() in ["q", "quit", "exit"]:
            print("종료합니다.")
            break
        response = chat.send_message(prompt)
        print(response.text)
except KeyboardInterrupt:
    print("\nCtrl+C로 종료합니다.")

 

 

 

Chat responses with using stream:

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

 

 

Refactoring Ver.

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

import logging
from google.cloud import logging as gcp_logging

# 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 = ""

print("프롬프트 대화 시작 ('q', 'quit', 'exit' 입력 또는 Ctrl+C로 종료)")

try:
    while True:
        prompt = input("\n프롬프트를 작성하세요: ")
        if prompt.strip().lower() in ["q", "quit", "exit"]:
            print("종료합니다.")
            break
        response_text = ""
        for chunk in chat.send_message_stream(prompt):
            print(chunk.text, end="", flush=True)
            response_text += chunk.text
        print()  # 줄 바꿈
except KeyboardInterrupt:
    print("\nCtrl+C로 종료합니다.")

 

 

Result

일반 응답

 

스트리밍 응답

 

 

잘못된 케데몬 줄거리를 알려준다.. RAG가 필요해 보인다.

 

 

Summary

일반 응답

  • chat.send_message()를 사용하여 프롬프트에 대해 AI의 전체 응답을 한 번에 받아 출력한다. 즉, 사용자가 프롬프트를 입력하면 전체 답변이 생성될 때까지 기다린 후 결과를 한꺼번에 표시한다.

스트리밍 응답

  • chat.send_message_stream()을 사용해 AI의 응답을 몇 글자(혹은 토큰)씩 "실시간"으로 받아와 바로 출력한다. 전체 문장이 완성되기 전이라도, 준비된 부분부터 끊김 없이 터미널에 표시된다. 긴 답변도 기다리지 않고, 즉시 결과 일부를 확인할 수 있다.
  • 실시간 대화형 AI, 라이브 채팅, 긴 텍스트 출력에 적합하다.

 

기능적 비교

  send_message() send_message_stream()
응답 방식 전체 답변 완료 후 한 번에 출력 부분 답변이 생성될 때마다 실시간 출력
응답 체감 속도 느림 (전체 대기 필요) 빠름 (즉시 부분 결과 확인)
코드 구조 결과값(str) 형태로 받아옴 반복문(for)으로 chunk별 출력
적합한 환경/용도 짧은 응답, 대기 시간 상관없는 환경 긴 답변, 빠른 피드백 필요한 환경

 

'Study > Google Skills' 카테고리의 다른 글

[Google Study Jam X IT’s Study] Build Real World AI Applications with Gemini and Imagen (4)  (0) 2025.09.19
[Google Study Jam X IT’s Study] Build Real World AI Applications with Gemini and Imagen (2)  (0) 2025.09.19
[Google Study Jam X IT’s Study] Build Real World AI Applications with Gemini and Imagen (1)  (0) 2025.09.19
[Google Study Jam X IT’s Study] Gemini in BigQuery (4)  (0) 2025.09.07
[Google Study Jam X IT’s Study] Gemini in BigQuery (1)  (0) 2025.09.07
'Study/Google Skills' 카테고리의 다른 글
  • [Google Study Jam X IT’s Study] Build Real World AI Applications with Gemini and Imagen (4)
  • [Google Study Jam X IT’s Study] Build Real World AI Applications with Gemini and Imagen (2)
  • [Google Study Jam X IT’s Study] Build Real World AI Applications with Gemini and Imagen (1)
  • [Google Study Jam X IT’s Study] Gemini in BigQuery (4)
Z0e
Z0e
3D Vision Engineer, Zoe 입니다.
  • Z0e
    I'm not a robot
    Z0e
    • 분류 전체보기
      • Spatial AI
        • Geometry
        • SLAM
      • Programming
        • Python
        • Git
        • Docker
      • Setting
        • Ubuntu
        • ROS
      • Study
        • Google Skills
  • 인기 글

  • hELLO· Designed By정상우.v4.10.3
Z0e
[Google Study Jam X IT’s Study] Build Real World AI Applications with Gemini and Imagen (3)
상단으로

티스토리툴바