Tetap teratur dengan koleksi
Simpan dan kategorikan konten berdasarkan preferensi Anda.
Halaman ini menunjukkan cara menggunakan Python SDK untuk merender visualisasi dari spesifikasi diagram yang disediakan dalam respons Conversational Analytics API. Kode contoh mengekstrak spesifikasi diagram (dalam format Vega-Lite) dari kolom chart respons dan menggunakan library Vega-Altair untuk merender diagram, menyimpannya sebagai gambar, dan menampilkannya.
Contoh: Merender diagram batang dari API
Contoh ini menunjukkan cara merender diagram batang dari respons agen Conversational Analytics API. Contoh ini mengirimkan permintaan dengan perintah berikut:
"Create a bar graph that shows the top five states by the total number of airports."
Kode contoh menentukan fungsi bantuan berikut:
render_chart_response: Mengekstrak konfigurasi Vega-Lite dari pesan chart, mengonversinya ke format yang dapat digunakan oleh library Vega-Altair, merender diagram, menyimpannya ke chart.png, dan menampilkannya.
chat: Mengirim permintaan ke Conversational Analytics API menggunakan variabel inline_context dan daftar messages saat ini, memproses respons streaming, dan jika diagram ditampilkan, memanggil render_chart_response untuk menampilkannya.
Untuk menggunakan contoh kode berikut, ganti kode berikut:
Create a bar graph that shows the top five states by the total number of airports: Perintah yang ingin Anda kirim ke Conversational Analytics API.
fromgoogle.cloudimportgeminidataanalyticsfromgoogle.protobuf.json_formatimportMessageToDictimportaltairasaltimportproto# Helper function for rendering chart responsedefrender_chart_response(resp):def_convert(v):ifisinstance(v,proto.marshal.collections.maps.MapComposite):return{k:_convert(v)fork,vinv.items()}elifisinstance(v,proto.marshal.collections.RepeatedComposite):return[_convert(el)forelinv]elifisinstance(v,(int,float,str,bool)):returnvelse:returnMessageToDict(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 APIdefchat(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 requeststream=client.chat(request=request)forreplyinstream:if"chart"inreply.system_message:# ChartMessage includes `query` for generating a chart and `result` with the generated chart.if"result"inreply.system_message.chart:render_chart_response(reply.system_message.chart)# Send the prompt to make a bar graphchat("Create a bar graph that shows the top five states by the total number of airports.")
[[["Mudah dipahami","easyToUnderstand","thumb-up"],["Memecahkan masalah saya","solvedMyProblem","thumb-up"],["Lainnya","otherUp","thumb-up"]],[["Sulit dipahami","hardToUnderstand","thumb-down"],["Informasi atau kode contoh salah","incorrectInformationOrSampleCode","thumb-down"],["Informasi/contoh yang saya butuhkan tidak ada","missingTheInformationSamplesINeed","thumb-down"],["Masalah terjemahan","translationIssue","thumb-down"],["Lainnya","otherDown","thumb-down"]],["Terakhir diperbarui pada 2025-09-04 UTC."],[],[],null,["# Render an agent response as a visualization\n\n| This product or feature is subject to the \"Pre-GA Offerings Terms\" in the General Service Terms section\n| of the [Service Specific Terms](/terms/service-terms#1).\n|\n| Pre-GA products and features are available \"as is\" and might have limited support.\n|\n| For more information, see the\n| [launch stage descriptions](/products#product-launch-stages).\n\nThis page shows how to use the Python SDK to render a visualization from the chart specifications that are provided within a [Conversational Analytics API](/gemini/docs/conversational-analytics-api/overview) response. The [sample code](#example-render-bar-chart) extracts the chart specification (in the [Vega-Lite format](https://vega.github.io/vega-lite/)) from the response's `chart` field and uses the [Vega-Altair](https://altair-viz.github.io/) library to render the chart, save it as an image, and display it.\n| **Note:** This guide assumes that you're working in an environment like Colaboratory. This guide also builds on the setup in [Build a data agent using the Python SDK](/gemini/docs/conversational-analytics-api/build-agent-sdk), which shows how to authenticate and initialize the required `client`, `inline_context`, and `messages` variables.\n\nExample: Render a bar chart from an API\n---------------------------------------\n\nThis example shows how to render a bar chart from a Conversational Analytics API agent response. The example sends a request with the following prompt: \n\n```\n\"Create a bar graph that shows the top five states by the total number of airports.\"\n```\n\nThe sample code defines the following helper functions:\n\n- `render_chart_response`: Extracts the Vega-Lite configuration from the `chart` message, converts it to a format that can be used by the Vega-Altair library, renders the chart, saves it to `chart.png`, and displays it.\n- `chat`: Sends a request to the Conversational Analytics API using the `inline_context` variable and the current `messages` list, processes the streaming response, and if a chart is returned, calls `render_chart_response` to display it.\n\nTo use the following sample code, replace the following:\n\n- \u003cvar class=\"readonly\" translate=\"no\"\u003esqlgen-testing\u003c/var\u003e: The ID of your billing project that has the [required APIs enabled](/gemini/docs/conversational-analytics-api/enable-the-api).\n- \u003cvar class=\"readonly\" translate=\"no\"\u003eCreate a bar graph that shows the top five states by the total number of airports\u003c/var\u003e: The prompt that you want to send to the Conversational Analytics API.\n\n from google.cloud import geminidataanalytics\n from google.protobuf.json_format import MessageToDict\n import altair as alt\n import proto\n\n # Helper function for rendering chart response\n def render_chart_response(resp):\n def _convert(v):\n if isinstance(v, proto.marshal.collections.maps.MapComposite):\n return {k: _convert(v) for k, v in v.items()}\n elif isinstance(v, proto.marshal.collections.RepeatedComposite):\n return [_convert(el) for el in v]\n elif isinstance(v, (int, float, str, bool)):\n return v\n else:\n return MessageToDict(v)\n\n vega_config = _convert(resp.result.vega_config)\n chart = alt.Chart.from_dict(vega_config)\n chart.save('chart.png')\n chart.display()\n\n # Helper function for calling the API\n def chat(q: str):\n billing_project = \"\u003cvar class=\"edit\" translate=\"no\"\u003esqlgen-testing\u003c/var\u003e\"\n\n input_message = geminidataanalytics.Message(\n user_message=geminidataanalytics.UserMessage(text=q)\n )\n\n client = geminidataanalytics.DataChatServiceClient()\n request = geminidataanalytics.ChatRequest(\n inline_context=inline_context,\n parent=f\"projects/{billing_project}/locations/global\",\n messages=messages,\n )\n\n # Make the request\n stream = client.https://cloud.google.com/python/docs/reference/google-cloud-geminidataanalytics/latest/google.cloud.geminidataanalytics_v1alpha.services.data_chat_service.DataChatServiceClient.html(request=request)\n\n for reply in stream:\n if \"chart\" in reply.system_message:\n # ChartMessage includes `query` for generating a chart and `result` with the generated chart.\n if \"result\" in reply.system_message.chart:\n render_chart_response(reply.system_message.chart)\n\n # Send the prompt to make a bar graph\n chat(\"\u003cvar class=\"edit\" translate=\"no\"\u003eCreate a bar graph that shows the top five states by the total number of airports.\u003c/var\u003e\")"]]