ADK용 Google Cloud Pub/Sub 도구¶
Supported in ADKPython v1.22.0
PubSubToolset을 사용하면 에이전트가
Google Cloud Pub/Sub
서비스와 상호작용하여 메시지를 게시(publish), pull, acknowledge할 수 있습니다.
사전 준비 사항¶
PubSubToolset을 사용하기 전에 다음이 필요합니다:
- Google Cloud 프로젝트에서 Pub/Sub API를 활성화합니다.
- 인증 및 권한 부여: 에이전트를 실행하는 주체(예: 사용자, 서비스 계정)가 Pub/Sub 작업 수행에 필요한 IAM 권한을 가지고 있어야 합니다. Pub/Sub 역할에 대한 자세한 내용은 Pub/Sub 액세스 제어 문서를 참조하세요.
- 토픽 또는 구독 생성: 메시지 게시를 위한 토픽 생성과 메시지 수신을 위한 구독 생성이 필요합니다.
사용 방법¶
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import asyncio
import os
from google.adk.agents import Agent
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.adk.tools.pubsub.config import PubSubToolConfig
from google.adk.tools.pubsub.pubsub_credentials import PubSubCredentialsConfig
from google.adk.tools.pubsub.pubsub_toolset import PubSubToolset
from google.genai import types
import google.auth
# Define constants for this example agent
AGENT_NAME = "pubsub_agent"
APP_NAME = "pubsub_app"
USER_ID = "user1234"
SESSION_ID = "1234"
GEMINI_MODEL = "gemini-2.0-flash"
# Define Pub/Sub tool config.
# You can optionally set the project_id here, or let the agent infer it from context/user input.
tool_config = PubSubToolConfig(project_id=os.getenv("GOOGLE_CLOUD_PROJECT"))
# Uses externally-managed Application Default Credentials (ADC) by default.
# This decouples authentication from the agent / tool lifecycle.
# https://cloud.google.com/docs/authentication/provide-credentials-adc
application_default_credentials, _ = google.auth.default()
credentials_config = PubSubCredentialsConfig(
credentials=application_default_credentials
)
# Instantiate a Pub/Sub toolset
pubsub_toolset = PubSubToolset(
credentials_config=credentials_config, pubsub_tool_config=tool_config
)
# Agent Definition
pubsub_agent = Agent(
model=GEMINI_MODEL,
name=AGENT_NAME,
description=(
"Agent to publish, pull, and acknowledge messages from Google Cloud"
" Pub/Sub."
),
instruction="""\
You are a cloud engineer agent with access to Google Cloud Pub/Sub tools.
You can publish messages to topics, pull messages from subscriptions, and acknowledge messages.
""",
tools=[pubsub_toolset],
)
# Session and Runner
session_service = InMemorySessionService()
session = asyncio.run(
session_service.create_session(
app_name=APP_NAME, user_id=USER_ID, session_id=SESSION_ID
)
)
runner = Runner(
agent=pubsub_agent, app_name=APP_NAME, session_service=session_service
)
# Agent Interaction
def call_agent(query):
"""
Helper function to call the agent with a query.
"""
content = types.Content(role="user", parts=[types.Part(text=query)])
events = runner.run(user_id=USER_ID, session_id=SESSION_ID, new_message=content)
print("USER:", query)
for event in events:
if event.is_final_response():
final_response = event.content.parts[0].text
print("AGENT:", final_response)
call_agent("publish 'Hello World' to 'my-topic'")
call_agent("pull messages from 'my-subscription'")
도구¶
PubSubToolset에는 다음 도구가 포함됩니다:
publish_message¶
Pub/Sub 토픽에 메시지를 게시합니다.
| Parameter | Type | Description |
|---|---|---|
topic_name |
str |
Pub/Sub 토픽 이름(예: projects/my-project/topics/my-topic)입니다. |
message |
str |
게시할 메시지 내용입니다. |
attributes |
dict[str, str] |
(선택 사항) 메시지에 첨부할 속성입니다. |
ordering_key |
str |
(선택 사항) 메시지의 정렬 키입니다. 이 값을 설정하면 메시지가 순서대로 게시됩니다. |
pull_messages¶
Pub/Sub 구독에서 메시지를 pull합니다.
| Parameter | Type | Description |
|---|---|---|
subscription_name |
str |
Pub/Sub 구독 이름(예: projects/my-project/subscriptions/my-sub)입니다. |
max_messages |
int |
(선택 사항) pull할 최대 메시지 수입니다. 기본값은 1입니다. |
auto_ack |
bool |
(선택 사항) 메시지를 자동으로 acknowledge할지 여부입니다. 기본값은 False입니다. |
acknowledge_messages¶
Pub/Sub 구독의 하나 이상의 메시지를 acknowledge합니다.
| Parameter | Type | Description |
|---|---|---|
subscription_name |
str |
Pub/Sub 구독 이름(예: projects/my-project/subscriptions/my-sub)입니다. |
ack_ids |
list[str] |
acknowledge할 acknowledgment ID 목록입니다. |