本頁說明如何使用 Python SDK 向對話式數據分析 API 傳送要求。Python 程式碼範例示範如何完成下列工作:
- 驗證並設定環境
- 調整設定並初始化用戶端
- 連結至 Looker、BigQuery 或數據分析資料來源
- 設定有狀態或無狀態對話的脈絡
- 建立資料代理
- 建立對話
- 管理資料代理和對話
- 使用 API 提問
- 建立無狀態多輪對話
- 定義輔助函式
驗證及設定環境
如要使用 Conversational Analytics API 的 Python SDK,請按照 Conversational Analytics API SDK Colaboratory 筆記本中的操作說明下載及安裝 SDK。請注意,下載方法和 SDK Colab 的內容可能會有變動。
在筆記本中完成設定操作說明後,您可以使用下列程式碼匯入必要的 SDK 程式庫,並在 Colaboratory 環境中驗證 Google 帳戶:
from google.colab import auth
auth.authenticate_user()
from google.cloud import geminidataanalytics
from google.api_core import client_options
調整設定並初始化用戶端
下列 Python 程式碼範例定義了帳單專案、位置和系統指令,這些指令會在整個指令碼中使用,並根據位置初始化 API 用戶端和端點設定:
# Billing project
billing_project = "my_project_name"
location = "LOCATION"
# System instructions
system_instruction = "Help the user analyze their data."
# Set client options based on location.
if not location or location == "global":
endpoint = "geminidataanalytics.googleapis.com"
elif "-" in location:
# Regional endpoints
endpoint = f"geminidataanalytics-{location}.googleapis.com"
else:
# Multi-regional endpoints
endpoint = f"geminidataanalytics.{location}.rep.googleapis.com"
opts = client_options.ClientOptions(api_endpoint=endpoint)
data_agent_client = geminidataanalytics.DataAgentServiceClient(client_options=opts)
data_chat_client = geminidataanalytics.DataChatServiceClient(client_options=opts)
請按照下列方式替換範例值:
- my_project_name: Google Cloud 專案的 ID,您已在該專案啟用必要的 API。
LOCATION:資源的儲存位置。如要使用全域端點,請指定
global。為符合資料落地規定,請指定支援的單一區域 (例如us-east4) 或多區域 (例如eu或us)。詳情請參閱「資料落地」。Help the user analyze their data.:系統指示,用於引導代理行為,並根據資料需求自訂。舉例來說,您可以使用系統指令定義業務術語、控制回覆長度或設定資料格式。建議您按照「撰寫有效的系統指令」一文中的 YAML 格式定義系統指令,提供詳細且結構化的指引。
連結至資料來源
以下各節說明如何定義代理資料來源的連線詳細資料。代理可透過下列方式連結資料:
連結 Looker 資料
如要定義 Looker 探索和 Looker 憑證的連線,請參閱「連線至 Looker」。
連結 BigQuery 資料
以下各節說明如何使用資料表參照、圖表參照或兩者,連結至 BigQuery 資料。如要進一步瞭解如何連結資料表和圖表 (包括必要角色),請參閱「連結至 BigQuery」。
連結至 BigQuery 資料表
下列程式碼範例定義了多個 BigQuery 資料表的連線,並包含選用結構化背景資訊欄位的範例。
bigquery_table_reference_1 = geminidataanalytics.BigQueryTableReference()
bigquery_table_reference_1.project_id = "PROJECT_ID_1"
bigquery_table_reference_1.dataset_id = "DATASET_ID_1"
bigquery_table_reference_1.table_id = "TABLE_ID_1"
bigquery_table_reference_1.schema = geminidataanalytics.Schema()
bigquery_table_reference_1.schema.description = "TABLE_DESCRIPTION"
bigquery_table_reference_1.schema.fields = [
geminidataanalytics.Field(
name="COLUMN_NAME",
description="COLUMN_DESCRIPTION"
)
]
bigquery_table_reference_2 = geminidataanalytics.BigQueryTableReference()
bigquery_table_reference_2.project_id = "PROJECT_ID_2"
bigquery_table_reference_2.dataset_id = "DATASET_ID_2"
bigquery_table_reference_2.table_id = "TABLE_ID_2"
bigquery_table_reference_3 = geminidataanalytics.BigQueryTableReference()
bigquery_table_reference_3.project_id = "PROJECT_ID_3"
bigquery_table_reference_3.dataset_id = "DATASET_ID_3"
bigquery_table_reference_3.table_id = "TABLE_ID_3"
# Connect to your data source
datasource_references = geminidataanalytics.DatasourceReferences()
datasource_references.bq.table_references = [bigquery_table_reference_1, bigquery_table_reference_2, bigquery_table_reference_3]
請按照下列方式替換範例值:
- PROJECT_ID_1: Google Cloud 專案的 ID,其中包含您要連結的 BigQuery 資料集和資料表。如要連結公開資料集,請指定
bigquery-public-data。 - DATASET_ID_1:BigQuery 資料集的 ID。例如:
san_francisco。 - TABLE_ID_1:BigQuery 資料表的 ID。例如:
street_trees。 - TABLE_DESCRIPTION:資料表內容和用途的選用說明。
- COLUMN_NAME:資料表中資料欄的名稱,您可以選擇是否提供說明。
- COLUMN_DESCRIPTION:資料欄內容和用途的說明 (選填)。
連結至 BigQuery Graph
您也可以使用 BigQuery Graph 連結至圖表。在 property_graph_references 欄位中提供一或多個圖表參照。
如要瞭解 BigQuery 版本需求和圖表查詢限制,請參閱「連結至 BigQuery Graph」。
# BigQuery graph reference
graph_reference = geminidataanalytics.BigQueryPropertyGraphReference()
graph_reference.project_id = "GRAPH_PROJECT_ID"
graph_reference.dataset_id = "GRAPH_DATASET_ID"
graph_reference.property_graph_id = "GRAPH_ID"
# Connect to your data source
datasource_references = geminidataanalytics.DatasourceReferences()
datasource_references.bq.property_graph_references = [graph_reference]
請按照下列方式替換範例值:
- GRAPH_PROJECT_ID:含有 BigQuery 圖表的 Google Cloud 專案 ID。
- GRAPH_DATASET_ID:包含圖表的 BigQuery 資料集 ID。
- GRAPH_ID:BigQuery 圖表的 ID。
如要使用同一個資料代理查詢表格和圖表,請在 datasource_references.bq 上同時設定 table_references 和 property_graph_references。
連結至數據分析資料
下列程式碼範例定義了與數據分析資料來源的連線。
studio_datasource_id = "my_datasource_id"
studio_references = geminidataanalytics.StudioDatasourceReference()
studio_references.datasource_id = studio_datasource_id
## Connect to your data source
datasource_references.studio.studio_references = [studio_references]
在上述範例中,請將 my_datasource_id 替換為資料來源 ID。
連線至 AlloyDB 資料
下列程式碼範例使用 Python SDK 定義與 AlloyDB 資料庫的連線。
# Define the AlloyDB database reference
alloydb_database_reference = geminidataanalytics.AlloyDbDatabaseReference()
alloydb_database_reference.project_id = "PROJECT_ID"
alloydb_database_reference.region = "REGION"
alloydb_database_reference.cluster_id = "CLUSTER_ID"
alloydb_database_reference.instance_id = "INSTANCE_ID"
alloydb_database_reference.database_id = "DATABASE"
alloydb_database_reference.table_ids = ["TABLE_1_ID", "TABLE_2_ID"]
# Optional: Include this if you have created advanced context for the agent
agent_context_reference = geminidataanalytics.AgentContextReference()
agent_context_reference.context_set_id = f"projects/{billing_project}/locations/{location}/contextSets/your_context_set_id"
# Add the AlloyDB reference to the DatasourceReferences object
datasource_references = geminidataanalytics.DatasourceReferences()
datasource_references.alloydb.database_reference = alloydb_database_reference
# Optional:
# datasource_references.alloydb.agent_context_reference = agent_context_reference
請按照下列方式替換範例值:
- PROJECT_ID:AlloyDB 叢集所在 Google Cloud 專案的 ID。
- REGION:AlloyDB 叢集所在的區域,例如
us-central1。 - CLUSTER_ID:AlloyDB 叢集的 ID。
- INSTANCE_ID:AlloyDB 執行個體的 ID。
- DATABASE:目標資料庫的名稱,例如
financial。 - TABLE_1_ID、TABLE_2_ID:建議資料代理使用的資料庫資料表清單,例如
"loan"、"client"、"disp"。 - your_context_set_id::如果您為代理建立了進階情境,請提供情境集的 ID。
連線至 MySQL 適用的 Cloud SQL 資料
如要連線至 MySQL 適用的 Cloud SQL 執行個體,請使用 geminidataanalytics SDK 中的 CloudSqlReference 類別。這包括指定專案、執行個體、資料庫,以及代理應考量的特定資料表 (選用)。
連線至 MySQL 適用的 Cloud SQL 資料前,請務必使用 Identity and Access Management (IAM) 向 MySQL 適用的 Cloud SQL 進行驗證。詳情請參閱「向 MySQL 適用的 Cloud SQL 和 PostgreSQL 適用的 Cloud SQL 進行驗證」。
以下範例使用 Python SDK 定義 MySQL 適用的 Cloud SQL 資料庫連線。
# Import the necessary library
from google.cloud import geminidataanalytics
# Define the Cloud SQL database reference
cloud_sql_database_reference = geminidataanalytics.CloudSqlDatabaseReference(
project_id="PROJECT_ID",
instance_id="INSTANCE_ID",
database_id="DATABASE_ID",
# Optional: Specify table IDs to guide the agent
table_ids=["TABLE_1_ID", "TABLE_2_ID"]
)
# Create a CloudSqlReference object
cloud_sql_reference = geminidataanalytics.CloudSqlReference(
database_reference=cloud_sql_database_reference
# Optional: Include this if you have created advanced context for the agent
# agent_context_reference=geminidataanalytics.AgentContextReference(
# context_set_id=f"projects/{billing_project}/locations/{location}/contextSets/your_context_set_id"
# )
)
# Add the Cloud SQL reference to the DatasourceReferences object
datasource_references = geminidataanalytics.DatasourceReferences()
datasource_references.cloud_sql = cloud_sql_reference
請按照下列方式替換範例值:
- PROJECT_ID: Google Cloud 專案的 ID,該專案包含 MySQL 適用的 Cloud SQL 執行個體。
- INSTANCE_ID:MySQL 適用的 Cloud SQL 執行個體 ID。
- DATABASE_ID:執行個體中的目標資料庫名稱,例如
financial。 - TABLE_1_ID、TABLE_2_ID:(選用) 建議資料代理使用的資料庫特定資料表名稱清單,例如
"orders"和"customers"。 - your_context_set_id::如果您為代理建立了進階情境,請提供情境集的 ID。
建立資料代理或與其互動時,可以使用 datasource_references 物件。
連線至 PostgreSQL 適用的 Cloud SQL 資料
如要連線至 PostgreSQL 適用的 Cloud SQL 執行個體,請使用 geminidataanalytics SDK 中的 CloudSqlReference
類別。這包括指定專案、執行個體、資料庫,以及代理應考量的特定資料表 (選用)。
連線至 PostgreSQL 適用的 Cloud SQL 資料前,請務必使用 IAM 向 PostgreSQL 適用的 Cloud SQL 進行驗證。詳情請參閱「向 MySQL 適用的 Cloud SQL 和 PostgreSQL 適用的 Cloud SQL 進行驗證」。
以下範例使用 Python SDK 定義與 PostgreSQL 適用的 Cloud SQL 資料庫的連線。
# Import the necessary library
from google.cloud import geminidataanalytics
# Define the Cloud SQL database reference
cloud_sql_database_reference = geminidataanalytics.CloudSqlDatabaseReference(
project_id="PROJECT_ID",
instance_id="INSTANCE_ID",
database_id="DATABASE_ID",
# Optional: Specify table IDs to guide the agent
table_ids=["TABLE_1_ID", "TABLE_2_ID"]
)
# Create a CloudSqlReference object
cloud_sql_reference = geminidataanalytics.CloudSqlReference(
database_reference=cloud_sql_database_reference
# Optional: Include this if you have created advanced context for the agent
# agent_context_reference=geminidataanalytics.AgentContextReference(
# context_set_id=f"projects/{billing_project}/locations/{location}/contextSets/your_context_set_id"
# )
)
# Add the Cloud SQL reference to the DatasourceReferences object
datasource_references = geminidataanalytics.DatasourceReferences()
datasource_references.cloud_sql = cloud_sql_reference
請按照下列方式替換範例值:
- PROJECT_ID: Google Cloud 專案的 ID,該專案包含 PostgreSQL 適用的 Cloud SQL 執行個體。
- INSTANCE_ID:PostgreSQL 適用的 Cloud SQL 執行個體 ID。
- DATABASE_ID:執行個體中的目標資料庫名稱,例如
postgres。 - TABLE_1_ID、TABLE_2_ID:(選用) 建議資料代理使用的資料庫內特定資料表名稱清單,例如
"users"和"products"。 - your_context_set_id::如果您為代理建立了進階情境,請提供情境集的 ID。
建立資料代理或與其互動時,可以使用 datasource_references 物件。
連結至 Spanner 資料
如要連線至 Spanner 執行個體,請使用 geminidataanalytics SDK 的 SpannerReference 類別。這包括指定專案、執行個體、資料庫,以及代理應考量的特定資料表 (選用)。
連結至 Spanner 資料前,請確認使用者或服務帳戶具備 spanner.databaseReader IAM 角色。詳情請參閱「套用 IAM 角色」。
下列 Python 程式碼範例使用 Python SDK 定義 Spanner 資料庫連線。
# Import the necessary library
from google.cloud import geminidataanalytics
# Define the Spanner database reference
spanner_database_reference = geminidataanalytics.SpannerDatabaseReference(
project_id="PROJECT_ID",
instance_id="INSTANCE_ID",
database_id="DATABASE_ID",
# Optional: Specify table IDs to guide the agent
table_ids=["TABLE_1_ID", "TABLE_2_ID"]
)
# Create a SpannerReference object
spanner_reference = geminidataanalytics.SpannerReference(
database_reference=spanner_database_reference
# Optional: Include this if you have created advanced context for the agent
# agent_context_reference=geminidataanalytics.AgentContextReference(
# context_set_id=f"projects/{billing_project}/locations/{location}/contextSets/your_context_set_id"
# )
)
# Add the Spanner reference to the DatasourceReferences object
datasource_references = geminidataanalytics.DatasourceReferences()
datasource_references.spanner = spanner_reference
請按照下列方式替換範例值:
- PROJECT_ID:包含 Spanner 執行個體的 Google Cloud 專案 ID。
- INSTANCE_ID:Spanner 執行個體的 ID。
- DATABASE_ID::執行個體中的目標資料庫名稱。
- TABLE_1_ID、TABLE_2_ID:(選用) 建議資料代理使用的資料庫內特定資料表名稱清單,例如
"Singers"和"Albums"。 - your_context_set_id::如果您為代理建立了進階情境,請提供情境集的 ID。
建立資料代理或與其互動時,可以使用 datasource_references 物件。
設定有狀態或無狀態對話的背景資訊
對話式數據分析 API 支援多輪對話,使用者可根據先前的對話內容提出後續問題。下列 Python 程式碼範例示範如何為有狀態或無狀態對話設定情境:
- 有狀態的對話: Google Cloud 儲存及管理對話記錄。有狀態的對話本質上是多輪對話,因為 API 會保留先前訊息的脈絡。您只需要傳送每個回合的目前訊息。
- 無狀態對話:由應用程式管理對話記錄。每次傳送新訊息時,都必須附上完整的對話記錄。如需在無狀態模式下管理多輪對話的詳細範例,請參閱「建立無狀態多輪對話」。
有狀態的對話
下列程式碼範例會設定有狀態對話的背景資訊,其中 Google Cloud 會儲存及管理對話記錄。您也可以在下列程式碼範例中加入 published_context.options.analysis.python.enabled = True 這一行,啟用 Python 進階分析功能。
# Set up context for stateful chat
published_context = geminidataanalytics.Context()
published_context.system_instruction = system_instruction
published_context.datasource_references = datasource_references
# Optional: To enable advanced analysis with Python, include the following line:
published_context.options.analysis.python.enabled = True
# Optional: To limit query costs to 100 MiB, include the following line:
published_context.options.datasource.big_query_max_billed_bytes.value = 104857600
無狀態對話
下列程式碼範例會設定無狀態對話的背景資訊,您必須在每則訊息中傳送完整的對話記錄。您也可以在下列程式碼範例中加入 inline_context.options.analysis.python.enabled = True 這一行,啟用 Python 進階分析功能。
# Set up context for stateless chat
inline_context = geminidataanalytics.Context()
inline_context.system_instruction = system_instruction
inline_context.datasource_references = datasource_references
# Optional: To enable advanced analysis with Python, include the following line:
inline_context.options.analysis.python.enabled = True
# Optional: To limit query costs to 100 MiB, include the following line:
inline_context.options.datasource.big_query_max_billed_bytes = 104857600
建立資料代理
下列 Python 程式碼範例會發出 API 要求,建立資料代理,以便您與資料對話。您可以同步或非同步建立代理。資料代理已設定指定的資料來源、系統指令和情境。
建立資料代理時,您可以視需要設定 kms_key 欄位,使用 CMEK 保護資料代理。詳情請參閱「客戶自行管理的加密金鑰 (CMEK)」。
同步
data_agent_id = "data_agent_1"
# Optional: If using CMEK, replace the empty strings with your KMS key details.
key_ring = "" # KEY_RING_NAME
key_name = "" # KEY_NAME
key_project = "" # KMS_PROJECT_ID (Defaults to billing_project if empty)
key_location = "" # KEY_LOCATION (Defaults to location if empty; except eu)
data_agent = geminidataanalytics.DataAgent()
data_agent.data_analytics_agent.published_context = published_context
data_agent.name = f"projects/{billing_project}/locations/{location}/dataAgents/{data_agent_id}" # Optional
# Optional: Add CMEK key if details are provided
if key_ring and key_name:
if not key_project:
key_project = billing_project
if not key_location:
key_location = location
kms_key_data_agent = f"projects/{key_project}/locations/{key_location}/keyRings/{key_ring}/cryptoKeys/{key_name}"
data_agent.kms_key = kms_key_data_agent # Add for CMEK
request = geminidataanalytics.CreateDataAgentRequest(
parent=f"projects/{billing_project}/locations/{location}",
data_agent_id=data_agent_id, # Optional
data_agent=data_agent,
)
try:
response = data_agent_client.create_data_agent_sync(request=request)
print("Data Agent created")
print(response)
except Exception as e:
print(f"Error creating Data Agent: {e}")
非同步
data_agent_id = "data_agent_1"
# Optional: If using CMEK, replace the empty strings with your KMS key details.
key_ring = "" # KEY_RING_NAME
key_name = "" # KEY_NAME
key_project = "" # KMS_PROJECT_ID (Defaults to billing_project if empty)
key_location = "" # KEY_LOCATION (Defaults to location if empty; except eu)
data_agent = geminidataanalytics.DataAgent()
data_agent.data_analytics_agent.published_context = published_context
data_agent.name = f"projects/{billing_project}/locations/{location}/dataAgents/{data_agent_id}" # Optional
# Optional: Add CMEK key if details are provided
if key_ring and key_name:
if not key_project:
key_project = billing_project
if not key_location:
key_location = location
kms_key_data_agent = f"projects/{key_project}/locations/{key_location}/keyRings/{key_ring}/cryptoKeys/{key_name}"
data_agent.kms_key = kms_key_data_agent # Add for CMEK
request = geminidataanalytics.CreateDataAgentRequest(
parent=f"projects/{billing_project}/locations/{location}",
data_agent_id=data_agent_id, # Optional
data_agent=data_agent,
)
try:
data_agent_client.create_data_agent(request=request)
print("Data Agent created")
except Exception as e:
print(f"Error creating Data Agent: {e}")
在上述範例中,請替換下列值:
- data_agent_1:資料代理的專屬 ID。
- KEY_RING_NAME:如果使用 CMEK,請提供 Cloud KMS 金鑰環的名稱。
- KEY_NAME:如果使用 CMEK,則為 Cloud KMS 金鑰名稱。
- KMS_PROJECT_ID:如果使用 CMEK,則為金鑰託管位置的專案 ID。
- KEY_LOCATION:如果使用 CMEK,則為金鑰環的位置。如果是
eu多區域,請使用europe。如果是其他位置,請使用與資料代理程式相同的位置。如未提供,則預設為資料代理程式的位置,適用於eu多區域以外的所有位置。詳情請參閱「金鑰地點規定」。
建立對話
下列 Python 程式碼範例會發出 API 要求來建立對話。
建立對話時,您可以視需要設定 kms_key 欄位,使用 CMEK 保護對話。詳情請參閱「客戶自行管理的加密金鑰 (CMEK)」。
# Initialize request arguments
data_agent_id = "data_agent_1"
conversation_id = "conversation_1"
# Optional: If using CMEK, replace the empty strings with your KMS key details.
key_ring = "" # KEY_RING_NAME
key_name = "" # KEY_NAME
key_project = "" # KMS_PROJECT_ID (Defaults to billing_project if empty)
key_location = "" # KEY_LOCATION (Defaults to location if empty; single regions only)
conversation = geminidataanalytics.Conversation()
conversation.agents = [f'projects/{billing_project}/locations/{location}/dataAgents/{data_agent_id}']
conversation.name = f"projects/{billing_project}/locations/{location}/conversations/{conversation_id}"
# Optional: Add CMEK key if details are provided
if key_ring and key_name:
if not key_project:
key_project = billing_project
if not key_location:
key_location = location
kms_key_conversation = f"projects/{key_project}/locations/{key_location}/keyRings/{key_ring}/cryptoKeys/{key_name}"
conversation.kms_key = kms_key_conversation # Add for CMEK
request = geminidataanalytics.CreateConversationRequest(
parent=f"projects/{billing_project}/locations/{location}",
conversation_id=conversation_id,
conversation=conversation,
)
# Make the request
response = data_chat_client.create_conversation(request=request)
# Handle the response
print(response)
請按照下列方式替換範例值:
- data_agent_1:資料代理的 ID,如「建立資料代理」中的程式碼範例區塊所示。
- conversation_1:對話的專屬 ID。
- KEY_RING_NAME:如果使用 CMEK,請提供 Cloud KMS 金鑰環的名稱。
- KEY_NAME:如果使用 CMEK,則為 Cloud KMS 金鑰名稱。
- KMS_PROJECT_ID:如果使用 CMEK,則為金鑰託管位置的專案 ID。
- KEY_LOCATION:如果使用 CMEK,則為金鑰環的位置。如果是
us多區域,請使用us-central1。如果是eu多區域,請使用europe-west1。如果選取單一區域,請使用與對話相同的區域。如未提供,系統會預設為對話的位置,這項設定僅適用於單一區域。詳情請參閱「金鑰地點規定」。
管理資料代理和對話
下列程式碼範例說明如何使用 Conversational Analytics API 管理資料代理和對話。您可以執行下列工作:
取得資料代理
下列 Python 程式碼範例示範如何發出 API 要求,擷取先前建立的資料代理。
# Initialize request arguments
data_agent_id = "data_agent_1"
request = geminidataanalytics.GetDataAgentRequest(
name=f"projects/{billing_project}/locations/{location}/dataAgents/{data_agent_id}",
)
# Make the request
response = data_agent_client.get_data_agent(request=request)
# Handle the response
print(response)
在上例中,將 data_agent_1 值替換為要擷取的資料代理程式專屬 ID。
列出資料代理
下列程式碼示範如何呼叫 list_data_agents 方法,列出特定專案的所有資料代理。如要列出所有代理,您必須具備專案的 geminidataanalytics.dataAgents.list 權限。如要進一步瞭解哪些 IAM 角色包含這項權限,請參閱預先定義的角色清單。
billing_project = "YOUR-BILLING-PROJECT"
location = "global"
request = geminidataanalytics.ListDataAgentsRequest(
parent=f"projects/{billing_project}/locations/{location}",
)
# Make the request
page_result = data_agent_client.list_data_agents(request=request)
# Handle the response
for response in page_result:
print(response)
將 YOUR-BILLING-PROJECT 替換為計費專案 ID。
列出可存取的資料代理
下列程式碼示範如何呼叫 list_accessible_data_agents 方法,列出特定專案中所有可存取的資料代理。
billing_project = "YOUR-BILLING-PROJECT"
creator_filter = "YOUR-CREATOR-FILTER"
location = "global"
request = geminidataanalytics.ListAccessibleDataAgentsRequest(
parent=f"projects/{billing_project}/locations/{location}",
creator_filter=creator_filter
)
# Make the request
page_result = data_agent_client.list_accessible_data_agents(request=request)
# Handle the response
for response in page_result:
print(response)
請按照下列方式替換範例值:
- YOUR-BILLING-PROJECT:計費專案的 ID。
- YOUR-CREATOR-FILTER:根據資料代理建立者套用的篩選器。可能的值包括
NONE(預設)、CREATOR_ONLY和NOT_CREATOR_ONLY。
更新資料代理
下列程式碼範例示範如何對資料代理程式資源呼叫 update_data_agent_sync 或 update_data_agent 方法,以同步或非同步方式更新資料代理程式。要求需要 DataAgent 物件,其中包含要變更欄位的新值,以及採用 FieldMask 物件的 update_mask 參數,用於指定要更新的欄位。
如要更新資料代理,您必須具備該代理的 geminidataanalytics.dataAgents.update IAM 權限。如要進一步瞭解哪些 IAM 角色包含這項權限,請參閱預先定義的角色清單。
同步
data_agent_id = "data_agent_1"
billing_project = "YOUR-BILLING-PROJECT"
data_agent = geminidataanalytics.DataAgent()
data_agent.data_analytics_agent.published_context = published_context
data_agent.name = f"projects/{billing_project}/locations/{location}/dataAgents/{data_agent_id}"
data_agent.description = "Updated description of the data agent."
update_mask = field_mask_pb2.FieldMask(paths=['description', 'data_analytics_agent.published_context'])
request = geminidataanalytics.UpdateDataAgentRequest(
data_agent=data_agent,
update_mask=update_mask,
)
try:
# Make the request
response = data_agent_client.update_data_agent_sync(request=request)
print("Data Agent Updated")
print(response)
except Exception as e:
print(f"Error updating Data Agent: {e}")
非同步
data_agent_id = "data_agent_1"
billing_project = "YOUR-BILLING-PROJECT"
data_agent = geminidataanalytics.DataAgent()
data_agent.data_analytics_agent.published_context = published_context
data_agent.name = f"projects/{billing_project}/locations/{location}/dataAgents/{data_agent_id}"
data_agent.description = "Updated description of the data agent."
update_mask = field_mask_pb2.FieldMask(paths=['description', 'data_analytics_agent.published_context'])
request = geminidataanalytics.UpdateDataAgentRequest(
data_agent=data_agent,
update_mask=update_mask,
)
try:
# Make the request
data_agent_client.update_data_agent(request=request)
print("Data Agent Updated")
except Exception as e:
print(f"Error updating Data Agent: {e}")
請按照下列方式替換範例值:
- data_agent_1:要更新的資料代理程式 ID。
- YOUR-BILLING-PROJECT:計費專案的 ID。
- Updated description of the data agent.:更新後的資料代理說明。
取得資料代理的 IAM 政策
下列程式碼範例示範如何使用 get_iam_policy 方法,擷取資料代理的 IAM 政策。要求會指定資料代理資源路徑。
billing_project = "YOUR-BILLING-PROJECT"
location = "global"
data_agent_id = "data_agent_1"
resource = f"projects/{billing_project}/locations/{location}/dataAgents/{data_agent_id}"
request = iam_policy_pb2.GetIamPolicyRequest(
resource=resource,
)
try:
response = data_agent_client.get_iam_policy(request=request)
print("IAM Policy fetched successfully!")
print(f"Response: {response}")
except Exception as e:
print(f"Error setting IAM policy: {e}")
請按照下列方式替換範例值:
- YOUR-BILLING-PROJECT:計費專案的 ID。
- data_agent_1:要取得 IAM 政策的資料代理 ID。
設定資料代理的 IAM 政策
如要共用代理,您可以使用 set_iam_policy 方法,將特定代理的 IAM 角色指派給使用者。要求中包含繫結,指定應將哪些角色指派給哪些使用者。
billing_project = "YOUR-BILLING-PROJECT"
location = "global"
data_agent_id = "data_agent_1"
role = "roles/geminidataanalytics.dataAgentEditor"
users = "EMAIL_ADDRESS"
resource = f"projects/{billing_project}/locations/{location}/dataAgents/{data_agent_id}"
# Construct the IAM policy
binding = policy_pb2.Binding(
role=role,
members= [f"user:{i.strip()}" for i in users.split(",")]
)
policy = policy_pb2.Policy(bindings=[binding])
# Create the request
request = iam_policy_pb2.SetIamPolicyRequest(
resource=resource,
policy=policy
)
# Send the request
try:
response = data_agent_client.set_iam_policy(request=request)
print("IAM Policy set successfully!")
print(f"Response: {response}")
except Exception as e:
print(f"Error setting IAM policy: {e}")
請按照下列方式替換範例值:
- YOUR-BILLING-PROJECT:計費專案的 ID。
- data_agent_1:要設定 IAM 政策的資料代理 ID。
- EMAIL_ADDRESSES:以半形逗號分隔的使用者電子郵件清單,您要將指定角色授予這些使用者。
刪除資料代理
下列程式碼範例示範如何使用 delete_data_agent_sync 或 delete_data_agent 方法,以同步或非同步方式刪除資料代理。刪除資料代理後,會進入 30 天的虛刪除期,期間無法復原。詳情請參閱「資料保留和刪除」。要求會指定資料代理程式資源網址。
同步
billing_project = "YOUR-BILLING-PROJECT"
location = "global"
data_agent_id = "data_agent_1"
request = geminidataanalytics.DeleteDataAgentRequest(
name=f"projects/{billing_project}/locations/{location}/dataAgents/{data_agent_id}",
)
try:
# Make the request
data_agent_client.delete_data_agent_sync(request=request)
print("Data Agent Deleted")
except Exception as e:
print(f"Error deleting Data Agent: {e}")
非同步
billing_project = "YOUR-BILLING-PROJECT"
location = "global"
data_agent_id = "data_agent_1"
request = geminidataanalytics.DeleteDataAgentRequest(
name=f"projects/{billing_project}/locations/{location}/dataAgents/{data_agent_id}",
)
try:
# Make the request
data_agent_client.delete_data_agent(request=request)
print("Data Agent Deleted")
except Exception as e:
print(f"Error deleting Data Agent: {e}")
請按照下列方式替換範例值:
- YOUR-BILLING-PROJECT:計費專案的 ID。
- data_agent_1:要刪除的資料代理 ID。
取得對話
下列程式碼範例示範如何使用 get_conversation 方法擷取現有對話的資訊。要求會指定對話資源路徑。
billing_project = "YOUR-BILLING-PROJECT"
location = "global"
conversation_id = "conversation_1"
request = geminidataanalytics.GetConversationRequest(
name = f"projects/{billing_project}/locations/{location}/conversations/{conversation_id}"
)
# Make the request
response = data_chat_client.get_conversation(request=request)
# Handle the response
print(response)
請按照下列方式替換範例值:
- YOUR-BILLING-PROJECT:計費專案的 ID。
- conversation_1:要擷取的對話 ID。
列出對話
下列程式碼範例示範如何呼叫 list_conversations 方法,列出特定專案的對話。要求會指定父項資源網址,也就是專案和位置 (例如 projects/my-project/locations/global)。
根據預設,這個方法會傳回您建立的對話。管理員使用者 (具備 cloudaicompanion.topicAdmin IAM 角色的使用者) 可以查看專案中的所有對話。
billing_project = "YOUR-BILLING-PROJECT"
location = "global"
request = geminidataanalytics.ListConversationsRequest(
parent=f"projects/{billing_project}/locations/{location}",
)
# Make the request
response = data_chat_client.list_conversations(request=request)
# Handle the response
print(response)
將 YOUR-BILLING-PROJECT 替換為已啟用必要 API 的計費專案 ID。
列出對話中的訊息
以下程式碼範例示範如何使用 list_messages 方法擷取對話中的所有訊息。要求會指定對話資源路徑。
如要列出訊息,您必須具備對話的 cloudaicompanion.topics.get 權限。
billing_project = "YOUR-BILLING-PROJECT"
location = "global"
conversation_id = "conversation_1"
request = geminidataanalytics.ListMessagesRequest(
parent=f"projects/{billing_project}/locations/{location}/conversations/{conversation_id}",
)
# Make the request
response = data_chat_client.list_messages(request=request)
# Handle the response
print(response)
請按照下列方式替換範例值:
- YOUR-BILLING-PROJECT:計費專案的 ID。
- conversation_1:要列出訊息的對話 ID。
刪除對話
下列程式碼範例示範如何刪除對話。管理員 (具備 cloudaicompanion.topicAdmin Identity and Access Management 角色的使用者) 或具備 cloudaicompanion.topics.delete Identity and Access Management 權限的使用者,可以刪除專案中的對話。
billing_project = "YOUR-BILLING-PROJECT"
location = "global"
conversation_id = "conversation_1"
request = geminidataanalytics.DeleteConversationRequest(
name = f"projects/{billing_project}/locations/{location}/conversations/{conversation_id}"
)
# Make the request
response = data_chat_client.delete_conversation(request=request)
# Handle the response
print(response)
請按照下列方式替換範例值:
- YOUR-BILLING-PROJECT:計費專案的 ID。
- conversation_1:要列出訊息的對話 ID。
使用 API 提問
建立資料代理後,如果是可記錄狀態的對話,請建立對話,然後向代理傳送查詢。下列程式碼範例說明如何呼叫 data_chat_client.chat 方法。這些範例會使用您在「設定有狀態或無狀態對話的情境」中設定的情境變數 (例如資料來源和系統指令)。
傳送查詢時,API 會傳回 Message 物件串流。這個串流可以包含不同類型的訊息,包括文字、資料表和圖表。文字訊息可提供代理的推論過程、報告進度,或提供最終答案。每則簡訊的用途會以 TextType 值表示:
THOUGHT:顯示代理在規劃如何回答查詢時的內部思考過程。THOUGHT訊息會逐步說明代理的推論和決策過程,並包含兩個部分:parts[0]是思考摘要,簡要總結完整的思考文字;parts[1]則是完整的思考文字。PROGRESS:回報代理執行動作的進度,例如擷取資料或叫用工具。這個值只會針對 Looker 資料來源傳回,且包含兩個部分:parts[0]是摘要,parts[1]是完整的進度文字。FINAL_RESPONSE:提供查詢的最終答案。
下列程式碼範例使用 定義輔助函式中定義的 show_message 輔助函式,處理及顯示串流中的每則訊息。如要瞭解如何在使用 Looker 資料來源時,在使用者介面中顯示這些訊息,請參閱「顯示 Looker 資料來源的代理回覆」。
有狀態的對話
傳送有狀態的對話要求,並附上 Conversation 參考資料
您可以參照先前建立的 Conversation 資源,向資料代理傳送有狀態的對話要求。
# Create a request that contains a single user message (your question)
question = "Which species of tree is most prevalent?"
messages = [geminidataanalytics.Message()]
messages[0].user_message.text = question
data_agent_id = "data_agent_1"
conversation_id = "conversation_1"
# Create a conversation_reference
conversation_reference = geminidataanalytics.ConversationReference()
conversation_reference.conversation = f"projects/{billing_project}/locations/{location}/conversations/{conversation_id}"
conversation_reference.data_agent_context.data_agent = f"projects/{billing_project}/locations/{location}/dataAgents/{data_agent_id}"
# Form the request
request = geminidataanalytics.ChatRequest(
parent = f"projects/{billing_project}/locations/{location}",
# credentials = credentials,
messages = messages,
conversation_reference = conversation_reference
)
# Make the request
stream = data_chat_client.chat(request=request, timeout=300 #custom timeout up to 600s)
# Handle the response
for response in stream:
show_message(response)
請按照下列方式替換範例值:
無狀態對話
下列程式碼範例示範如何在設定無狀態對話的情境後,將查詢傳送至資料代理。如要傳送無狀態查詢,可以參照先前定義的 DataAgent 資源,或在要求中使用內嵌內容。
傳送含有 DataAgent 參照的無狀態對話要求
您可以參照先前建立的 DataAgent 資源,將查詢傳送至資料代理。
# Create a request that contains a single user message (your question)
question = "Which species of tree is most prevalent?"
messages = [geminidataanalytics.Message()]
messages[0].user_message.text = question
data_agent_id = "data_agent_1"
data_agent_context = geminidataanalytics.DataAgentContext()
data_agent_context.data_agent = f"projects/{billing_project}/locations/{location}/dataAgents/{data_agent_id}"
# Form the request
request = geminidataanalytics.ChatRequest(
parent=f"projects/{billing_project}/locations/{location}",
# credentials=credentials,
messages=messages,
data_agent_context = data_agent_context
)
# Make the request
stream = data_chat_client.chat(request=request, timeout=300 #custom timeout up to 600s)
# Handle the response
for response in stream:
show_message(response)
請按照下列方式替換範例值:
- Which species of tree is most prevalent?:要傳送給資料代理的自然語言問題。
- data_agent_1:資料代理的專屬 ID,如「建立資料代理」中所定義。
傳送無狀態對話要求,並提供內嵌背景資訊
下列程式碼範例示範如何使用 inline_context 參數,直接在無狀態對話要求中提供背景資訊。
# Create a request that contains a single user message (your question)
question = "Which species of tree is most prevalent?"
messages = [geminidataanalytics.Message()]
messages[0].user_message.text = question
request = geminidataanalytics.ChatRequest(
inline_context=inline_context,
parent=f"projects/{billing_project}/locations/{location}",
# credentials=credentials,
messages=messages,
)
# Make the request
stream = data_chat_client.chat(request=request, timeout=300 #custom timeout up to 600s)
# Handle the response
for response in stream:
show_message(response)
在上述範例中,將 Which species of tree is most prevalent? 替換為要傳送至資料代理的自然語言問題。
如要讓 API 從資料集或專案清單中選擇要查詢的 BigQuery 資料表,請參閱「連結至 BigQuery 資料集和專案」。
建立無狀態多輪對話
如要在無狀態對話中提出後續問題,應用程式必須在每次傳送新要求時,一併傳送完整的訊息記錄,藉此管理對話情境。以下範例說明如何建立多輪對話,方法是參照資料代理,或使用內嵌情境直接提供資料來源。
# List that is used to track previous turns and is reused across requests
conversation_messages = []
data_agent_id = "data_agent_1"
# Use data agent context
data_agent_context = geminidataanalytics.DataAgentContext()
data_agent_context.data_agent = f"projects/{billing_project}/locations/{location}/dataAgents/{data_agent_id}"
# Helper function for calling the API
def multi_turn_Conversation(msg):
message = geminidataanalytics.Message()
message.user_message.text = msg
# Send a multi-turn request by including previous turns and the new message
conversation_messages.append(message)
request = geminidataanalytics.ChatRequest(
parent=f"projects/{billing_project}/locations/{location}",
# credentials=credentials,
messages=conversation_messages,
# Use data agent context
data_agent_context=data_agent_context,
# Use inline context
# inline_context=inline_context,
)
# Make the request
stream = data_chat_client.chat(request=request, timeout=300 #custom timeout up to 600s)
# Handle the response
for response in stream:
show_message(response)
conversation_messages.append(response)
# Send the first turn request
multi_turn_Conversation("Which species of tree is most prevalent?")
# Send follow-up turn request
multi_turn_Conversation("Can you show me the results as a bar chart?")
在上述範例中,請按照下列方式替換範例值:
- data_agent_1:資料代理的專屬 ID,如「建立資料代理」中的程式碼範例區塊所示。
- Which species of tree is most prevalent?:要傳送給資料代理的自然語言問題。
- Can you show me the results as a bar chart?:根據前一個問題延伸或修正的後續問題。
定義輔助函式
下列程式碼範例包含先前程式碼範例中使用的輔助函式定義。這些函式有助於剖析 API 的回應並顯示結果。
import json as json_lib
import textwrap
import time
import altair as alt
import IPython
import pandas as pd
import proto
import requests
from google.protobuf.json_format import MessageToDict, MessageToJson
from IPython.display import display, HTML
from pygments import highlight, lexers, formatters
from google.protobuf import field_mask_pb2
from google.iam.v1 import policy_pb2
from google.iam.v1 import iam_policy_pb2
def handle_text_response(resp):
parts = resp.parts
full_text = "".join(parts)
if "\n" not in full_text and len(full_text) > 80:
wrapped_text = textwrap.fill(full_text, width=80)
print(wrapped_text)
else:
print(full_text)
def display_schema(data):
fields = getattr(data, "fields")
df = pd.DataFrame({
"Column": map(lambda field: getattr(field, 'name'), fields),
"Type": map(lambda field: getattr(field, 'type'), fields),
"Description": map(lambda field: getattr(field, 'description', '-'), fields),
"Mode": map(lambda field: getattr(field, 'mode'), fields)
})
display(df)
def display_section_title(text):
display(HTML('<h2>{}</h2>'.format(text)))
def format_looker_table_ref(table_ref):
return 'lookmlModel: {}, explore: {}, lookerInstanceUri: {}'.format(table_ref.lookml_model, table_ref.explore, table_ref.looker_instance_uri)
def format_bq_table_ref(table_ref):
return '{}.{}.{}'.format(table_ref.project_id, table_ref.dataset_id, table_ref.table_id)
def display_datasource(datasource):
source_name = ''
if 'studio_datasource_id' in datasource:
source_name = getattr(datasource, 'studio_datasource_id')
elif 'looker_explore_reference' in datasource:
source_name = format_looker_table_ref(getattr(datasource, 'looker_explore_reference'))
else:
source_name = format_bq_table_ref(getattr(datasource, 'bigquery_table_reference'))
print(source_name)
display_schema(datasource.schema)
def handle_schema_response(resp):
if 'query' in resp:
print(resp.query.question)
elif 'result' in resp:
display_section_title('Schema resolved')
print('Data sources:')
for datasource in resp.result.datasources:
display_datasource(datasource)
def handle_data_response(resp):
if "query" in resp:
query = resp.query
display_section_title("Retrieval query")
print(f"Query name: {query.name}")
if "question" in query:
print(f"Question: {query.question}")
if "datasources" in query:
print("Data sources:")
for datasource in query.datasources:
display_datasource(datasource)
elif "generated_sql" in resp:
display_section_title("SQL generated")
print(resp.generated_sql)
elif "result" in resp:
display_section_title("Data retrieved")
fields = [field.name for field in resp.result.schema.fields]
d = {}
for el in resp.result.data:
for field in fields:
if field in d:
d[field].append(el[field])
else:
d[field] = [el[field]]
display(pd.DataFrame(d))
def handle_chart_response(resp):
def _value_to_dict(v):
if isinstance(v, proto.marshal.collections.maps.MapComposite):
return _map_to_dict(v)
elif isinstance(v, proto.marshal.collections.RepeatedComposite):
return [_value_to_dict(el) for el in v]
elif isinstance(v, (int, float, str, bool)):
return v
else:
return MessageToDict(v)
def _map_to_dict(d):
out = {}
for k in d:
if isinstance(d[k], proto.marshal.collections.maps.MapComposite):
out[k] = _map_to_dict(d[k])
else:
out[k] = _value_to_dict(d[k])
return out
if 'query' in resp:
print(resp.query.instructions)
elif 'result' in resp:
vegaConfig = resp.result.vega_config
vegaConfig_dict = _map_to_dict(vegaConfig)
alt.Chart.from_json(json_lib.dumps(vegaConfig_dict)).display();
def show_message(msg):
m = msg.system_message
if 'text' in m:
handle_text_response(getattr(m, 'text'))
elif 'schema' in m:
handle_schema_response(getattr(m, 'schema'))
elif 'data' in m:
handle_data_response(getattr(m, 'data'))
elif 'chart' in m:
handle_chart_response(getattr(m, 'chart'))
print('\n')