이 페이지에서는 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.")