이 Codelab 정보
1. 개요
이 실습에서는 CICD 파이프라인을 설정하고 Gemini와 통합하여 코드 검토 단계를 자동화합니다.
학습할 내용
이 실습에서는 다음 작업을 진행하는 방법을 학습합니다.
- GitHub, GitLab, CircleCI에서 GenAI 코드 검토 자동화 단계를 추가하는 방법
- LangChain ReAct 에이전트 및 툴킷을 사용하여 GitLab 문제에 댓글을 달고 JIRA 티켓을 여는 등의 작업을 자동화하는 방법
기본 요건
- 이 실습에서는 Cloud 콘솔 및 Cloud Shell 환경에 익숙하다고 가정합니다.
2. 설정 및 요건
Cloud 프로젝트 설정
- Google Cloud Console에 로그인하여 새 프로젝트를 만들거나 기존 프로젝트를 재사용합니다. 아직 Gmail이나 Google Workspace 계정이 없는 경우 계정을 만들어야 합니다.
- 프로젝트 이름은 이 프로젝트 참가자의 표시 이름입니다. 이는 Google API에서 사용하지 않는 문자열이며 언제든지 업데이트할 수 있습니다.
- 프로젝트 ID는 모든 Google Cloud 프로젝트에서 고유하며, 변경할 수 없습니다(설정된 후에는 변경할 수 없음). Cloud 콘솔은 고유한 문자열을 자동으로 생성합니다. 일반적으로는 신경 쓰지 않아도 됩니다. 대부분의 Codelab에서는 프로젝트 ID (일반적으로
PROJECT_ID
로 식별됨)를 참조해야 합니다. 생성된 ID가 마음에 들지 않으면 다른 임의 ID를 생성할 수 있습니다. 또는 직접 시도해 보고 사용 가능한지 확인할 수도 있습니다. 이 단계 이후에는 변경할 수 없으며 프로젝트 기간 동안 유지됩니다. - 참고로 세 번째 값은 일부 API에서 사용하는 프로젝트 번호입니다. 이 세 가지 값에 대한 자세한 내용은 문서를 참고하세요.
- 다음으로 Cloud 리소스/API를 사용하려면 Cloud 콘솔에서 결제를 사용 설정해야 합니다. 이 Codelab 실행에는 많은 비용이 들지 않습니다. 이 튜토리얼이 끝난 후에 요금이 청구되지 않도록 리소스를 종료하려면 만든 리소스 또는 프로젝트를 삭제하면 됩니다. Google Cloud 신규 사용자는 300달러(USD) 상당의 무료 체험판 프로그램에 참여할 수 있습니다.
환경 설정
Gemini 채팅을 엽니다.
또는 검색창에 'Gemini에게 물어보기'를 입력합니다.
Cloud AI Companion API를 사용 설정합니다.
'Start chatting
'를 클릭하고 샘플 질문 중 하나를 따르거나 직접 프롬프트를 입력하여 사용해 봅니다.
프롬프트 예시:
- Cloud Run을 5가지 주요 요점으로 설명합니다.
- Google Cloud Run 제품 관리자로서 학생에게 Cloud Run을 5가지 핵심사항으로 간단히 설명합니다.
- Google Cloud Run 제품 관리자로서 인증된 Kubernetes 개발자에게 Cloud Run을 5가지 핵심사항으로 간단히 설명합니다.
- Google Cloud Run 제품 관리자로서 Cloud Run과 GKE 중 어느 쪽을 사용해야 하는지 선임 개발자에게 5가지 핵심 사항으로 설명합니다.
프롬프트 가이드에서 더 나은 프롬프트 작성에 대해 자세히 알아보세요.
Google Cloud를 위한 Gemini에서 사용자 데이터를 사용하는 방법
Google 개인 정보 보호 약정
Google은 업계 최초로 AI/ML 개인 정보 보호 약정을 발표했습니다. 여기에는 클라우드에 저장된 고객 데이터에 대해 고객이 최고 수준의 보안 및 제어 권한을 가져야 한다는 Google의 신념이 표명되어 있습니다.
제출 및 수신하는 데이터
분석하거나 완료하기 위해 Gemini에 제출하는 모든 입력 정보나 코드를 포함하여 Gemini에 묻는 질문을 프롬프트라고 합니다. Gemini로부터 받는 답변이나 코드 완성을 '응답'이라고 합니다. Gemini는 프롬프트나 해당 응답을 데이터로 사용하여 모델을 학습시키지 않습니다.
프롬프트 암호화
Gemini에 프롬프트를 제출하면 Gemini의 기본 모델에 입력으로 전송 중인 데이터가 암호화됩니다.
Gemini에서 생성된 프로그램 데이터
Gemini는 퍼스트 파티 Google Cloud 코드와 선택된 서드 파티 코드로 학습됩니다. Gemini가 제공하는 코드 완성, 생성, 분석을 포함해 코드의 보안, 테스트, 효과에 대한 책임은 사용자에게 있습니다.
Google에서 메시지를 처리하는 방식을 자세히 알아보세요.
3. 프롬프트 테스트 옵션
기존 devai cli 프롬프트를 변경/확장하려면 다음과 같은 몇 가지 옵션이 있습니다.
Vertex AI Studio는 Google Cloud의 Vertex AI 플랫폼에 포함된 도구로, 생성형 AI 모델의 개발과 사용을 간소화하고 가속화하도록 설계되었습니다.
Google AI Studio는 프롬프트 엔지니어링 및 Gemini API를 프로토타입으로 제작하고 실험하기 위한 웹 기반 도구입니다. 1백만 개의 컨텍스트 윈도우가 포함된 Gemini 1.5 Pro를 가입하거나 자세히 알아보세요.
- Gemini 웹 앱 (gemini.google.com)
Google Gemini 웹 앱 (gemini.google.com)은 Google의 Gemini AI 모델을 살펴보고 활용하는 데 도움이 되도록 설계된 웹 기반 도구입니다.
- Android용 Google Gemini 모바일 앱 및 iOS용 Google 앱
4. 서비스 계정 만들기
검색창 오른쪽에 있는 아이콘을 클릭하여 Cloud Shell을 활성화합니다.
열린 터미널에서 Vertex AI API 및 Gemini 채팅을 사용하기 위해 필요한 서비스를 사용 설정합니다.
gcloud services enable \
aiplatform.googleapis.com \
cloudaicompanion.googleapis.com \
cloudresourcemanager.googleapis.com \
secretmanager.googleapis.com
승인하라는 메시지가 표시되면 '승인'을 클릭하여 계속합니다.
다음 명령어를 실행하여 새 서비스 계정과 키를 만듭니다.
이 서비스 계정을 사용하여 CICD 파이프라인에서 Vertex AI Gemini API에 API를 호출합니다.
PROJECT_ID=$(gcloud config get-value project)
SERVICE_ACCOUNT_NAME='vertex-client'
DISPLAY_NAME='Vertex Client'
KEY_FILE_NAME='vertex-client-key'
gcloud iam service-accounts create $SERVICE_ACCOUNT_NAME --display-name "$DISPLAY_NAME"
gcloud projects add-iam-policy-binding $PROJECT_ID --member="serviceAccount:$SERVICE_ACCOUNT_NAME@$PROJECT_ID.iam.gserviceaccount.com" --role="roles/aiplatform.admin" --condition None
gcloud projects add-iam-policy-binding $PROJECT_ID --member="serviceAccount:$SERVICE_ACCOUNT_NAME@$PROJECT_ID.iam.gserviceaccount.com" --role="roles/secretmanager.secretAccessor" --condition None
gcloud iam service-accounts keys create $KEY_FILE_NAME.json --iam-account=$SERVICE_ACCOUNT_NAME@$PROJECT_ID.iam.gserviceaccount.com
5. GitHub 저장소를 개인 GitHub 저장소로 포크
https://github.com/GoogleCloudPlatform/genai-for-developers/fork로 이동하여 GitHub 사용자 ID를 소유자로 선택합니다.
'main' 브랜치만 복사하는 옵션을 선택 해제합니다.
'Create fork
'을(를) 클릭합니다.
7. 저장소 보안 비밀 추가
포크된 GitHub 저장소의 'Settings / Secrets and variables / Actions
' 아래에 저장소 비밀을 만듭니다.
이름이 'GOOGLE_API_CREDENTIALS
'인 저장소 보안 비밀을 추가합니다.
Google Cloud Shell 창/탭으로 전환하고 Cloud Shell 터미널에서 아래 명령어를 실행합니다.
cat ~/vertex-client-key.json
파일 콘텐츠를 복사하여 보안 비밀의 값으로 붙여넣습니다.
Qwiklabs 프로젝트 ID를 값 로 사용하여
PROJECT_ID
시크릿을 추가합니다.
8. GitHub Actions 워크플로 실행
브라우저에서 GitHub 저장소로 이동하여 워크플로를 실행합니다.
워크플로가 코드 푸시 또는 수동 실행에서 실행되도록 구성됩니다.
'All workflows'(모든 워크플로)에서 'GenAI For Developers
'를 선택하고 'main
' 브랜치를 사용하여 'Run workflow
'를 클릭합니다.
결과 검토:
테스트 적용 범위 명령어의 결과:
devai review testcoverage -c ${{ github.workspace }}/sample-app/src/main/java/anthos/samples/bankofanthos/balancereader
코드 검토 명령어의 결과:
devai review code -c ${{ github.workspace }}/sample-app/src/main/java/anthos/samples/bankofanthos/balancereader
실적 검토 명령어의 결과:
devai review performance -c ${{ github.workspace }}/sample-app/src/main/java/anthos/samples/bankofanthos/balancereader
보안 검토 명령어의 결과:
devai review security -c ${{ github.workspace }}/sample-app/src/main/java/anthos/samples/bankofanthos/balancereader
차단기 검토 명령어의 결과:
devai review blockers -c ${{ github.workspace }}/sample-app/pom.xml
9. 저장소 복제
Cloud Shell 터미널로 돌아가서 저장소를 클론합니다.
GitHub 저장소의 폴더를 만듭니다.
mkdir github
cd github
명령어를 실행하기 전에 YOUR-GITHUB-USERID
를 GitHub 사용자 ID로 변경합니다.
터미널에서 Git 사용자 이름과 이메일을 설정합니다.
명령어를 실행하기 전에 값을 업데이트합니다.
git config --global user.name "Your Name"
git config --global user.email "your_email@example.com"
git clone https://github.com/YOUR-GITHUB-USERID/genai-for-developers.git
Cloud Shell 편집기에서 폴더를 변경하고 워크플로 파일을 엽니다.
cd genai-for-developers
cloudshell edit .github/workflows/devai-review.yml
구성 파일이 IDE에 표시될 때까지 기다립니다.
10. Gemini Code Assist 사용 설정
오른쪽 하단의 Gemini
아이콘을 클릭합니다.
'Login to Google Cloud
' 및 'Select a Google Cloud Project
'을 클릭합니다.
팝업 창에서 Qwiklabs 프로젝트를 선택합니다.
11. Gemini Code Assist로 코드 설명
devai-review.yml
파일의 아무 곳이나 마우스 오른쪽 버튼으로 클릭하고 Gemini Code Assist > Explain
를 선택합니다.
설명 검토:
12. 로컬에서 DEVAI CLI 실행
Cloud Shell 편집기로 돌아가 새 터미널을 엽니다.
Cloud Shell 터미널로 돌아가 아래 명령어를 실행하여 devai
를 로컬에 설치합니다.
pip3 install devai-cli
CLI가 설치되었지만 PATH에 없습니다.
WARNING: The script devai is installed in '/home/student_00_478dfeb8df15/.local/bin' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
아래 명령어를 실행하여 PATH 환경 변수를 업데이트합니다. 사용자의 홈 폴더 이름으로 바꿉니다. 예: student_00_478dfeb8df15
export PATH=$PATH:/home/YOUR-USER-HOME-FOLDER/.local/bin
devai CLI 명령어를 실행하여 로컬에서 코드 검토를 실행합니다. CLI 출력을 검토합니다.
export PROJECT_ID=$(gcloud config get-value project)
export LOCATION=us-central1
cd ~/github/genai-for-developers
devai review code -c ./sample-app/src/main/java/anthos/samples/bankofanthos/balancereader
아래 명령어를 실행하여 검토 스크립트를 엽니다.
cloudshell edit devai-cli/src/devai/commands/review.py
review.py
파일의 아무 곳이나 마우스 오른쪽 버튼으로 클릭하고 Gemini Code Assist > Explain
를 선택합니다.
설명을 검토합니다.
13. DevAI CLI 개발
이 섹션에서는 devai cli를 변경합니다.
시작하려면 python virtualenv를 설정하고 요구사항을 설치한 후 샘플 명령어를 실행합니다.
cd ~/github/genai-for-developers/devai-cli
python3 -m venv venv
. venv/bin/activate
pip3 install -r src/requirements.txt
pip3 install --editable ./src
devai echo
테스트 적용 범위 검토 명령어를 실행하여 모든 것이 제대로 작동하는지 확인합니다.
devai review testcoverage -c ~/github/genai-for-developers/sample-app/src
Cloud Shell 편집기에서 마크다운 미리보기를 사용하여 결과를 검토합니다.
새 파일을 만들고 Gemini의 대답을 붙여넣습니다.
그런 다음 명령어 팔레트를 사용하고 'Markdown: Open Preview
'를 선택합니다.
14. devai cli 명령어 살펴보기
코드 검토 명령어
devai review code -c ~/github/genai-for-developers/sample-app/src/main/java
실적 검토 명령어
devai review performance -c ~/github/genai-for-developers/sample-app/src/main/java
보안 검토 명령어
devai review security -c ~/github/genai-for-developers/sample-app/src/main/java
테스트 적용 범위 검토 명령어
devai review testcoverage -c ~/github/genai-for-developers/sample-app/src
차단자 검토 명령어
devai review blockers -c ~/github/genai-for-developers/sample-app/pom.xml
devai review blockers -c ~/github/genai-for-developers/sample-app/setup.md
이미지/다이어그램 검토 및 요약:
입력 다이어그램[~/github/genai-for-developers/images/extension-diagram.png
]:
명령어 검토:
devai review image \
-f ~/github/genai-for-developers/images/extension-diagram.png \
-p "Review and summarize this diagram"
출력:
The diagram outlines a process for conducting local code reviews using a VS Code extension or CLI, leveraging Google Cloud's Vertex AI (Gemini Pro) for generating review prompts. **Process Flow:** 1. **Code Style Check:** Developers initiate the process by checking their code for adherence to pre-defined style guidelines. 2. **Prompt Generation:** The VS Code extension/CLI sends the code to Vertex AI (Gemini Pro) on Google Cloud. 3. **Vertex AI Review:** Vertex AI analyzes the code and generates relevant review prompts. 4. **Local Review:** The prompts are sent back to the developer's IDE for their consideration. 5. **Optional Actions:** Developers can optionally: - Create new JIRA issues directly from the IDE based on the review prompts. - Generate new issues in a GitLab repository. **Key Components:** * **VS Code Extension/CLI:** Tools facilitating the interaction with Vertex AI and potential integrations with JIRA and GitLab. * **Vertex AI (Gemini Pro):** Google Cloud's generative AI service responsible for understanding the code and generating meaningful review prompts. * **Google Cloud Secret Manager:** Securely stores API keys and access tokens required to authenticate and interact with Google Cloud services. * **JIRA/GitLab (Optional):** Issue tracking and project management tools that can be integrated for a streamlined workflow. **Benefits:** * **Automated Review Assistance:** Leveraging AI to generate review prompts saves time and improves the consistency and quality of code reviews. * **Local Development:** The process empowers developers to conduct reviews locally within their familiar IDE. * **Integration Options:** The flexibility to integrate with project management tools like JIRA and GitLab streamlines workflow and issue tracking.
이미지 차이 분석:
devai review imgdiff \
-c ~/github/genai-for-developers/images/devai-api.png \
-t ~/github/genai-for-developers/images/devai-api-slack.png
출력:
The following UI elements are missing in the "AFTER UPGRADE STATE" image compared to the "BEFORE UPGRADE STATE" image: 1. **Slack:** The entire Slack element, including the icon, "Team channel" label, and the arrow indicating interaction, is absent in the AFTER UPGRADE image. 2. **Storage Bucket:** The "Storage Bucket" element with its icon and "PDFs" label is missing in the AFTER UPGRADE image. 3. **"GenAI Agents" label in Vertex AI block:** The BEFORE UPGRADE image has "Vertex AI Agents" and "GenAI Agent" labels within the Vertex AI block, while the AFTER UPGRADE image only has "Vertex AI." 4. **"Open JIRA Issue" and "Team Project" labels:** In the BEFORE UPGRADE image, these labels are connected to the JIRA block with an arrow. These are missing in the AFTER UPGRADE image. **Decision Explanation:** The analysis is based on a direct visual comparison of the two provided images, noting the presence and absence of specific UI elements and their associated labels. The elements listed above are present in the BEFORE UPGRADE image but absent in the AFTER UPGRADE image.
문서 생성 명령어:
devai document readme -c ~/github/genai-for-developers/sample-app/src/main/
출력:
# Bank of Anthos - Balance Reader Service ## Table of Contents - [Description](#description) - [Features](#features) - [Technologies Used](#technologies-used) - [Installation](#installation) - [Configuration](#configuration) - [Usage](#usage) - [Health Checks](#health-checks) - [Metrics and Tracing](#metrics-and-tracing) - [Contributing](#contributing) - [License](#license) ## Description The Balance Reader service is a component of the Bank of Anthos sample application. It provides a REST endpoint for retrieving the current balance of a user account. This service demonstrates key concepts for building microservices with Spring Boot and deploying them to a Kubernetes cluster. ## Features - Securely retrieves account balances using JWT authentication. - Leverages a local cache for fast balance retrieval. - Asynchronously processes transactions from a central ledger. - Provides health check endpoints for Kubernetes liveness and readiness probes. - Exposes metrics to Stackdriver for monitoring and observability. - Supports distributed tracing with Zipkin. ## Technologies Used - Java - Spring Boot - Spring Data JPA - Hibernate - Google Cloud SQL (PostgreSQL) - JWT (JSON Web Token) - Guava Cache - Micrometer - Stackdriver - Zipkin ## Installation 1. **Prerequisites:** - Java 17 or later - Maven 3.5 or later - Docker (for containerization) - Kubernetes cluster (for deployment) - Google Cloud account (for Stackdriver and other GCP services)
Cloud Shell 편집기에서 사용 가능한 devai cli 명령어를 검토합니다.
cloudshell edit ~/github/genai-for-developers/devai-cli/README.md
또는 GitHub 저장소에서 README.md를 검토하세요.
15. 파일에서 모든 환경 변수 추적
만들려는 모든 환경 변수 (예: API 키, API 토큰 등)를 추적할 새 파일을 시작합니다.
실습을 진행하면서 여러 시스템에 여러 번 사용할 것이므로 한곳에서 참조하는 것이 더 쉽습니다.
16. LangSmith LLM 추적 구성
LangSmith 계정을 만들고 설정 섹션에서 서비스 API 키를 생성합니다. https://docs.smith.langchain.com/
LangSmith 통합에 필요한 환경 변수를 설정합니다. 명령어를 실행하기 전에 서비스 API 키를 바꿉니다.
export LANGCHAIN_API_KEY=langsmith-service-api-key
export LANGCHAIN_TRACING_V2=true
export LANGCHAIN_ENDPOINT="https://api.smith.langchain.com"
터미널에 민감한 정보가 노출되지 않도록 하려면 read -s
를 사용하는 것이 좋습니다. read -s
는 콘솔의 명령어 기록에 값이 표시되지 않고 환경 변수를 설정할 수 있는 안전한 방법입니다. 실행한 후 값을 붙여넣고 Enter 키를 눌러야 합니다.
17. JIRA 명령어 구성
프로젝트의 JIRA API 토큰을 만듭니다. https://id.atlassian.com/manage-profile/security/api-tokens
JIRA 통합에 필요한 환경 변수를 설정합니다 (명령어를 실행하기 전에 값을 바꿉니다).
export JIRA_API_TOKEN=your-token-value
export JIRA_USERNAME="email that you used to register with JIRA"
export JIRA_INSTANCE_URL="https://YOUR-PROJECT.atlassian.net"
export JIRA_PROJECT_KEY="JIRA project key"
export JIRA_CLOUD=true
review.py
파일을 엽니다.
cloudshell edit ~/github/genai-for-developers/devai-cli/src/devai/commands/review.py
review.py
파일을 검토합니다.
source=source.format(format_files_as_string(context)) code_chat_model = GenerativeModel(model_name) code_chat = code_chat_model.start_chat() code_chat.send_message(qry) response = code_chat.send_message(source) ... else: click.echo(response.text)
다음 줄 아래의 줄을 찾아 주석 처리를 삭제합니다.
# Uncomment after configuring JIRA and GitLab env variables - see README.md for details
파일 상단에 JIRA 명령어 가져오기
# from devai.commands.jira import create_jira_issue
code
메서드에서 JIRA 문제를 만드는 메서드
#create_jira_issue("Code Review Results", response.text)
코드 검토 명령어를 다시 실행하고 상담사의 출력을 확인합니다.
export PROJECT_ID=$(gcloud config get-value project)
export LOCATION=us-central1
devai review code -c ~/github/genai-for-developers/sample-app/src/main/java/anthos/samples/bankofanthos/balancereader
샘플 출력:
(venv) student_00_19a997c157f8@cloudshell:~/genai-for-developers/devai-cli (qwiklabs-gcp-02-71a9948ae110)$ devai review code -c ../sample-app/src/main/java/anthos/samples/bankofanthos/balancereader /home/student_00_19a997c157f8/genai-for-developers/devai-cli/venv/lib/python3.9/site-packages/langchain_core/_api/deprecation.py:117: LangChainDeprecationWarning: The function `initialize_agent` was deprecated in LangChain 0.1.0 and will be removed in 0.2.0. Use new agent constructor methods like create_react_agent, create_json_agent, create_structured_chat_agent, etc. instead. warn_deprecated( Response from Model: ```java // Class: TransactionRepository // Method: findBalance // Efficiency - Consider using a native SQL query to improve performance for complex database operations. - Use prepared statements to avoid SQL injection vulnerabilities. // Best Practices - Return a Optional<Long> instead of null to handle the case when no balance is found for the given account.
/home/student_00_19a997c157f8/genai-for-developers/devai-cli/venv/lib/python3.9/site-packages/langchain_core/_api/deprecation.py:117: LangChainDeprecationWarning: __call__
함수는 LangChain 0.1.0에서 지원 중단되었으며 0.2.0에서 삭제됩니다. 대신 invoke를 사용하세요. warn_deprecated(
새 AgentExecutor 체인 진입... 생각: 설명이 질문에 제공되어 생각할 것이 없음. 조치:
{
"action": "create_issue",
"action_input": {
"description": "Class: TransactionRepository\nMethod: findBalance\n\nEfficiency\n- Consider using a native SQL query to improve performance for complex database operations.\n- Use prepared statements to avoid SQL injection vulnerabilities.\n\nBest Practices\n- Return a Optional<Long> instead of null to handle the case when no balance is found for the given account."
}
}
키가 CYMEATS-117인 새 문제가 생성됨
관찰: 키: CYMEATS-117로 새 문제가 생성됨 생각:최종 답변: CYMEATS-117
체인이 완료되었습니다.
Open your JIRA project in the browser and review the created issue.
Sample JIRA issue view.
<img src="img/9a93a958c30f0b51.png" alt="9a93a958c30f0b51.png" width="624.00" />
Open [LangSmith portal](https://smith.langchain.com/) and review LLM trace for JIRA issue creation call.
Sample LangSmith LLM trace.
<img src="img/6222ee1653a5ea54.png" alt="6222ee1653a5ea54.png" width="624.00" />
## Import GitHub repo to GitLab repo
Go to [https://gitlab.com/projects/new](https://gitlab.com/projects/new) and select "`Import project`" / "`Repository by URL`" option:
Git repository url:
https://github.com/GoogleCloudPlatform/genai-for-developers.git
Or
Your personal GitHub project that you created earlier in this lab.
Under Project URL - select your GitLab userid
Set Visibility to `Public`.
Click - "`Create Project`" to start the import process.
If you see an error about invalid GitHub Repository URL, [create a new GitHub token](https://github.com/settings/tokens)(fine-grained) with Public repositories read-only access, and retry import again providing your GitHub userid and token.
## Clone GitLab repo and setup SSH key
Return to Google Cloud Shell terminal and set up a new SSH key.
Update your email before running the commands. Hit enter multiple times to accept defaults.
ssh-keygen -t ed25519 -C "your-email-address"
eval "$(ssh-agent -s)" ssh-add ~/.ssh/id_ed25519
cat ~/.ssh/id_ed25519.pub
Add a public key to your GitLab account.
Open [https://gitlab.com/-/profile/keys](https://gitlab.com/-/profile/keys) and click "Add new key".
For the key value copy/paste the output of the last command.
Go back to the terminal and clone the repository.
cd ~ mkdir gitlab cd gitlab
Replace with your GitLab userid and repository url that was just created.
```console
git clone git@gitlab.com:YOUR_GITLAB_USERID/genai-for-developers.git
디렉터리를 변경하고 .gitlab-ci.yml
파일을 엽니다.
cd genai-for-developers
cloudshell edit .gitlab-ci.yml
이전에 사용 설정하지 않았다면 Cloud Shell 편집기에서 Gemini
를 사용 설정합니다.
.gitlab-ci.yml
파일의 아무 곳이나 마우스 오른쪽 버튼으로 클릭하고 'Gemini Code Assist > Explain
this"
를 선택합니다.
18. GitLab 명령어 구성
GitLab을 열고 이전 단계에서 만든 GitLab 저장소의 'Settings / Access Tokens
' 아래에 프로젝트 액세스 토큰을 만듭니다.
다음 단계에서 사용할 액세스 토큰 값을 복사하여 저장합니다.
다음 세부정보를 사용하세요.
- 토큰 이름:
devai-cli-qwiklabs
- 역할:
Maintainer
- 범위:
api
GitLab 통합에 필요한 환경 변수를 설정합니다.
이 명령어를 사용하려면 GitLab 액세스 토큰을 업데이트해야 합니다.
export GITLAB_PERSONAL_ACCESS_TOKEN=gitlab-access-token
이 명령어를 사용하려면 GitLab 사용자 ID와 저장소 이름을 업데이트해야 합니다.
export GITLAB_REPOSITORY="USERID/REPOSITORY"
나머지 환경 변수를 설정합니다.
export GITLAB_URL="https://gitlab.com"
export GITLAB_BRANCH="devai"
export GITLAB_BASE_BRANCH="main"
GitLab 웹사이트를 열고 프로젝트에서 'CICD AI Insights
'라는 제목으로 새 GitLab 문제를 만듭니다.
다른 방법으로는 아래의 curl 명령어를 사용하는 것입니다. GitLab 프로젝트 ID가 필요합니다. 'Settings
/ General
' 섹션에서 확인할 수 있습니다.
export GITLAB_PROJECT_ID=56390153 # replace
curl --request POST \
--header "PRIVATE-TOKEN: $GITLAB_PERSONAL_ACCESS_TOKEN" \
--header "Content-Type: application/json" \
--data '{"title":"CICD AI Insights"}' \
https://gitlab.com/api/v4/projects/$GITLAB_PROJECT_ID/issues
Cloud Shell로 돌아가서 review.py
파일을 엽니다.
cloudshell edit ~/gitlab/genai-for-developers/devai-cli/src/devai/commands/review.py
아래 코드를 찾아 주석 처리를 해제합니다.
GitLab 명령어 가져오기 라인
# from devai.commands.gitlab import create_gitlab_issue_comment
GitLab 문제에 댓글을 달 수 있는 방법
# create_gitlab_issue_comment(response.text)
19. DevAI CLI 개발
GitLab 저장소/디렉터리로 전환했기 때문입니다. 아래의 설정 단계를 다시 실행해야 합니다.
터미널에서 python virtualenv를 설정하고 요구사항을 설치한 후 샘플 명령어를 실행합니다.
export PROJECT_ID=$(gcloud config get-value project)
export LOCATION=us-central1
cd ~/gitlab/genai-for-developers/devai-cli
python3 -m venv venv
. venv/bin/activate
pip3 install -r src/requirements.txt
pip3 install --editable ./src
devai echo
cli의 위치를 확인할 수 있습니다. 이번에는 GitLab 폴더 아래에 있어야 합니다.
which devai
터미널에서 코드 검토 명령어를 다시 실행합니다.
devai review code -c ~/gitlab/genai-for-developers/sample-app/src/main/java/anthos/samples/bankofanthos/balancereader
샘플 출력 - 일부 섹션이 축약됨
(venv) student_00_19a997c157f8@cloudshell:~/genai-for-developers/devai-cli (qwiklabs-gcp-02-71a9948ae110)$ devai review code -c ../sample-app/src/main/java/anthos/samples/bankofanthos/balancereader . . Response from Model: **Class: Transaction** **Method: toString** **Maintainability:** * The formatting of the string representation could be more clear and concise. Consider using a dedicated method for formatting the amount, e.g., `formatAmount()`. . . > Entering new AgentExecutor chain... Thought: I need to first get the issue ID using the Get Issues tool, then I can comment on the issue using the Comment on Issue tool. Action: Get Issues Action Input: Observation: Found 1 issues: [{'title': 'CICD AI Insights', 'number': 1}] Thought:Thought: I found the issue ID, so now I can add the comment to the issue. Action: Comment on Issue Action Input: 1 Action: Get Issue Action Input: 1 Observation: {"title": "CICD AI Insights", "body": "", "comments": "[{'body': '**Transaction.java**\\n\\n\\n**Class:** Transaction\\n\\n\\n* **Security:** Consider using a custom date format like \\\\\"yyyy-MM-dd HH:mm:ss.SSS\\\\\" to handle timestamps more robustly.\\n\\n\\n**JWTVerifierGenerator.java**\\n\\n\\n* . . Thought:Now I can use the Comment on Issue tool to add the comment to the issue. Action: Comment on Issue Action Input: 1 **Class: Transaction** **Method: toString** **Maintainability:** . . . Observation: Commented on issue 1 Thought:I have now completed the necessary actions and added the comment to the issue 'CICD AI Insights'. Final Answer: Comment added to issue 'CICD AI Insights' > Finished chain.
GitLab 웹사이트를 열고 업데이트된 문제를 검토합니다.
LangSmith에서 LLM 트레이스를 검토합니다.
샘플 LLM 트레이스
20. GitLab 저장소에 변경사항 푸시
Google Cloud Shell 편집기로 돌아갑니다.
'Source Control
' 탭으로 전환합니다.
review.py
파일을 업데이트하려면 변경사항을 스테이징, 커밋, 푸시합니다.
21. GitLab CICD 구성
다음으로 변경사항이 저장소에 푸시될 때 코드 검토를 실행하도록 GitLab CICD 파이프라인을 사용 설정합니다.
GitLab 웹사이트를 열고 'Settings / CICD"
섹션으로 이동합니다.
Variables
섹션을 펼치고 'Add variable
'를 클릭합니다.
변수를 추가할 때는 모든 체크박스를 선택 해제해야 합니다. 예:
모든 환경 변수를 보관하는 메모를 사용하여 JIRA, GitLab, LangSmith의 환경 변수를 추가합니다.
PROJECT_ID=qwiklabs-project-id LOCATION=us-central1 GOOGLE_CLOUD_CREDENTIALS - cat ~/vertex-client-key.json LANGCHAIN_TRACING_V2=true LANGCHAIN_ENDPOINT="https://api.smith.langchain.com" LANGCHAIN_API_KEY=your-service-api-key JIRA_API_TOKEN=your-token JIRA_USERNAME="email that you used to register with JIRA" JIRA_INSTANCE_URL="https://YOUR-PROJECT.atlassian.net" JIRA_PROJECT_KEY="JIRA project key" JIRA_CLOUD=true GITLAB_PERSONAL_ACCESS_TOKEN=your-gitlab-token GITLAB_URL="https://gitlab.com" GITLAB_REPOSITORY="USERID/REPOSITORY" GITLAB_BRANCH="devai" GITLAB_BASE_BRANCH="main"
GOOGLE_CLOUD_CREDENTIALS
변수 값에는 위 섹션에서 만든 서비스 계정 키를 사용합니다.
cat ~/vertex-client-key.json
CI/CD 변수 보기:
23. GitLab 파이프라인 출력 검토
GitLab UI에서 'Build / Jobs
'를 열고 파이프라인 출력을 검토합니다.
GitLab 웹사이트를 열고 'CICD Insights
' 문제에 관한 업데이트된 댓글을 검토합니다.
GitLab 워크플로 실행 사용 중지
Google Cloud Shell 편집기로 돌아갑니다. 코드 푸시 이벤트에서 GitLab 워크플로 실행을 사용 중지하려면 줄의 주석 처리를 삭제합니다. UI에서 주문형으로 워크플로를 실행할 수는 있습니다.
# workflow: # rules: # - if: $CI_PIPELINE_SOURCE == "web"
프로젝트 루트에서 .gitlab-ci.yml
을 열고 다음 줄의 주석 처리를 삭제합니다.
cloudshell edit ~/gitlab/genai-for-developers/.gitlab-ci.yml
'Source Control
' 탭으로 전환하여 이 변경사항을 스테이징, 커밋, 푸시합니다.
24. CircleCI 통합
CircleCI란 무엇인가요?
CircleCI는 팀이 소프트웨어 개발 및 배포 프로세스를 자동화할 수 있는 클라우드 기반 CI/CD 플랫폼입니다. GitHub, Bitbucket, GitLab과 같은 버전 관리 시스템과 통합되므로 팀에서 자동화된 테스트 및 빌드를 실행하여 실시간으로 코드 변경사항을 검증할 수 있습니다. 지속적 배포의 경우 CircleCI는 AWS, Google Cloud, Azure와 같은 다양한 클라우드 환경에 소프트웨어를 배포하는 작업을 자동화할 수 있습니다.
설정
CircleCI 웹사이트를 열고 새 프로젝트를 만듭니다. 저장소에 'GitLab
' / 'Cloud
'을 선택합니다.
CircleCI에 GitLab 계정에 대한 액세스 권한을 부여합니다.
'가장 빠름' 옵션에서 main
브랜치를 선택합니다. CircleCI에서 기존 구성 파일을 감지하여 이 단계를 건너뛸 수 있습니다.
프로젝트가 생성되면 'Project Settings
' / 'Environment Variables
' 섹션을 클릭합니다.
지금까지 사용한 모든 환경 변수를 추가합니다.
다음은 추가할 환경 변수의 샘플 목록입니다.
PROJECT_ID=qwiklabs-project-id LOCATION=us-central1 GOOGLE_CLOUD_CREDENTIALS - cat ~/vertex-client-key.json LANGCHAIN_TRACING_V2=true LANGCHAIN_ENDPOINT="https://api.smith.langchain.com" LANGCHAIN_API_KEY=your-service-api-key JIRA_API_TOKEN=your-token JIRA_USERNAME="email that you used to register with JIRA" JIRA_INSTANCE_URL="https://YOUR-PROJECT.atlassian.net" JIRA_PROJECT_KEY="JIRA project key" JIRA_CLOUD=true GITLAB_PERSONAL_ACCESS_TOKEN=your-gitlab-token GITLAB_URL="https://gitlab.com" GITLAB_REPOSITORY="USERID/REPOSITORY" GITLAB_BRANCH="devai" GITLAB_BASE_BRANCH="main"
25. JIRA 및 GitLab 메서드 사용 설정
Google Cloud Shell 편집기를 열고 review.py
파일을 변경합니다.
아래에서 줄을 찾아 주석 처리를 삭제합니다.
# from devai.commands.jira import create_jira_issue
create_jira_issue("Performance Review Results", response.text) create_gitlab_issue_comment(response.text) . . . create_jira_issue("Security Review Results", response.text) create_gitlab_issue_comment(response.text)
'Source Control
' 탭으로 전환하여 이 변경사항을 스테이징, 커밋, 푸시합니다.
GitLab 웹사이트를 열고 'Build
' / 'Pipelines
'로 이동합니다.
CircleCI 링크를 따라 워크플로를 검토합니다.
저장소의 GitLab 문제에 관한 댓글을 검토합니다.
JIRA 프로젝트에서 생성된 새 문제를 검토합니다.
26. 축하합니다.
축하합니다. 실습을 완료했습니다.
학습한 내용
- GitHub, GitLab, CircleCI에 GenAI 코드 검토 자동화 단계를 추가했습니다.
- LangChain ReAct 에이전트: GitLab 문제에 댓글을 달고 JIRA 티켓을 여는 등의 작업을 자동화합니다.
다음 단계:
- 더 많은 실습 세션이 제공될 예정입니다.
삭제
이 튜토리얼에서 사용된 리소스 비용이 Google Cloud 계정에 청구되지 않도록 하려면 리소스가 포함된 프로젝트를 삭제하거나 프로젝트를 유지하고 개별 리소스를 삭제하세요.
프로젝트 삭제
비용이 청구되지 않도록 하는 가장 쉬운 방법은 튜토리얼에서 만든 프로젝트를 삭제하는 것입니다.
©2024 Google LLC All rights reserved. Google 및 Google 로고는 Google LLC의 상표입니다. 기타 모든 회사명 및 제품명은 해당 업체의 상표일 수 있습니다.