將代理人回應轉譯為視覺化資訊

本頁面說明如何使用 Python SDK,從 Conversational Analytics API 回應中提供的圖表規格,算繪視覺化內容。範例程式碼會從回應的 chart 欄位中擷取圖表規格 (Vega-Lite 格式),並使用 Vega-Altair 程式庫算繪圖表、儲存為圖片,然後顯示該圖片。

範例:從 API 算繪長條圖

這個範例說明如何根據 Conversational Analytics API 代理程式的回應,算繪長條圖。這個範例會傳送含有下列提示的要求:

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

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

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

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

  • sqlgen-testing:已啟用必要 API 的帳單專案 ID。
  • Create a bar graph that shows the top five states by the total number of airports:要傳送至 Conversational Analytics 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(v) for k, v in v.items()}
    elif isinstance(v, proto.marshal.collections.RepeatedComposite):
      return [_convert(el) for el in v]
    elif isinstance(v, (int, float, str, bool)):
      return v
    else:
      return MessageToDict(v)

  vega_config = _convert(resp.result.vega_config)
  chart = alt.Chart.from_dict(vega_config)
  chart.save('chart.png')
  chart.display()

# Helper function for calling the API
def chat(q: str):
  billing_project = "sqlgen-testing"

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

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

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

  for reply in stream:
    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:
        render_chart_response(reply.system_message.chart)

# 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.")