1. 개요
이 실습에서는 Google의 생성형 AI 제품을 사용하여 Gemini Cloud Assist의 도움을 받아 Google Cloud에 인프라를 구축하고, 자연어를 사용하여 BigQuery 데이터를 Data Canvas의 SQL 기능에 쿼리하고, Gemini Code Assist의 도움을 받아 Colab Enterprise Jupyter 노트북과 Eclipse Theia (Visual Studio Code)에서 코드를 작성하고, Cloud Storage 및 BigQuery 기반 소스에 구축된 AI 검색 및 채팅 기능을 Vertex AI Agent Builder에 통합합니다.
AI Recipe Haven이라는 레시피 및 요리 웹사이트를 만드는 것이 목표입니다. 이 사이트는 Python 및 Streamlit로 빌드되며 두 가지 주요 페이지가 포함됩니다. Cooking Advice는 Gemini와 레시피북 그룹에 연결된 Vertex AI Agent Builder 기반 소스를 사용하여 만들 챗봇을 호스팅하고, 요리 관련 조언을 제공하고 요리 관련 질문에 답변합니다. Recipe Search는 Gemini에서 제공하는 검색엔진으로, 이번에는 BigQuery 레시피 데이터베이스를 기반으로 합니다.
이 연습의 코드 중에서 막히는 부분이 있으면 모든 코드 파일의 솔루션이 연습 GitHub 저장소의 solution 브랜치에 있습니다.
목표
이 실습에서는 다음 작업을 수행하는 방법을 알아봅니다.
- Gemini Cloud Assist 활성화 및 사용
- Vertex AI Agent Builder에서 요리 조언 챗봇을 위한 검색 앱 만들기
- Gemini Code Assist를 사용하여 Colab Enterprise 노트북에 데이터를 로드하고 정리
- Vertex AI Agent Builder에서 레시피 생성기를 위한 검색 앱 만들기
- Gemini의 도움을 받아 핵심 Python 및 Streamlit 웹 애플리케이션의 프레임 설정
- Cloud Run에 웹 애플리케이션 배포
- 레시피북 검색 Agent Builder 앱에 Cooking Advice 페이지 연결
- (선택사항) 레시피 검색 페이지를 레시피 검색 Agent Builder 앱에 연결
- (선택사항) 최종 애플리케이션 살펴보기
2. 설정 및 요건
실습 시작 버튼을 클릭하기 전에
다음 안내를 확인하세요. 실습에는 시간 제한이 있으며 일시중지할 수 없습니다. 실습 시작을 클릭하면 타이머가 시작됩니다. 이 타이머는 Google Cloud 리소스를 사용할 수 있는 시간이 얼마나 남았는지를 표시합니다.
Qwiklabs 실습을 통해 시뮬레이션이나 데모 환경이 아닌 실제 클라우드 환경에서 직접 실습 활동을 진행할 수 있습니다. 실습 시간 동안 Google Cloud에 로그인하고 액세스하는 데 사용할 수 있는 새로운 임시 사용자 인증 정보가 제공됩니다.
필요한 사항
이 실습을 완료하려면 다음이 필요합니다.
- 표준 인터넷 브라우저(Chrome 브라우저 권장)
- 실습을 끝까지 진행할 시간
참고: 이미 개인용 Google Cloud 계정이나 프로젝트가 있어도 이 실습에서는 사용하지 마세요.
참고: Pixelbook을 사용하는 경우 시크릿 창을 열어 이 실습을 실행하세요.
실습을 시작하고 Google Cloud 콘솔에 로그인하는 방법
- 실습 시작 버튼을 클릭합니다. 실습 비용을 결제해야 하는 경우 결제 수단을 선택할 수 있는 팝업이 열립니다. 왼쪽에 있는 패널에서 이 실습에 사용해야 하는 임시 사용자 인증 정보를 확인할 수 있습니다.
- 사용자 이름을 복사한 다음 Google 콘솔 열기를 클릭합니다. 실습에서 리소스가 가동된 후 로그인 페이지가 표시된 다른 탭이 열립니다.
팁: 두 탭은 각각 별도의 창에 나란히 여세요.
계정 선택 페이지가 표시되면 '다른 계정 사용'을 클릭합니다.
- 로그인 페이지에서 연결 세부정보 패널에서 복사한 사용자 이름을 붙여넣습니다. 그런 다음 비밀번호를 복사하여 붙여넣습니다.
중요: 연결 세부정보 패널에 표시된 사용자 인증 정보를 사용해야 합니다. 본인의 Qwiklabs 사용자 인증 정보를 사용하지 마세요. 개인용 Google Cloud 계정이 있어도 이 실습에서는 사용하지 마세요 (요금 청구 방지). 4. 이후에 표시되는 페이지를 클릭하여 넘깁니다.
- 이용약관에 동의합니다.
- 임시 계정이므로 복구 옵션이나 2단계 인증을 추가하지 않습니다.
- 무료 평가판을 신청하지 않습니다.
잠시 후 Cloud 콘솔이 이 탭에서 열립니다.
참고: 왼쪽 상단의 탐색 메뉴를 클릭하면 Google Cloud 제품 및 서비스 목록이 있는 메뉴를 볼 수 있습니다.
3. 작업 0. 워크스테이션 클러스터 확인
이 실습의 후반부에서는 Google Cloud 워크스테이션을 사용하여 개발 작업을 진행합니다. 이 실습의 시작 프로세스에서 워크스테이션의 클러스터 생성이 시작되었을 것입니다. 계속하기 전에 클러스터가 빌드되고 있는지 확인해 보겠습니다.
- Google Cloud 콘솔에서 검색창을 사용하여 Cloud Workstations로 이동합니다.
- 왼쪽 탐색 메뉴를 사용하여 클러스터 관리를 봅니다.
- 업데이트 중인 클러스터가 있으면 문제가 없으며 작업 1로 이동할 수 있습니다. 어떤 상태의 클러스터도 표시되지 않으면 페이지를 새로고침합니다. 그래도 클러스터 업데이트 (빌드)가 표시되지 않으면 이 안내의 왼쪽 상단에 있는 버튼을 사용하여 이 실습을 종료하고 실습을 다시 시작합니다.
4. 작업 1. Gemini Cloud Assist 활성화 및 사용
이 작업에서는 Gemini Cloud Assist를 활성화하고 사용해 봅니다. Gemini Cloud Assist는 Google Cloud 콘솔에서 작업하는 동안 조언을 제공하고, Google Cloud 인프라를 빌드, 구성, 모니터링하는 데 도움을 주며, gcloud
명령어를 제안하고 Terraform 스크립트를 작성할 수도 있습니다.
- Cloud Assist를 사용 설정하려면 Cloud Console UI 상단의 검색창을 클릭하고 Gemini에게 물어보기를 선택합니다 (Gemini에게 Cloud 콘솔에 관해 물어보기라고 표시될 수도 있음).
- 페이지의 필수 API 섹션으로 스크롤하여 Google Cloud를 위한 Gemini API를 사용 설정합니다.
- 채팅 인터페이스가 즉시 표시되지 않으면 채팅 시작을 클릭합니다. 먼저 Gemini에게 Cloud Workstations 사용의 몇 가지 이점을 설명해 달라고 요청하세요. 잠시 시간을 내어 생성된 대답을 살펴보세요.
- 다음으로 Agent Builder의 이점과 생성형 응답을 실현하는 데 어떻게 도움이 되는지 묻습니다.
- 마지막으로 비교를 살펴보겠습니다. Google Cloud 콘솔의 Gemini 채팅 창에서 다음 질문을 합니다.
What are the major steps to creating a search app grounded in a
GCS data source using Vertex AI Agent builder?
- 이제 시크릿 창이 아닌 창에서 여기의 공개 Gemini 웹사이트로 이동하여 필요한 경우 로그인하고 동일한 질문을 합니다. 응답이 동일하거나 적어도 비슷한가요? 구체적인 단계는 무엇인가요? 어느 쪽이 눈에 띄게 더 나은가요? 어쨌든 다음 단계를 진행할 때 응답을 염두에 두세요.
참고: 임시 Qwiklabs 계정을 사용하여 위 단계를 수행하려고 하면 차단됩니다. 조직에서 Gemini 웹 앱 사용을 허용하지 않아 직장 계정도 차단된 경우 이 단계를 건너뛰고 다음 단계로 진행하세요. 이로 인해 연습문제를 완료하는 데는 영향을 미치지 않습니다.
5. 작업 2. Vertex AI Agent Builder에서 요리 조언 챗봇을 위한 검색 앱 만들기
빌드 중인 웹사이트에는 사용자가 요리 관련 질문에 대한 답변을 찾을 수 있도록 설계된 챗봇이 포함된 요리 조언 페이지가 있습니다. 이 도구는 70개의 공개 도메인 레시피북이 포함된 소스를 기반으로 하는 Gemini를 기반으로 합니다. 레시피북은 Gemini가 질문에 답변할 때 사용하는 정보 소스로 사용됩니다.
- Cloud 콘솔 검색창을 사용하여 Vertex AI로 이동합니다. 대시보드에서 모든 권장 API 사용 설정을 클릭합니다. Vertex AI API 자체를 사용 설정해야 한다는 팝업 상자가 표시되면 이를 사용 설정합니다.
- 검색을 사용하여 Agent Builder로 이동한 다음 계속 및 API 활성화를 클릭합니다.
- 앞서 Gemini에서 제안한 바와 같이 Agent Builder에서 검색 앱을 만들려면 공신력 있는 데이터 소스를 만들어야 합니다. 사용자가 검색하면 Gemini는 질문과 지능적인 대답을 작성하는 방법을 이해하지만, 본능적인 지식을 가져오는 대신 근거가 있는 소스에서 대답에 사용되는 정보를 찾습니다.
왼쪽 메뉴에서 데이터 스토어로 이동하여 데이터 스토어 만들기를 선택합니다. 4. 요리 조언 페이지의 기반으로 사용 중인 공개 도메인 레시피북은 현재 외부 프로젝트의 Cloud Storage 버킷에 있습니다. Cloud Storage 소스 유형을 선택합니다. 5. 가져오는 정보 유형과 관련된 기본 옵션을 검토하되 변경하지는 않습니다. 가져오기 유형을 폴더로 설정하고 버킷 경로에 labs.roitraining.com/labs/old-cookbooks
를 사용한 다음 계속을 클릭합니다. 6. 데이터 스토어 이름을 old-cookbooks
로 지정합니다. 수정하여 ID를 old-cookbooks-id
로 변경하고 데이터 스토어를 만듭니다.
Vertex AI Agent Builder는 여러 앱 유형을 지원하며 데이터 스토어는 각각의 정보 소스로 작동합니다. 검색 앱은 일반적인 용도와 검색에 적합합니다. 채팅 앱은 Dataflow 기반 챗봇/보이스봇 애플리케이션의 생성형 흐름을 위한 것입니다. 맞춤 콘텐츠 앱은 더 나은 맞춤 콘텐츠 엔진을 만드는 데 도움이 됩니다. 에이전트 앱은 생성형 AI 기반 에이전트를 만드는 데 사용됩니다. 결국에는 상담사가 우리가 원하는 작업을 가장 잘 수행할 수 있을 것으로 보이지만 현재 제품이 미리보기 버전이므로 검색 앱 유형을 계속 사용할 예정입니다. 7. 왼쪽 메뉴를 사용하여 앱으로 이동한 다음 앱 만들기를 클릭합니다. 8. 검색 앱 유형을 선택합니다. 다양한 옵션을 살펴보지만 변경하지는 않습니다. 앱 이름을 cookbook-search
로 지정합니다. 수정을 클릭하고 앱 ID를 cookbook-search-id
로 설정합니다. 회사를 Google
로 설정하고 계속을 클릭합니다. 9. 몇 단계 전에 만든 old-cookbooks
데이터 스토어를 선택하고 검색 앱을 만듭니다.
활동 탭을 살펴보면 아직 레시피북이 가져오고 색인을 생성하고 있는 것을 볼 수 있습니다. Agent Builder가 제공된 70개의 레시피북에 포함된 수천 개의 페이지에 색인을 생성하는 데 5분 이상 걸립니다. 작동하는 동안 레시피 생성기의 레시피 데이터베이스 데이터를 로드하고 정리해 보겠습니다.
6. 작업 3. Gemini Code Assist를 사용하여 Colab Enterprise 노트북에 데이터를 로드하고 정리
Google Cloud에서는 Jupiter 노트북을 사용할 수 있는 몇 가지 주요 방법을 제공합니다. Google의 최신 제품인 Colab Enterprise를 사용합니다. 무료 환경에서 Jupiter 노트북을 실험하려는 개인 및 조직에서 흔히 사용하는 Google의 Colab 제품을 알고 계신 분도 있을 것입니다. Colab Enterprise는 Google의 다른 클라우드 제품과 완전히 통합되어 있으며 GCP 환경의 보안 및 규정 준수 기능을 최대한 활용하는 상용 Google Cloud 제품입니다.
Colab Enterprise에서 제공하는 기능 중 하나는 Google의 Gemini Code Assist와의 통합입니다. Code Assist는 여러 코드 편집기에서 사용할 수 있으며 코딩하는 동안 조언과 원활한 인라인 추천을 제공할 수 있습니다. 레시피 데이터를 처리하는 동안 이 생성형 어시스턴트를 활용합니다.
- 검색을 사용하여 Colab Enterprise 및 노트북 만들기로 이동합니다. 새로운 Colab 기능을 실험해 보라는 메시지가 표시되면 닫습니다. 노트북의 컴퓨팅 성능인 런타임을 사용 설정하려면 새 노트북의 오른쪽 상단에 있는 연결을 누릅니다.
- Colab Enterprise Files 창에서 현재 노트북 이름 옆에 있는 점 3개로 된 메뉴를 사용하여 이름을
Data Wrangling
로 바꿉니다.
- 새 + 텍스트 상자를 만들고 위쪽 화살표를 사용하여 페이지의 첫 번째 셀이 되도록 이동합니다.
- 텍스트 상자를 수정하고 다음을 입력합니다.
# Data Wrangling
Import the Pandas library
- 방금 만든 텍스트 블록 아래의 코드 블록에서 imp를 입력하기 시작하면 Gemini Code Assist가 나머지 가져오기를 회색으로 제안합니다. 탭 키를 눌러 제안사항을 수락합니다.
import pandas as pd
- 가져오기 코드 상자 아래에 텍스트 상자를 하나 더 만들고 다음을 입력합니다.
Create a Pandas DataFrame from: gs://labs.roitraining.com/labs/recipes/recipe_dataset.csv. View the first few records.
- 다른 코드 블록을 만들고 수정합니다. 다시 df를 입력하고 Gemini Code Assistant에서 생성된 코드를 살펴봅니다. 생성된 추천 위로 Python 키워드의 자동 완성 드롭리스트가 표시되면 Esc 키를 눌러 밝은 회색의 추천 코드를 확인합니다. 탭을 다시 눌러 추천을 수락합니다. 추천에 head() 함수 호출이 포함되지 않은 경우 추가합니다.
df = pd.read_csv('gs://labs.roitraining.com/labs/recipes/recipe_dataset.csv')
df.head()
- Pandas를 가져온 첫 번째 코드 셀을 클릭하고 명령어 메뉴 또는 키보드를 사용하여 선택한 셀을 실행합니다. 키보드에서 shift+enter를 누르면 셀이 실행되고 포커스가 다음 셀로 이동하며 필요한 경우 셀이 생성됩니다. 계속하기 전에 셀이 실행될 때까지 기다립니다.
참고: 셀이 실행되지 않은 경우 왼쪽에 [ ] 가 표시됩니다. 셀이 실행되는 동안 작동하는 회전 애니메이션이 표시됩니다. 셀이 완료되면 [13]과 같은 숫자가 표시됩니다. 9. CSV를 DataFrame에 로드하는 셀을 실행합니다. 파일이 로드될 때까지 기다린 후 데이터의 처음 5개 행을 살펴봅니다. 이 데이터는 BigQuery에 로드할 레시피 데이터이며, 나중에 레시피 생성기를 기반으로 하는 데 사용됩니다. 10. 새 코드 블록을 만들고 아래 주석을 입력합니다. 주석을 입력한 후 다음 코드 줄로 이동하면 df.columns
제안이 표시됩니다. 수락한 다음 셀을 실행합니다.
# List the current DataFrame column names
Jupyter 노트북에서 Gemini Code Assist의 도움을 받는 방법에는 코드 셀 위의 텍스트 셀 또는 코드 셀 자체의 주석이라는 두 가지 방법이 있습니다. 코드 셀 내의 주석은 Jupyter 노트북에서 잘 작동하지만 이 접근 방식은 Google의 Gemini Code Assist를 지원하는 다른 IDE에서도 작동합니다.
- 열을 정리해 보겠습니다.
Unnamed: 0
열 이름을id
로,link
열 이름을uri
로 바꿉니다. 원하는 프롬프트 > 코드 기법을 사용하여 코드를 만든 다음 만족스러우면 셀을 실행합니다.
# Rename the column 'Unnamed: 0' to 'id' and 'link' to 'uri'
df.rename(columns={'Unnamed: 0': 'id', 'link': 'uri'}, inplace=True)
source
및NER
열을 삭제하고head()
를 사용하여 처음 몇 행을 봅니다. 다시 Gemini를 사용하여 도움을 받으세요. 마지막 두 줄을 실행하고 결과를 살펴봅니다.
# Remove the source and NER columns
df.drop(columns=['source', 'NER'], inplace=True)
df.head()
- 데이터 세트에 있는 레코드 수를 확인해 보겠습니다. 다시 한번 프롬프트 기법을 선택하고 Gemini를 사용하여 코드를 생성할 수 있는지 확인합니다.
# Count the records in the DataFrame
df.shape # count() will also work
- 223만 개의 레코드는 처리할 시간이 충분하지 않을 수 있습니다. 오늘 연습에서는 Agent Builder의 색인 생성 프로세스가 너무 오래 걸릴 수 있습니다. 절충안으로 150,000개의 레시피를 샘플링하여 사용해 보겠습니다. 프롬프트 > 코드 접근 방식을 사용하여 샘플을 가져와
dfs
(소문자 s)라는 새 DataFrame에 저장합니다.
# Sample out 150,000 records into a DataFrame named dfs
dfs = df.sample(n=150000)
- 레시피 소스 데이터를 BigQuery에 로드할 준비가 되었습니다. 로드하기 전에 BigQuery로 이동하여 테이블을 보관할 데이터 세트를 준비해 보겠습니다. Google Cloud 콘솔에서 검색창을 사용하여 BigQuery로 이동합니다. BigQuery를 마우스 오른쪽 버튼으로 클릭하고 새 브라우저 탭에서 열 수 있습니다.
- 아직 표시되지 않으면 Cloud 콘솔 오른쪽 상단의 Gemini 로고를 사용하여 Gemini AI Chat 패널을 엽니다. API를 다시 사용 설정하라는 메시지가 표시되면 사용 설정을 누르거나 페이지를 새로고침합니다. 프롬프트를 실행합니다.
What is a dataset used for in BigQuery?
응답을 살펴본 후 다음과 같이 질문합니다.How can I create a dataset named recipe_data using the Cloud Console?
결과를 다음 몇 가지 단계와 비교해 보세요.
- BigQuery 탐색기 창에서 프로젝트 ID 옆에 있는 점 3개 작업 보기 메뉴를 클릭합니다. 그런 다음 데이터 세트 만들기를 선택합니다.
- 데이터 세트 및 ID를
recipe_data
로 지정합니다. 위치 유형을 미국으로 두고 데이터 세트 만들기를 클릭합니다. 데이터 세트가 이미 존재한다는 오류가 표시되면 계속 진행합니다.
BigQuery에서 데이터 세트를 만들었으므로 노트북으로 다시 전환하여 삽입을 진행해 보겠습니다. 19. Colab Enterprise에서 데이터 정리 노트북으로 다시 전환합니다. 새 코드 셀에서 project_id
라는 변수를 만들고 이를 사용하여 현재 프로젝트 ID를 보관합니다. 이 안내의 왼쪽 상단에 있는 실습 종료 버튼 아래에서 현재 프로젝트 ID를 찾을 수 있습니다. 원하는 경우 Cloud Console 홈페이지에서도 확인할 수 있습니다. 값을 project_id
변수에 할당하고 셀을 실행합니다.
# Create a variable to hold the current project_id
project_id='YOUR_PROJECT_ID'
- 프롬프트 > 코드 접근 방식을 사용하여 방금 만든 데이터 세트
recipe_data
의recipes
라는 테이블에 DataFramedfs
를 삽입하는 코드 블록을 만듭니다. 셀을 실행합니다.
dfs.to_gbq(destination_table='recipe_data.recipes', project_id=project_id, if_exists='replace')
7. 작업 4. Vertex AI Agent Builder에서 레시피 생성기를 위한 검색 앱 만들기
좋습니다. 레시피 데이터 테이블이 생성되었으므로 이를 사용하여 레시피 생성기의 기반 데이터 소스를 빌드해 보겠습니다. 사용할 접근 방식은 요리 챗봇에 사용한 것과 유사합니다. Vertex AI Agent Builder를 사용하여 데이터 스토어를 만든 다음 이를 검색 앱의 정보 소스로 사용합니다.
원하는 경우 Google Cloud 콘솔에서 Gemini에게 상담사 빌더 검색 앱을 만드는 단계를 알려 달라고 요청하거나 아래에 나와 있는 단계를 따르세요.
- 검색을 사용하여 에이전트 빌더로 이동합니다. 데이터 스토어 및 데이터 스토어 만들기를 엽니다. 이번에는 BigQuery 데이터 스토어 유형을 선택합니다.
- 테이블 선택 셀에서 찾아보기를 누르고
recipes
를 검색합니다. 표 옆에 있는 라디오 버튼을 선택합니다. 다른 qwiklabs-gcp-... 프로젝트의 레시피가 표시되면 나에게 속한 레시피를 선택해야 합니다.
참고: recipes
옆에 있는 라디오 버튼을 선택하는 대신 recipes
를 클릭하면 브라우저에 새 탭이 열리고 BigQuery의 테이블 개요 페이지로 이동합니다. 브라우저 탭을 닫고 Agent Builder에서 라디오 버튼을 선택하기만 하면 됩니다. 3. 나머지 기본 옵션을 검토하되 변경하지 말고 계속을 클릭합니다. 4. 스키마 검토 페이지에서 초기 기본 구성을 검토하지만 아무것도 변경하지 않습니다. 계속 5. 데이터 스토어 이름을 recipe-data
로 지정합니다. 데이터 스토어 ID를 수정하여 recipe-data-id
로 설정합니다. 데이터 스토어를 만듭니다. 6. 왼쪽 탐색 메뉴와 앱 만들기를 사용하여 앱으로 이동합니다. 7. 검색 앱을 다시 선택합니다. 앱 이름을 recipe-search
로 지정하고 ID를 recipe-search-id
로 설정합니다. 회사 이름을 Google
로 설정하고 계속을 클릭합니다. 8. 이번에는 recipe-data 데이터 소스를 확인합니다. 앱을 만듭니다.
데이터베이스 테이블의 색인이 생성되는 데 다소 시간이 걸립니다. 그동안 BigQuery의 새로운 데이터 캔버스를 실험해 보고 흥미로운 레시피를 찾아보겠습니다. 9. 검색창을 사용하여 BigQuery로 이동합니다. BigQuery Studio 상단에서 가장 오른쪽 탭 옆에 있는 아래쪽 화살표를 클릭하고 데이터 캔버스를 선택합니다. 리전을 us-central1로 설정합니다.
- 데이터 캔버스 검색창에서
recipes
를 검색하고 테이블을 캔버스에 추가합니다. - 레시피 테이블의 시각적 표현이 BigQuery 데이터 캔버스에 로드됩니다. 테이블의 스키마를 살펴보고, 테이블의 데이터를 미리 보고, 기타 세부정보를 살펴볼 수 있습니다. 표 표현 아래에서 쿼리를 클릭합니다.
- 캔버스에 대략 일반적인 BigQuery 쿼리 대화상자가 로드되지만 한 가지 추가사항이 있습니다. 쿼리 창 위에 Gemini에 도움을 요청하는 데 사용할 수 있는 텍스트 상자가 있습니다. 샘플에서 케이크 레시피를 찾을 수 있는지 살펴보겠습니다. 다음 프롬프트를 실행합니다 (텍스트를 입력하고 Enter/Return 키를 눌러 SQL 생성을 트리거).
Please select the title and ingredients for all the recipes with a title that contains the word cake.
- 생성된 SQL을 확인합니다. 만족스러우면 쿼리를 실행합니다.
- 괜찮은데? 계속하기 전에 다른 프롬프트와 쿼리를 자유롭게 실험해 보세요. 실험할 때는 구체적이지 않은 프롬프트를 사용해 효과가 있는 프롬프트와 그렇지 않은 프롬프트를 파악하세요. 예를 들어 다음 프롬프트가 표시됩니다.
Do I have any chili recipes?
(새 쿼리를 실행하는 것을 잊지 마세요.) 칠리 레시피 목록을 반환했지만 다음과 같이 수정할 때까지 재료가 누락되었습니다.
Do I have any chili recipes? Please include their title and ingredients.
(예, 프롬프트할 때는 '주세요'라고 말합니다. 엄마가 자랑스러워하실 거예요.)
칠리 레시피 중 하나에 버섯이 포함되어 있는 것을 발견했습니다. 칠리에 버섯을 넣는 사람이 있을까요? Gemini에게 이러한 레시피를 제외해 달라고 요청했습니다.
Do I have any chili recipes? Please include their title and ingredients, and ignore any recipes with mushrooms as an ingredient.
8. 작업 5. Gemini의 도움을 받아 핵심 Python 및 Streamlit 웹 애플리케이션의 프레임 설정
Vertex AI Agent Builder 데이터 스토어의 색인이 생성되고 검색 앱이 거의 준비되었으므로 이제 웹 애플리케이션을 빌드해 보겠습니다.
작업하는 동안 Gemini Code Assist를 활용할 예정입니다. Visual Studio Code에서 Gemini Code Assist를 사용하는 방법에 관한 자세한 내용은 여기의 문서를 참고하세요.
클라우드 기반 개발 환경인 Google Cloud Workstation에서 개발을 진행합니다. 이 경우 Eclipse Theia (오픈소스 Visual Studio Code)가 미리 로드되어 있습니다. 이 연습의 자동화 스크립트로 Cloud Workstation 클러스터와 구성이 생성되었지만 Cloud Workstation 자체는 만들어야 합니다. Cloud Workstations 및 사용에 관해 자세히 알아보려면 Gemini Cloud Assist에 문의하세요. :-)
- 검색을 사용하여 Cloud Workstations로 이동한 다음 워크스테이션 만들기를 클릭합니다. 워크스테이션 이름을
dev-env
로 지정하고 my-config 구성을 사용합니다. 워크스테이션을 만듭니다. - 몇 분 후 '내 워크스테이션' 목록에 새 워크스테이션이 표시됩니다.
dev-env
를 시작하고 실행되면 개발 환경을 실행합니다. - 워크스테이션 편집기가 새 브라우저 탭에서 열리고 잠시 후 익숙한 Theia (Visual Studio Code) 인터페이스가 표시됩니다. 인터페이스 왼쪽에서 소스 제어 탭을 펼치고 저장소 클론을 누릅니다.
- 저장소 URL에
https://github.com/haggman/recipe-app
를 입력합니다. 저장소를user
폴더에 클론한 다음 클론된 저장소를 열어 수정합니다. - 클론된 폴더를 살펴보고 웹 애플리케이션 작업을 시작하기 전에 편집기의 Cloud Code 플러그인을 Google Cloud에 로그인하고 Gemini를 사용 설정해야 합니다. 그럼 시작하겠습니다. 편집기 왼쪽 하단에서 Cloud Code - 로그인을 클릭합니다. 링크가 표시되지 않으면 1분 정도 기다린 후 다시 확인하세요.
- 터미널 창에 긴 URL이 표시됩니다. 브라우저에서 URL을 열고 단계에 따라 Cloud Code에 Google Cloud 환경에 대한 액세스 권한을 부여합니다. 인증할 때는 개인 Google Cloud 계정이 아닌 연습 임시
student-...
계정을 사용해야 합니다. 마지막 대화상자에서 인증 코드를 복사하여 Cloud Workstation 브라우저 탭의 대기 중인 터미널 창에 다시 붙여넣습니다. - 잠시 후 편집기 왼쪽 하단의 Cloud Code 링크가 Cloud Code - No Project(Cloud Code - 프로젝트 없음)로 변경됩니다. 새 링크를 클릭하여 프로젝트를 선택합니다. 편집기 상단에 명령 팔레트가 열립니다. Google Cloud 프로젝트 선택을 클릭하고 qwiklabs-gcp-... 프로젝트를 선택합니다. 잠시 후 편집기 왼쪽 하단의 링크가 업데이트되어 프로젝트 ID가 표시됩니다. 이는 Cloud Code가 작업 프로젝트에 연결되었음을 나타냅니다.
- Cloud Code가 프로젝트에 연결되었으므로 이제 Gemini Code Assist를 활성화할 수 있습니다. 편집기 인터페이스의 오른쪽 하단에서 취소선이 그어진 Gemini 로고를 클릭합니다. 편집기 왼쪽에 Gemini Chat 창이 열립니다. Google Cloud 프로젝트 선택을 클릭합니다. 명령어 팔레트가 열리면 qwiklabs-gcp-... 프로젝트를 선택합니다. 단계를 올바르게 수행했고 Google에서 아무것도 변경하지 않은 경우 이제 활성 Gemini 채팅 창이 표시됩니다.
- 마지막으로 편집기 터미널 창을 동일하게 구성해 보겠습니다. 햄버거 메뉴 > 보기 > 터미널을 사용하여 터미널 창을 엽니다.
gcloud init
실행 링크를 다시 사용하여 Cloud Shell 터미널이qwiklabs-gcp-...
프로젝트에서 작동하도록 허용합니다. 메시지가 표시되면qwiklabs-gcp-...
프로젝트의 숫자 옵션을 선택합니다. - 좋습니다. 터미널, Gemini 채팅, Cloud Code 구성이 모두 설정되었습니다. 탐색기 탭을 열고 몇 분 동안 현재 프로젝트의 파일을 살펴보세요.
- 탐색기에서 수정할
requirements.txt
파일을 엽니다. Gemini 채팅 창으로 전환하여 다음과 같이 요청합니다.
From the dependencies specified in the requirements.txt file, what type of application are we building?
- 이제 Python과 Streamlit을 사용하여 Vertex AI 및 Discovery Engine과 상호작용하는 대화형 웹 애플리케이션을 빌드합니다. 지금은 웹 애플리케이션 구성요소에 집중하겠습니다. Gemini에서 설명하는 것처럼 Streamlit은 Python으로 데이터 기반 웹 애플리케이션을 빌드하기 위한 프레임워크입니다. 이제 다음을 요청합니다.
Does the current project's folder structure seem appropriate for a Streamlit app?s
이 부분에서 Gemini에 문제가 발생하는 경향이 있습니다. Gemini는 현재 편집기에서 열려 있는 파일에 액세스할 수 있지만 전체 프로젝트를 실제로 볼 수는 없습니다. 다음과 같이 질문해 보세요.
Given the below, does the current project's file and folder structure seem appropriate for a Streamlit app?
- build.sh
- Home.py
- requirements.txt
- pages
-- Cooking_Advice.py
-- Recipe_Search.py
더 나은 답변을 받으려면
- Streamlit에 대해 자세히 알아보겠습니다.
What can you tell me about Streamlit?
좋습니다. Gemini에서 장단점을 포함한 멋진 개요를 제공하고 있습니다.
- 단점을 알아보려면 다음과 같이 질문할 수 있습니다.
What are the major downsides or shortcomings?
Gemini 채팅은 대화형 (멀티턴)이므로 'Streamlit의'라고 말할 필요가 없습니다. 채팅 세션에 있으므로 Gemini는 대화 내용을 알고 있습니다. Gemini 채팅 기록을 삭제하려면 Gemini 코드 채팅 창 상단의 휴지통 아이콘을 사용하세요.
9. 작업 6: Cloud Run에 웹 애플리케이션 배포
좋습니다. 핵심 애플리케이션 구조가 마련되었습니다. 하지만 제대로 작동하나요? 더 나아가 Google Cloud에서 어디에 호스팅해야 하나요?
- Gemini 채팅 창에서 다음을 요청합니다.
If I containerize this application, what compute technologies
in Google Cloud would be best for hosting it?
- 아직 IDE에서 작업하고 있지 않은 경우 Google Cloud Assist를 사용할 수도 있습니다. Google Cloud 콘솔을 연 다음 Gemini Cloud Assist를 열고 다음을 요청합니다.
If I have a containerized web application, where would be the
best place to run it in Google Cloud?
두 조언이 동일했나요? 조언에 동의하거나 동의하지 않으신 부분이 있나요? Gemini는 생성형 AI 어시스턴트이며, 사람의 어시스턴트와 마찬가지로 Gemini가 말하는 모든 내용에 동의하지 않을 수 있습니다. 하지만 Google Cloud와 코드 편집기에서 작업하는 동안 항상 이 도우미가 곁에 있으면 훨씬 더 효율적으로 작업할 수 있습니다.
- 스테이트리스(Stateless)의 단기 컨테이너화된 웹 애플리케이션의 경우 Cloud Run이 적합합니다. 코드 편집기의 Gemini 채팅 창에서 다음 프롬프트를 사용해 보세요.
What steps would be required to run this application in
Cloud Run?
- 먼저 Dockerfile을 만들어야 할 것 같습니다. 편집기를 사용하여 프로젝트 폴더의 루트에
Dockerfile
라는 파일을 만듭니다. 실수로 페이지 폴더에 배치하지 않도록 주의하세요. 수정할 파일을 엽니다. - 측면 Gemini 채팅 패널을 사용하여
Dockerfile
를 만들어 보겠습니다. 아래와 같은 프롬프트를 사용합니다. 결과가 채팅에 표시되면 추천 Dockerfile 바로 위에 있는 복사 아이콘 옆의 +를 사용하여 추천 코드를 Dockerfile에 삽입합니다.
Create a Dockerfile for the application in the current folder.
The dependencies are defined in requirements.txt and I want you
to use the Python 3 slim bookworm base image.
Gemini가 동일한 프롬프트에 항상 동일한 대답을 반환하지는 않습니다. Gemini에 Dockerfile을 처음 요청했을 때 제가 추천할 파일을 바로 가져왔습니다. 방금 다음과 같은 추천을 받았습니다.
```docker
# Base image
FROM python:3-bookworm-slim
# Set working directory
WORKDIR /app
# Install dependencies
RUN apt-get update && apt-get install -y \
build-essential \
libpq-dev \
gcc \
python3-dev \
&& rm -rf /var/lib/apt/lists/*
# Install pip and virtualenv
RUN pip install --upgrade pip virtualenv
# Create virtual environment
RUN python3 -m venv venv
# Activate virtual environment
WORKDIR /app/venv/bin
RUN . activate
# Install Streamlit and libraries from requirements.txt
RUN pip install -r requirements.txt
# Copy application files
COPY . /app
# Expose port 8501 for Streamlit
EXPOSE 8501
# Start Streamlit app
CMD ["streamlit", "run", "main.py"]
That's a heck of a Dockerfile. I'd simplify it a bit. We don't need the apt-get section as anything needed for Python is already in our base image. Also, using a virtual environment in a Python container is a waste of space, so I'd remove that. The expose command isn't strictly necessary, but it's fine. Also, it's trying to start main.py which I don't have.
6. Tweak the Dockerfile so it resembles the following:
FROM python:3.11-slim-bookworm
WORKDIR /app
COPY requirements.txt . RUN pip install –no-cache-dir –upgrade pip &&
pip install –no-cache-dir -r requirements.txt
COPY . .
CMD ["streamlit", "run", "Home.py"]
7. We need a place in Google cloud where we can store our container image. Let's get a little help from Gemini. In the Google Cloud Console Gemini Cloud Assist ask:
Google Cloud에서 Docker 이미지를 저장하기에 가장 좋은 위치는 어디인가요?
8. If one of the answers you received is the Google Container Registry, then I guess Gemini hasn't gotten word that GCR is deprecated. Again, just like human assistants, you may get out of date or simply wrong answers (hallucinations). Always make sure to consider your choices carefully, even when Gemini is recommending something.
Let's go with Artifact Registry. Ask Gemini Cloud Assist how to create a docker registry in Artifact Registry named cooking-images.
gcloud를 사용하여 Artifact Registry에 Docker 레지스트리를 만들려면 어떻게 해야 하나요?
9. Now ask Gemini how you could use Cloud Build to build a new image named `recipe-web-app` from the Dockerfile in the current folder.
방금 만든 Artifact Registry 저장소에서 동일한 이름의 이미지를 사용하여 gcloud로 recipe-web-app이라는 새 Cloud Run 서비스를 빌드하려면 어떻게 해야 하나요?
10. To save you a little time, I've created a script that will create the Artifact Registry repo (if needed), use Cloud Build to build and push the image to the repo, and finally to deploy the application to Cloud Run. In your code editor use the **Explorer** view to open `build.sh` and explore the file.
11. Gemini can operate via the chat window, but it can also work directly in your code file using comments, like we used in the Data Wrangling notebook, and it also may be invoked using Control+i on Windows or Command+i on Mac. Click somewhere in the build.sh script file, activate Gemini using the appropriate Command+i / Control+i command.
<img src="img/61ac2c9a245a3695.png" alt="61ac2c9a245a3695.png" width="624.00" />
12. At the prompt enter the below. Examine and **Accept** the change.
현재 파일에 주석을 달아주세요.
How cool is that?! How many times have you had to work with someone elses code, only to have to waste time gaining a base understanding of their commentless work before you can even start making your changes. Gemini to the rescue!
13. Let's build and deploy our application. In the terminal window execute the `build.sh` file.
. build.sh
14. If you watch the build process, first it will build the Artifact Registry docker repo. Then, it uses Cloud Build to create the container image from the Dockerfile in the local folder (since we didn't supply a `cloudbuild.yaml`). Lastly, the docker image will be deployed into a new Cloud Run service. At the end of the script you'll get a Cloud Run test URL to use.
Open the returned link in a new tab of your browser. Take a moment and explore the application's structure and pages. Nice, now we need a hook in our generative AI functionality.
## Task 7: Connect the Cooking Advice page to our cookbook-search Agent Builder app
We have the framework for the web application running, but we need to connect the two work pages to our two Vertex AI Agent Builder search apps. Let's start with Cooking Advice.
1. In the Google Cloud console use search to navigate to **Chat** in Vertex AI.
2. In the right hand settings page pane set the model to **gemini-1.5-flash-002**. Slide the output token limit up to the max so the model can return longer answers if needed. Open the **Safety Filter Settings**. Set Hate speech, Sexually explicit content, and Harassment content to **Block some**. Set Dangerous content to **Block few** and **Save**. We're setting Dangerous Content a bit lower because talking about knives and cutting can be misinterpreted by Gemini as violence.
3. Slide on the toggle to enable **Grounding** then click **Customize**. Set the grounding source to **Vertex AI search** and for the datastore path use the following. Change YOUR_PROJECT_ID to the project ID found up near the End Lab button in these instructions, then **Save** the grounding settings
projects/YOUR_PROJECT_ID/locations/global/collections/default_collection/dataStores/old-cookbooks-id
**Note:** If you get an error then you either didn't change the project ID to your actual project ID, or you may have missed the step where you changed the old-cookbooks Agent Builder Data Store ID. Check your Agent Builder > Data Stores > old-cookbooks for its actual Data store ID.
4. Test a couple of chat messages. Perhaps start with the below. Try a few others if you like.
토마토가 잘 익었는지 어떻게 알 수 있나요?
5. The model works, now let's experiment with the code. Click **Clear Conversation** so our conversations don't become part of the code then click **Get Code**.
<img src="img/dce8ad7ee006cca1.png" alt="dce8ad7ee006cca1.png" width="624.00" />
6. At the top of the code window, press Open Notebook so we can experiment and perfect the code in Colab Enterprise before integrating it into our app.
7. Take a few minutes to familiarize yourself with the code. Let's make a couple of changes to adapt it to what we want. Before we start, run the first code cell to connect to the compute and install the AI Platform SDK. After the block runs you will be prompted to restart the session. Go ahead and do that.
8. Move to the code we pulled out of Vertex AI Studio. Change the name of the method *multiturn_generate_content* to `start_chat_session`.
9. Scroll to the `model = GenerativeModel(` method call. The existing code defines the `generation_config` and `safety_settings` but doesn't actually use them. Modify the creation of the `GenerativeModel` so it resembles:
model = GenerativeModel( "gemini-1.5-flash-002", tools=tools, generation_config=generation_config, safety_settings=safety_settings, )
10. Lastly, add a final line to the method, just below `chat = model.start_chat()`, so the function returns the `chat` object. The finished function should look like the below.
**Note:** DO NOT COPY this code into your notebook. It is simply here as a sanity check.
def start_chat_session(): vertexai.init(project="qwiklabs-gcp-02-9a7298ceaaec", location="us-central1") tools = [ Tool.from_retrieval( retrieval=grounding.Retrieval( source=grounding.VertexAISearch(datastore="projects/qwiklabs-gcp-02-9a7298ceaaec/locations/global/collections/default_collection/dataStores/old-cookbooks-id"), ) ), ] model = GenerativeModel( "gemini-1.5-flash-002", tools=tools, generation_config=generation_config, safety_settings=safety_settings, ) chat = model.start_chat() return chat
11. Scroll to the bottom of the code cell and change the final line calling the old function so it calls the new function name and stores the returned object in a variable `chat`. Once you are satisfied with your changes, run the cell.
chat = start_chat_session()
12. Create a new code cell and add the comment `# Use chat to invoke Gemini and print out the response`. Move to the next line and type resp and Gemini should auto complete the block for you. Update the prompt to `How can I tell if a tomato is ripe?`. Run the cell
response = chat.send_message("토마토가 잘 익었는지 어떻게 알 수 있나요?") print(response)
13. That's the response alright, but the part we really want is that nested text field. Modify the codeblock to print just that section, like:
response = chat.send_message("토마토가 잘 익었는지 어떻게 알 수 있나요?") print(response.candidates[0].content.parts[0].text)
14. Good, now that we have working chat code, let's integrate it into our web application. Copy all the contents of the code cell that creates the `start_chat_session` function (we won't need the test cell). If you click into the cell you can click the triple dot menu in the upper right corner and copy from there
<img src="img/17bf8d947393d4b.png" alt="17bf8d947393d4b.png" width="326.00" />
15. Switch to your Cloud Workstation editor and open pages\Cooking_Advice.py for editing.
16. Locate the comment:
이 메시지 아래에 노트북에서 복사한 코드를 추가합니다.
17. Paste your copied code just below the above comment. Nice, now we have the section which drives the chat engine via a grounded call to Gemini. Now let's integrate it into Streamlit.
18. Locate section of commented code directly below the comment:
다음은 세션 변수를 설정하는 코드입니다.
안내에 따라 이 블록의 주석 처리를 해제합니다.
19. Uncomment this section of code (Up till the next `Setup done, let's build the page UI` section) and explore it. It creates or retrieves the chat and history session variables.
20. Next, we need to integrate the history and chat functionality into the UI. Scroll in the code until you locate the below comment.
다음은 채팅 인터페이스를 만드는 코드입니다.
지시에 따라 아래 코드의 주석 처리를 삭제합니다.
21. Uncomment the rest of the code below the comment and take a moment to explore it. If you like, highlight it and get Gemini to explain its functionality.
22. Excellent, now let's build the application and deploy it. When the URL comes back, launch the application and give the Cooking Advisor page a try. Perhaps ask it about ripe tomatoes, or the bot knows a good way to prepare brussels sprouts.
. build.sh
How cool is that! Your own personal AI cooking advisor :-)
## Task 8: (Optional) Connect the Recipe Search page to the recipe-search Agent Builder app
When we connected the Cooking Advice page to its grounded source, we did so using the Gemini API directly. For Recipe Search, let's connect to the Vertex AI Agent Builder search app directly.
1. In your Cloud Workstation editor, open the `pages/Recipe_Search.py` page for editing. Investigate the structure of the page.
2. Towards the top of the file, set your project ID.
3. Examine the `search_sample` function. This code more or less comes directly from the Discovery Engine documentation [here](https://cloud.google.com/generative-ai-app-builder/docs/preview-search-results#genappbuilder_search-python). You can find a working copy in this notebook [here](https://github.com/GoogleCloudPlatform/generative-ai/blob/main/search/create_datastore_and_search.ipynb).
4. The only change I made was to return the `response.results` instead of just the results. Without this, the return type is an object designed to page through results, and that's something we don't need for our basic application.
5. Scroll to the very end of the file and uncomment the entire section below `Here are the first 5 recipes I found`.
6. Highlight the whole section you just uncommented and open Gemini Code chat. Ask, `Explain the highlighted code`. If you don't have something selected, Gemini can explain the whole file. If you highlight a section and ask Gemini to explain, or comment, or improve it, Gemini will.
Take a moment and read through the explanation. For what it's worth, using a Colab Enterprise notebook is a great way to explore the Gemini APIs before you integrate them into your application. It's especially helpful at exploring some of the newer APIs which may not be documented as well as they could be.
7. At your editor terminal window, run `build.sh` to deploy the final application. Wait until the new version is deployed before moving to the next step.
## Task 9: (Optional) Explore the final application
Take a few minutes to explore the final application.
1. In the Google Cloud console, use search to navigate to **Cloud Run**, then click into your **recipe-web-app**.
2. Locate the application test URL (towards the top) and open it in a new browser tab.
3. The application home page should appear. Note the basic layout and navigation provided by Streamlit, with the python files from the `pages` folder displayed as navigational choices, and the `Home.py` loaded as the home page. Navigate to the **Cooking Advice** page.
4. After a few moments the chat interface will appear. Again, note the nice core layout provided by Streamlit.
5. Try a few cooking related questions and see how the bot functions. Something like:
브로콜리 준비에 관한 조언이 있나요?
전통적인 닭고기 수프 레시피는 어때요?
머랭에 대해 알려 줘.
6. Now let's find a recipe or two. Navigate to the Recipe Search page and try a few searches. Something like:
칠리 콘 카르네
칠리, 옥수수, 쌀
레몬 머랭 파이
딸기가 들어간 디저트
## Congratulations!
You have created an application leveraging Vertex AI Agent Builder applications. Along the way you've explored Gemini Cloud Assist, Gemini Code Assist, and the natural language to SQL features of BigQuery's Data Canvas. Fantastic job!