빠른 시작: 에이전트 개발 키트 (ADK)를 사용하여 AI 에이전트를 빌드하고 Cloud Run에 배포

Python용 에이전트 개발 키트 (ADK)를 사용하여 단일 명령어로 AI 에이전트를 빌드하고 Cloud Run에 배포하는 방법을 알아봅니다. 배포한 에이전트는 지정한 도시의 일기 예보를 가져옵니다.

이 빠른 시작의 단계를 따르면 소스 코드에서 배포할 때 Cloud Run에서 Dockerfile을 자동으로 빌드합니다.

Python 빌드팩이 Cloud Run 소스 배포의 기본 진입점을 결정하는 방법에 대한 자세한 내용은 Python 애플리케이션 빌드를 참고하세요.

시작하기 전에

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. Install the Google Cloud CLI.

  3. 외부 ID 공급업체(IdP)를 사용하는 경우 먼저 제휴 ID로 gcloud CLI에 로그인해야 합니다.

  4. gcloud CLI를 초기화하려면, 다음 명령어를 실행합니다.

    gcloud init
  5. Create or select a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.
    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  6. 이 가이드에 기존 프로젝트를 사용하는 경우 이 가이드를 완료하는 데 필요한 권한이 있는지 확인합니다. 새 프로젝트를 만든 경우에는 이미 필요한 권한이 있습니다.

  7. Verify that billing is enabled for your Google Cloud project.

  8. Install the Google Cloud CLI.

  9. 외부 ID 공급업체(IdP)를 사용하는 경우 먼저 제휴 ID로 gcloud CLI에 로그인해야 합니다.

  10. gcloud CLI를 초기화하려면, 다음 명령어를 실행합니다.

    gcloud init
  11. Create or select a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.
    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  12. 이 가이드에 기존 프로젝트를 사용하는 경우 이 가이드를 완료하는 데 필요한 권한이 있는지 확인합니다. 새 프로젝트를 만든 경우에는 이미 필요한 권한이 있습니다.

  13. Verify that billing is enabled for your Google Cloud project.

  14. Enable the Cloud Run Admin API, Vertex AI API, and Cloud Build APIs:

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    gcloud services enable run.googleapis.com aiplatform.googleapis.com cloudbuild.googleapis.com
  15. 에이전트 개발 키트 문서의 안내에 따라 ADK를 설치합니다.
  16. 프로젝트에서 인증되지 않은 호출을 제한하는 도메인 제한 조직 정책이 적용되는 경우 비공개 서비스 테스트의 설명대로 배포된 서비스에 액세스해야 합니다.

  17. Cloud Run 가격 책정을 검토하거나 가격 계산기로 비용을 추정합니다.
  18. 필요한 역할

    이 빠른 시작을 완료하는 데 필요한 권한을 얻으려면 관리자에게 다음의 IAM 역할을 부여해 달라고 요청하세요.

    역할 부여에 대한 자세한 내용은 프로젝트, 폴더, 조직에 대한 액세스 관리를 참조하세요.

    커스텀 역할이나 다른 사전 정의된 역할을 통해 필요한 권한을 얻을 수도 있습니다.

    Cloud Build 서비스 계정에 프로젝트에 대한 액세스 권한 부여

    이 동작을 재정의하지 않는 한 Cloud Build는 자동으로 Compute Engine 기본 서비스 계정을 기본 Cloud Build 서비스 계정으로 사용하여 소스 코드와 Cloud Run 리소스를 빌드합니다.

    Cloud Build에서 소스를 빌드할 수 있게 하려면 Cloud Build 서비스 계정에 프로젝트에 대한 Cloud Run 빌더(roles/run.builder) 역할을 부여하세요.

    gcloud projects add-iam-policy-binding PROJECT_ID \
        --member=serviceAccount:SERVICE_ACCOUNT_EMAIL_ADDRESS \
        --role=roles/run.builder

    PROJECT_ID를 Google Cloud프로젝트 ID로 바꾸고 SERVICE_ACCOUNT_EMAIL_ADDRESS를 Cloud Build 서비스 계정의 이메일 주소로 바꿉니다. Compute Engine 기본 서비스 계정을 Cloud Build 서비스 계정으로 사용하는 경우 서비스 계정 이메일 주소에 다음 형식을 사용합니다.

    PROJECT_NUMBER-compute@developer.gserviceaccount.com

    여기에서 PROJECT_NUMBER를 Google Cloud프로젝트 번호로 바꿉니다.

    프로젝트 ID와 프로젝트 번호를 찾는 방법에 대한 자세한 내용은 프로젝트 만들기 및 관리를 참조하세요.

    Cloud Run 빌더 역할을 부여하면 전파되는 데 몇 분 정도 걸립니다.

    샘플 애플리케이션 작성

    Python으로 애플리케이션을 작성하려면 다음을 수행합니다.

    1. parent_folder라는 새 상위 디렉터리를 만들고 디렉터리를 다음으로 변경합니다.

      mkdir parent_folder
      cd parent_folder
      
    2. parent_folder 디렉터리에서 multi_tool_agent라는 새 하위 디렉터리를 만들고 디렉터리를 다음으로 변경합니다.

      mkdir multi_tool_agent
      cd multi_tool_agent
      
    3. 에이전트를 가져올 __init__.py 파일을 만듭니다.

      from . import agent
      
    4. 지정된 도시의 시간과 날씨에 관한 질문에 답변하는 에이전트를 정의하는 agent.py 파일을 만듭니다.

      import datetime
      from zoneinfo import ZoneInfo
      from google.adk.agents import Agent
      
      def get_weather(city: str) -> dict:
          """Retrieves the current weather report for a specified city.
      
          Args:
              city (str): The name of the city for which to retrieve the weather report.
      
          Returns:
              dict: status and result or error msg.
          """
          if city.lower() == "new york":
              return {
                  "status": "success",
                  "report": (
                      "The weather in New York is sunny with a temperature of 25 degrees"
                      " Celsius (77 degrees Fahrenheit)."
                  ),
              }
          else:
              return {
                  "status": "error",
                  "error_message": f"Weather information for '{city}' is not available.",
              }
      
      def get_current_time(city: str) -> dict:
          """Returns the current time in a specified city.
      
          Args:
              city (str): The name of the city for which to retrieve the current time.
      
          Returns:
              dict: status and result or error msg.
          """
      
          if city.lower() == "new york":
              tz_identifier = "America/New_York"
          else:
              return {
                  "status": "error",
                  "error_message": (
                      f"Sorry, I don't have timezone information for {city}."
                  ),
              }
      
          tz = ZoneInfo(tz_identifier)
          now = datetime.datetime.now(tz)
          report = (
              f'The current time in {city} is {now.strftime("%Y-%m-%d %H:%M:%S %Z%z")}'
          )
          return {"status": "success", "report": report}
      
      root_agent = Agent(
          name="weather_time_agent",
          model="gemini-2.0-flash",
          description=(
              "Agent to answer questions about the time and weather in a city."
          ),
          instruction=(
              "You are a helpful agent who can answer user questions about the time and weather in a city."
          ),
          tools=[get_weather, get_current_time],
      )
      
    5. .env 파일을 만들고 다음 변수를 추가합니다.

      GOOGLE_GENAI_USE_VERTEXAI=TRUE
      GOOGLE_CLOUD_PROJECT=PROJECT_ID
      GOOGLE_CLOUD_LOCATION=REGION
      

      다음을 바꿉니다.

      • PROJECT_ID: Google Cloud 프로젝트 ID
      • REGION: 서비스를 배포할 리전입니다.
    6. 상위 폴더 디렉터리 parent_folder로 이동하고 google-adk 종속 항목을 추가할 requirements.txt 파일을 만듭니다.

      google-adk
      

      소스 프로젝트에는 다음 구조가 포함됩니다.

      parent_folder/
      ├── requirements.txt
      └── multi_tool_agent/
          ├── __init__.py
          ├── agent.py
          └── .env
      

    앱이 완료되어 배포할 준비가 되었습니다.

    소스에서 Cloud Run에 배포

    소스에서 배포는 소스 코드에서 컨테이너 이미지를 자동으로 빌드하고 이를 배포합니다.

    1. 소스 코드 디렉터리 (parent_folder)에서 다음 명령어를 사용하여 Cloud Run에 배포합니다.

      gcloud beta run deploy --source .
      1. 서비스 이름을 입력하라는 메시지가 표시되면 Enter 키를 눌러 기본 이름(예: weather-agent)을 수락합니다.

      2. 프로젝트에서 추가 API(예: Artifact Registry API)를 사용 설정하라는 메시지가 표시되면 y를 눌러 응답합니다.

      3. 리전을 입력하라는 메시지가 표시되면 리전(예: europe-west1)을 선택합니다.

      4. 지정된 리전에 저장소를 만들라는 메시지가 표시되면 y를 눌러 응답합니다.

      5. 공개 액세스를 허용하라는 메시지가 표시되면 y로 응답합니다. 이를 방지하는 도메인 제한 조직 정책이 있는 경우 이 메시지가 표시되지 않을 수 있습니다. 자세한 내용은 시작하기 전에 섹션을 참조하세요.

      그런 다음 배포가 완료될 때까지 잠시 기다립니다. 성공하면 명령줄에 서비스 URL이 표시됩니다. 서비스 URL에서 /list-apps로 이동합니다. 예를 들면 https://weather-agent-123456789101.us-central1.run.app/list-apps입니다.

    에이전트 실행

    ADK 에이전트를 쿼리하려면 다음 curl 명령어를 실행하세요.

    1. 앱 목록을 가져오려면 다음 명령어를 실행합니다.

      curl -X GET SERVICE_URL/list-apps
      

      SERVICE_URL을 배포된 서비스의 URL로 바꿉니다.

    2. 세션을 시작하려면 다음 명령어를 실행합니다.

      curl -X POST SERVICE_URL/apps/multi_tool_agent/users/u_123/sessions/s_123 -H "Content-Type: application/json" -d '{"key1": "value1", "key2": 42}'
      
    3. 에이전트를 쿼리하려면 다음 명령어를 실행합니다.

      curl -X POST SERVICE_URL/run \
      -H "Content-Type: application/json" \
      -d "{\"appName\": \"multi_tool_agent\",\"userId\": \"u_123\",\"sessionId\": \"s_123\",\"newMessage\": { \"role\": \"user\", \"parts\": [{ \"text\": \"What's the weather in New York today?\" }]}}"
      

    에이전트가 쿼리 결과에 날씨 정보를 반환합니다.

    지원되는 curl 명령어에 관한 자세한 내용과 예시는 ADK 문서의 API 서버 사용을 참고하세요.

    삭제

    Google Cloud 계정에 추가 비용이 청구되지 않게 하려면 이 빠른 시작으로 배포한 모든 리소스를 삭제합니다.

    저장소 삭제

    배포된 서비스를 사용하지 않으면 Cloud Run에서 요금을 청구하지 않습니다. 하지만 Artifact Registry에 컨테이너 이미지를 저장하는 요금이 부과될 수 있습니다. Artifact Registry 저장소를 삭제하려면 Artifact Registry 문서의 저장소 삭제 단계를 따르세요.

    서비스 삭제

    Cloud Run 서비스는 요청을 수신할 때까지 비용을 청구하지 않습니다. Cloud Run 서비스를 삭제하려면 다음 단계 중 하나를 수행합니다.

    콘솔

    서비스를 삭제하려면 다음 안내를 따르세요.

    1. Google Cloud 콘솔에서 Cloud Run 서비스 페이지로 이동합니다.

      Cloud Run으로 이동

    2. 서비스 목록에서 삭제할 서비스를 찾은 다음 체크박스를 클릭하여 선택합니다.

    3. 삭제를 클릭합니다. 이렇게 하면 서비스의 모든 버전이 삭제됩니다.

    gcloud

    서비스를 삭제하려면 다음 명령어를 실행합니다.

    gcloud run services delete SERVICE --region REGION

    다음을 바꿉니다.

    • SERVICE: 서비스 이름
    • REGION: 서비스의 Google Cloud 리전

    테스트 프로젝트 삭제

    Google Cloud 프로젝트를 삭제하면 해당 프로젝트의 모든 리소스에 대한 비용 청구가 중단됩니다. 프로젝트의 모든 Google Cloud 리소스를 해제하려면 다음 단계를 따르세요.

      Delete a Google Cloud project:

      gcloud projects delete PROJECT_ID

    다음 단계

    코드 소스에서 컨테이너를 빌드하고 저장소로 푸시하는 방법에 대한 자세한 내용은 다음을 참조하세요.