本页介绍了如何使用 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.")