將代理程式回覆內容以視覺化方式呈現

對話式數據分析 API 可根據使用者問題生成互動式圖表。API 會以 Vega-Lite JSON 設定或 SVG 圖片的形式傳回圖表 (適用於 Looker 資料來源,且僅限 v1alpha 和 v1beta API 版本)。您也可以指示代理依特定需求生成圖表。API 會根據使用者問題傳回的資料結果,建立圖表。

長條圖顯示加州 20 至 30 歲和 40 至 50 歲年齡層的褲子總售價和訂單數量。

面積圖顯示過去 12 個月的每月總銷售價格成效,最高為 $3,395.12 美元,平均為 $2,517.68 美元。

支援的圖表

API 會使用 Vega-Lite 建立圖表,並支援所有標準 Vega-Lite 功能。支援的圖表類型如下:

  • 區
  • 長條圖
  • Geoshape
  • 熱視圖
  • 折線圖 (時間序列)
  • 圓餅圖
  • 散布圖

圖表的生成方式

代理會找出相關資料結果,並傳送給子代理。這個子代理會執行 Python 程式碼,生成圖表的 Vega-Lite JSON 設定。API 會使用對話內容,在生成圖表時更準確地瞭解使用者意圖。API 可運用 Python 建立更複雜的圖表。

代理可能會執行小幅度的資料轉換,例如匯總或套用篩選器,讓圖表更相關且易於閱讀。

輸出格式

圖表會以 chart 結果訊息傳回,並可提供下列格式:

您可以使用內容中的 ChartOptions 欄位要求圖片。要求圖片時,API 會同時提供圖片和 Vega-Lite JSON 輸出內容。

以視覺化方式呈現代理回覆

本節說明如何使用 Python SDK,根據對話式數據分析 API 回應中的圖表規格,轉譯圖表。程式碼範例會從回覆的 chart 欄位擷取圖表規格 (Vega-Lite 格式),並使用 Altair 程式庫 (以 Vega-Lite 為基礎建構) 算繪圖表、將圖表儲存為圖片,然後顯示圖表。

如要進一步瞭解如何使用 Vega-Lite 和 Vega-Lite 生態系統轉譯圖表,請參閱「製作 Vega-Lite 視覺化圖表的工具」。

範例:根據 Vega-Lite 輸出內容算繪圖表

這個範例會使用內嵌內容連結至 bigquery-public-data.faa.us_airports 公開 BigQuery 資料表,並根據對話式數據分析 API 代理的回覆,顯示長條圖。範例會傳送含有下列提示詞的要求:

"Create a bar graph that shows the top five states by the total number of airports."

程式碼範例定義了下列輔助函式:

  • render_chart_response:從 chart 訊息中擷取 Vega-Lite 設定,轉換為 Altair 程式庫可用的格式,然後算繪圖表、儲存至 chart.png 並顯示。
  • chat:使用 inline_context 變數和目前的 messages 清單,將要求傳送至對話式數據分析 API、處理串流回應,並在回應包含圖表時呼叫 render_chart_response 顯示圖表。

如要使用下列程式碼範例,請替換下列項目:

  • BILLING_PROJECT:已啟用必要 API 的帳單專案 ID。
  • Create a bar graph that shows the top five states by the total number of airports:要傳送至對話式數據分析 API 的提示。
from google.cloud import geminidataanalytics
from google.protobuf.json_format import MessageToDict
import altair as alt
import proto

# Helper function for rendering chart response
def render_chart_response(resp):
  def _convert(v):
    if isinstance(v, proto.marshal.collections.maps.MapComposite):
      return {k: _convert(val) for k, val in v.items()}
    elif isinstance(v, proto.marshal.collections.RepeatedComposite):
      return [_convert(el) for el in v]
    elif isinstance(v, (int, float, str, bool, type(None))):
      return v
    else:
      return MessageToDict(v)

  try:
    vega_config = _convert(resp.result.vega_config)
    chart = alt.Chart.from_dict(vega_config)
    chart.save('chart.png')
    chart.display()
    print("Chart rendered and saved as chart.png")
  except Exception as e:
    print(f"Error rendering chart: {e}")

# Helper function for calling the API
def chat(q: str, inline_context, messages):
  billing_project = "BILLING_PROJECT"

  input_message = geminidataanalytics.Message(
      user_message=geminidataanalytics.UserMessage(text=q)
  )
  messages.append(input_message)

  client = geminidataanalytics.DataChatServiceClient()
  request = geminidataanalytics.ChatRequest(
      inline_context=inline_context,
      parent=f"projects/{billing_project}/locations/global",
      messages=messages,
  )

  # Make the request
  try:
    stream = client.chat(request=request)

    for reply in stream:
      if 'system_message' in reply:
        if 'chart' in reply.system_message:
          # ChartMessage includes `query` for generating a chart and `result` with the generated chart.
          if 'result' in reply.system_message.chart:
            print("Chart result found in response.")
            render_chart_response(reply.system_message.chart)
          else:
            print("Chart message found, but no result yet.")
        # Append system messages to maintain context for follow-up turns
        messages.append(reply)

  except Exception as e:
    print(f"Error calling API: {e}")

# Configure inline context with the public FAA airports table in BigQuery
table_reference = geminidataanalytics.BigQueryTableReference()
table_reference.project_id = "bigquery-public-data"
table_reference.dataset_id = "faa"
table_reference.table_id = "us_airports"

datasource_references = geminidataanalytics.DatasourceReferences()
datasource_references.bq.table_references = [table_reference]

inline_context = geminidataanalytics.Context()
inline_context.datasource_references = datasource_references
messages = []

# Send the prompt to make a bar graph
chat("Create a bar graph that shows the top five states by the total number of airports", inline_context, messages)