このページでは、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.")