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

에이전트 개발 키트(ADK) 프레임워크는 AI 에이전트의 생성, 평가, 배포를 간소화합니다. ADK는 추론하고, 계획하고, 도구를 활용할 수 있는 에이전트를 빌드하기 위한 모듈식 코드 우선 접근 방식을 제공합니다.

이 튜토리얼에서는 Python용 ADK를 사용하여 AI 에이전트를 빌드하고 Cloud Run에 배포하는 방법을 보여줍니다. 이 에이전트는 사용자가 지정한 도시의 일기 예보를 가져옵니다.

Google Cloud CLI를 사용하여 ADK 에이전트를 호스팅하는 방법에 대한 자세한 내용은 ADK 문서의 Cloud Run에 배포를 참고하세요.

목표

비용

이 문서에서는 비용이 청구될 수 있는 Google Cloud구성요소를 사용합니다.

프로젝트 사용량을 기준으로 예상 비용을 산출하려면 가격 계산기를 사용합니다.

Google Cloud 신규 사용자는 무료 체험판을 사용할 수 있습니다.

시작하기 전에

  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. In the Google Cloud console, on the project selector page, select or create 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.

    Go to project selector

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

  4. In the Google Cloud console, on the project selector page, select or create 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.

    Go to project selector

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

  6. 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.

    Enable the APIs

  7. Google Cloud 프로젝트에서 Cloud Run 개발 환경을 설정합니다.
  8. 에이전트 개발 키트 문서의 안내에 따라 ADK를 설치합니다.
  9. 프로젝트에서 인증되지 않은 호출을 제한하는 도메인 제한 조직 정책이 적용되는 경우 비공개 서비스 테스트의 설명대로 배포된 서비스에 액세스해야 합니다.

  10. 필요한 역할

    AI 에이전트를 Cloud Run에 배포하는 데 필요한 권한을 얻으려면 관리자에게 다음 IAM 역할을 부여해 달라고 요청하세요.

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

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

샘플 애플리케이션 작성

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 계정에 추가 비용이 청구되지 않게 하려면 이 튜토리얼에서 배포한 모든 리소스를 삭제합니다.

프로젝트 삭제

이 튜토리얼용으로 새 프로젝트를 만든 경우 이 프로젝트를 삭제합니다. 기존 프로젝트를 사용했고 이 튜토리얼에 추가된 변경사항을 제외하고 보존하려면 튜토리얼을 위해 만든 리소스를 삭제합니다.

비용이 청구되지 않도록 하는 가장 쉬운 방법은 튜토리얼에서 만든 프로젝트를 삭제하는 것입니다.

프로젝트를 삭제하는 방법은 다음과 같습니다.

  1. In the Google Cloud console, go to the Manage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then click Delete.
  3. In the dialog, type the project ID, and then click Shut down to delete the project.

튜토리얼 리소스 삭제

  1. 이 튜토리얼에서 배포한 Cloud Run 서비스를 삭제합니다. Cloud Run 서비스는 요청을 수신할 때까지 비용을 청구하지 않습니다.

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

    gcloud run services delete SERVICE-NAME

    SERVICE-NAME를 서비스 이름으로 바꿉니다.

    Google Cloud 콘솔에서 Cloud Run 서비스를 삭제할 수도 있습니다.

  2. 튜토리얼 설정 중에 추가한 gcloud 기본 리전 구성을 삭제합니다.

     gcloud config unset run/region
    
  3. 프로젝트 구성을 삭제합니다.

     gcloud config unset project