Xiyan GBI best practices

更新时间:
复制 MD 格式

This topic describes how to use the Xiyan GBI API to implement an intelligent data Q&A feature and helps you quickly integrate the API into your projects.

Prerequisites

Procedure

Java

Step 1: Install the Xiyan GBI SDK for Java

  1. Obtain the latest version number of the Xiyan GBI Java SDK.

  2. Open the pom.xml file of your Maven project.

  3. Add the following dependency to the <dependencies> tag. Replace the version number in the <version></version> tag with the latest version.

     <dependency>
                <groupId>com.aliyun</groupId>
                <artifactId>alibabacloud-dataanalysisgbi20240823</artifactId>
                <version>1.0.0</version>
            </dependency>
  4. Save the pom.xml file.

  5. Update the project dependencies to add the SDK to your project.

Step 2: Implement the intelligent data Q&A feature

This example uses the Xiyan GBI RunDataAnalysis - Chat API and the RunDataAnalysisRequest class to demonstrate how to implement an intelligent data Q&A scenario.

Replace accessKeyId, accessKeySecret, and workspaceId in the code example with your actual values to ensure that the code runs correctly and returns the expected results.

package com.alibaba.iic.llmsolution.gbi.util;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.gateway.pop.Configuration;
import com.aliyun.sdk.gateway.pop.auth.SignatureVersion;
import com.aliyun.sdk.service.dataanalysisgbi20240823.AsyncClient;
import com.aliyun.sdk.service.dataanalysisgbi20240823.models.RunDataAnalysisRequest;
import com.aliyun.sdk.service.dataanalysisgbi20240823.models.RunDataAnalysisResponseBody;
import com.google.gson.Gson;
import darabonba.core.ResponseIterable;
import darabonba.core.ResponseIterator;
import darabonba.core.client.ClientOverrideConfiguration;

public class CommonExample {
    public static void main(String[] args) throws Exception {

        StaticCredentialProvider provider = StaticCredentialProvider.create(
                Credential.builder()
                        .accessKeyId("accessKeyId")
                        .accessKeySecret("accessKeySecret")
                        .build()
        );

        AsyncClient client = AsyncClient.builder()
                .region("cn-beijing")
                .credentialsProvider(provider)
                .serviceConfiguration(Configuration.create()
                        .setSignatureVersion(SignatureVersion.V3)
                )
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setProtocol("HTTPS")
                                .setEndpointOverride("dataanalysisgbi.cn-beijing.aliyuncs.com")
                )
                .build();
        // Controls the overall parameters for conversational analysis.
        RunDataAnalysisRequest request = RunDataAnalysisRequest.builder()
                // The ID of the workspace for the current conversation request.
                .workspaceId("workspaceId")
                // The user query for the current conversation request.
                .query("Query the top five products by sales")
                // The version for the current conversation request. If the specified version is not purchased, the default workspace version is used.
                .specificationType("STANDARD_MIX")
                // Specifies whether to generate only SQL and skip the visualization module.
                .generateSqlOnly(true)
                .build();

        // Gets and parses the streaming content.
        ResponseIterable<RunDataAnalysisResponseBody> x = client.runDataAnalysisWithResponseIterable(request);
        ResponseIterator<RunDataAnalysisResponseBody> iterator = x.iterator();
        while (iterator.hasNext()) {
            RunDataAnalysisResponseBody event = iterator.next();
            System.out.println(new Gson().toJson(event.getData()));
            // sql_part is the event for streaming SQL output. It streams the generated SQL content.
            if (event.getData().getEvent().equals("sql_part")) {
                System.out.println(event.getData().getSql());
            }
            // sql is the final SQL generation event. It is not streamed and directly provides the final SQL.
            if (event.getData().getEvent().equals("sql")) {
                System.out.println(event.getData().getSql());
            }
            // The request result contains the execution result of the visualization model, which can be rendered.
            if (event.getData().getVisualization() != null) {
                System.out.println("The current conversation analysis contains visualization module content that can be rendered");
            }
        }
        System.out.println("ALL***********************");
        System.out.println("Request header values for a successful request:");
        System.out.println(x.getStatusCode());
        System.out.println(x.getHeaders());
    }

}

Sample response

For parameter descriptions, see the Return parameters section of the RunDataAnalysis - Chat API.

{"event":"rewrite","requestId":"8499A3E6-C1B2-5D2E-845F-2F63F8795B4D","rewrite":"Query the top five products by sales and their sales volumes","sessionId":"8db26af8-721c-49bd-95f5-cceb0053ecf6"}
{"event":"selector","requestId":"8499A3E6-C1B2-5D2E-845F-2F63F8795B4D","rewrite":"Query the top five products by sales and their sales volumes","selector":["products","orders"],"sessionId":"8db26af8-721c-49bd-95f5-cceb0053ecf6"}
{"event":"evidence","evidence":"For all metrics, if not all dimensions are restricted, you must perform a SUM aggregation before other aggregations or filtering","rewrite":"Query the top five products by sales and their sales volumes","selector":["products","orders"]}
{"event":"sql_part","evidence":"For all metrics, if not all dimensions are restricted, you must perform a SUM aggregation before other aggregations or filtering","requestId":"8499A3E6-C1B2-5D2E-845F-2F63F8795B4D","rewrite":"Query the top five products by sales and their sales volumes","selector":["products","orders"],"sessionId":"8db26af8-721c-49bd-95f5-cceb0053ecf6","sql":"sql"}
sql
{"event":"sql_part","evidence":"For all metrics, if not all dimensions are restricted, you must perform a SUM aggregation before other aggregations or filtering","requestId":"8499A3E6-C1B2-5D2E-845F-2F63F8795B4D","rewrite":"Query the top five products by sales and their sales volumes","selector":["products","orders"],"sessionId":"8db26af8-721c-49bd-95f5-cceb0053ecf6","sql":""}

{"event":"sql_part","evidence":"For all metrics, if not all dimensions are restricted, you must perform a SUM aggregation before other aggregations or filtering","requestId":"8499A3E6-C1B2-5D2E-845F-2F63F8795B4D","rewrite":"Query the top five products by sales and their sales volumes","selector":["products","orders"],"sessionId":"8db26af8-721c-49bd-95f5-cceb0053ecf6","sql":"SELECT"}
SELECT
{"event":"sql_part","evidence":"For all metrics, if not all dimensions are restricted, you must perform a SUM aggregation before other aggregations or filtering","requestId":"8499A3E6-C1B2-5D2E-845F-2F63F8795B4D","rewrite":"Query the top five products by sales and their sales volumes","selector":["products","orders"],"sessionId":"8db26af8-721c-49bd-95f5-cceb0053ecf6","sql":"SELECT p.product_name, SUM(o.quantity)"}
SELECT p.product_name, SUM(o.quantity)
{"event":"sql_part","evidence":"For all metrics, if not all dimensions are restricted, you must perform a SUM aggregation before other aggregations or filtering","requestId":"8499A3E6-C1B2-5D2E-845F-2F63F8795B4D","rewrite":"Query the top five products by sales and their sales volumes","selector":["products","orders"],"sessionId":"8db26af8-721c-49bd-95f5-cceb0053ecf6","sql":"SELECT p.product_name, SUM(o.quantity) AS total_sales "}
SELECT p.product_name, SUM(o.quantity) AS total_sales 
{"event":"sql_part","evidence":"For all metrics, if not all dimensions are restricted, you must perform a SUM aggregation before other aggregations or filtering","requestId":"8499A3E6-C1B2-5D2E-845F-2F63F8795B4D","rewrite":"Query the top five products by sales and their sales volumes","selector":["products","orders"],"sessionId":"8db26af8-721c-49bd-95f5-cceb0053ecf6","sql":"SELECT p.product_name, SUM(o.quantity) AS total_sales FROM products p "}
SELECT p.product_name, SUM(o.quantity) AS total_sales FROM products p 
{"event":"sql_part","evidence":"For all metrics, if not all dimensions are restricted, you must perform a SUM aggregation before other aggregations or filtering","requestId":"8499A3E6-C1B2-5D2E-845F-2F63F8795B4D","rewrite":"Query the top five products by sales and their sales volumes","selector":["products","orders"],"sessionId":"8db26af8-721c-49bd-95f5-cceb0053ecf6","sql":"SELECT p.product_name, SUM(o.quantity) AS total_sales FROM products p JOIN orders o ON"}
SELECT p.product_name, SUM(o.quantity) AS total_sales FROM products p JOIN orders o ON
{"event":"sql_part","evidence":"For all metrics, if not all dimensions are restricted, you must perform a SUM aggregation before other aggregations or filtering","requestId":"8499A3E6-C1B2-5D2E-845F-2F63F8795B4D","rewrite":"Query the top five products by sales and their sales volumes","selector":["products","orders"],"sessionId":"8db26af8-721c-49bd-95f5-cceb0053ecf6","sql":"SELECT p.product_name, SUM(o.quantity) AS total_sales FROM products p JOIN orders o ON p.product_id \u003d"}
SELECT p.product_name, SUM(o.quantity) AS total_sales FROM products p JOIN orders o ON p.product_id =
{"event":"sql_part","evidence":"For all metrics, if not all dimensions are restricted, you must perform a SUM aggregation before other aggregations or filtering","requestId":"8499A3E6-C1B2-5D2E-845F-2F63F8795B4D","rewrite":"Query the top five products by sales and their sales volumes","selector":["products","orders"],"sessionId":"8db26af8-721c-49bd-95f5-cceb0053ecf6","sql":"SELECT p.product_name, SUM(o.quantity) AS total_sales FROM products p JOIN orders o ON p.product_id \u003d o.product_id "}
SELECT p.product_name, SUM(o.quantity) AS total_sales FROM products p JOIN orders o ON p.product_id = o.product_id 
{"event":"sql_part","evidence":"For all metrics, if not all dimensions are restricted, you must perform a SUM aggregation before other aggregations or filtering","requestId":"8499A3E6-C1B2-5D2E-845F-2F63F8795B4D","rewrite":"Query the top five products by sales and their sales volumes","selector":["products","orders"],"sessionId":"8db26af8-721c-49bd-95f5-cceb0053ecf6","sql":"SELECT p.product_name, SUM(o.quantity) AS total_sales FROM products p JOIN orders o ON p.product_id \u003d o.product_id GROUP BY p.product"}
SELECT p.product_name, SUM(o.quantity) AS total_sales FROM products p JOIN orders o ON p.product_id = o.product_id GROUP BY p.product
{"event":"sql_part","evidence":"For all metrics, if not all dimensions are restricted, you must perform a SUM aggregation before other aggregations or filtering","requestId":"8499A3E6-C1B2-5D2E-845F-2F63F8795B4D","rewrite":"Query the top five products by sales and their sales volumes","selector":["products","orders"],"sessionId":"8db26af8-721c-49bd-95f5-cceb0053ecf6","sql":"SELECT p.product_name, SUM(o.quantity) AS total_sales FROM products p JOIN orders o ON p.product_id \u003d o.product_id GROUP BY p.product_name ORDER BY"}
SELECT p.product_name, SUM(o.quantity) AS total_sales FROM products p JOIN orders o ON p.product_id = o.product_id GROUP BY p.product_name ORDER BY
{"event":"sql_part","evidence":"For all metrics, if not all dimensions are restricted, you must perform a SUM aggregation before other aggregations or filtering","requestId":"8499A3E6-C1B2-5D2E-845F-2F63F8795B4D","rewrite":"Query the top five products by sales and their sales volumes","selector":["products","orders"],"sessionId":"8db26af8-721c-49bd-95f5-cceb0053ecf6","sql":"SELECT p.product_name, SUM(o.quantity) AS total_sales FROM products p JOIN orders o ON p.product_id \u003d o.product_id GROUP BY p.product_name ORDER BY total_sales DESC "}
SELECT p.product_name, SUM(o.quantity) AS total_sales FROM products p JOIN orders o ON p.product_id = o.product_id GROUP BY p.product_name ORDER BY total_sales DESC 
{"event":"sql_part","evidence":"For all metrics, if not all dimensions are restricted, you must perform a SUM aggregation before other aggregations or filtering","requestId":"8499A3E6-C1B2-5D2E-845F-2F63F8795B4D","rewrite":"Query the top five products by sales and their sales volumes","selector":["products","orders"],"sessionId":"8db26af8-721c-49bd-95f5-cceb0053ecf6","sql":"SELECT p.product_name, SUM(o.quantity) AS total_sales FROM products p JOIN orders o ON p.product_id \u003d o.product_id GROUP BY p.product_name ORDER BY total_sales DESC LIMIT 5; "}
SELECT p.product_name, SUM(o.quantity) AS total_sales FROM products p JOIN orders o ON p.product_id = o.product_id GROUP BY p.product_name ORDER BY total_sales DESC LIMIT 5; 
{"event":"sql_part","evidence":"For all metrics, if not all dimensions are restricted, you must perform a SUM aggregation before other aggregations or filtering","requestId":"8499A3E6-C1B2-5D2E-845F-2F63F8795B4D","rewrite":"Query the top five products by sales and their sales volumes","selector":["products","orders"],"sessionId":"8db26af8-721c-49bd-95f5-cceb0053ecf6","sql":"SELECT p.product_name, SUM(o.quantity) AS total_sales FROM products p JOIN orders o ON p.product_id \u003d o.product_id GROUP BY p.product_name ORDER BY total_sales DESC LIMIT 5; "}
SELECT p.product_name, SUM(o.quantity) AS total_sales FROM products p JOIN orders o ON p.product_id = o.product_id GROUP BY p.product_name ORDER BY total_sales DESC LIMIT 5; 
{"event":"sql","evidence":"For all metrics, if not all dimensions are restricted, you must perform a SUM aggregation before other aggregations or filtering","requestId":"8499A3E6-C1B2-5D2E-845F-2F63F8795B4D","rewrite":"Query the top five products by sales and their sales volumes","selector":["products","orders"],"sessionId":"8db26af8-721c-49bd-95f5-cceb0053ecf6","sql":"SELECT p.product_name, SUM(o.quantity) AS total_sales\nFROM products p\nJOIN orders o ON p.product_id \u003d o.product_id\nGROUP BY p.product_name\nORDER BY total_sales DESC\nLIMIT 5;\n"}
SELECT p.product_name, SUM(o.quantity) AS total_sales
FROM products p
JOIN orders o ON p.product_id = o.product_id
GROUP BY p.product_name
ORDER BY total_sales DESC
LIMIT 5;

{"event":"sql_data","evidence":"For all metrics, if not all dimensions are restricted, you must perform a SUM aggregation before other aggregations or filtering","requestId":"8499A3E6-C1B2-5D2E-845F-2F63F8795B4D","rewrite":"Query the top five products by sales and their sales volumes","selector":["products","orders"],"sessionId":"8db26af8-721c-49bd-95f5-cceb0053ecf6","sql":"SELECT p.product_name, SUM(o.quantity) AS total_sales\nFROM products p\nJOIN orders o ON p.product_id \u003d o.product_id\nGROUP BY p.product_name\nORDER BY total_sales DESC\nLIMIT 5;\n","sqlData":{"column":["product_name","total_sales"],"data":[{"total_sales":"265","product_name":"Silk Scarf"},{"total_sales":"197","product_name":"Men's Electric Makeup Brush Set"},{"total_sales":"158","product_name":"Women's Electric Makeup Brush Set"},{"total_sales":"157","product_name":"Ring"},{"total_sales":"136","product_name":"Leather Bag"}]}}
{"event":"result","evidence":"For all metrics, if not all dimensions are restricted, you must perform a SUM aggregation before other aggregations or filtering","requestId":"8499A3E6-C1B2-5D2E-845F-2F63F8795B4D","rewrite":"Query the top five products by sales and their sales volumes","selector":["products","orders"],"sessionId":"8db26af8-721c-49bd-95f5-cceb0053ecf6","sql":"SELECT p.product_name, SUM(o.quantity) AS total_sales\nFROM products p\nJOIN orders o ON p.product_id \u003d o.product_id\nGROUP BY p.product_name\nORDER BY total_sales DESC\nLIMIT 5;\n","sqlData":{"column":["product_name","total_sales"],"data":[{"total_sales":"265","product_name":"Silk Scarf"},{"total_sales":"197","product_name":"Men's Electric Makeup Brush Set"},{"total_sales":"158","product_name":"Women's Electric Makeup Brush Set"},{"total_sales":"157","product_name":"Ring"},{"total_sales":"136","product_name":"Leather Bag"}]},"visualization":{"data":{"plotType":"bar","xAxis":["product_name"],"yAxis":["total_sales"]},"text":"The top five products by sales and their sales volumes are: Silk Scarf, with total sales of 265 units; Men's Electric Makeup Brush Set, with sales of 197 units; Women's Electric Makeup Brush Set, with sales of 158 units; Ring, with sales of 157 units; and Leather Bag, with sales of 136 units."}}
ALL***********************
Request header values for a successful request:
200
{Transfer-Encoding=chunked, Keep-Alive=timeout=25, Access-Control-Expose-Headers=*, Access-Control-Allow-Origin=*, x-acs-request-id=8499A3E6-C1B2-5D2E-845F-2F63F8795B4D, Connection=keep-alive, Date=Thu, 14 Nov 2024 08:16:49 GMT, Content-Type=text/event-stream;charset=utf-8, x-acs-trace-id=26e2559443d87082911aa44f656072df}

If you do not authorize a database connection, the following result is returned:

{"errorMessage":"data source is empty","event":"error"}
ALL***********************
Request header values for a successful request:
200
{Transfer-Encoding=chunked, Keep-Alive=timeout=25, Access-Control-Expose-Headers=*, Access-Control-Allow-Origin=*, x-acs-request-id=CB1F6A3B-43DC-5D9D-8FDC-57A9474B0DF3, Connection=keep-alive, Date=Thu, 14 Nov 2024 06:20:33 GMT, Content-Type=text/event-stream;charset=utf-8, x-acs-trace-id=dfa7db76cf65dcc933292999274fa687}

Python

Step 1: Install dependencies

pip install alibabacloud-tea-openapi-sse==1.0.2

Step 2: Implement the intelligent data Q&A feature

The following is a code example for the RunDataAnalysis - Chat API of Xiyan GBI.

Replace accessKeyId, accessKeySecret, and workspaceId in the code example with your actual values to ensure that the code runs correctly and returns the expected results.

from alibabacloud_tea_openapi_sse.client import Client as OpenApiClient
from alibabacloud_tea_openapi_sse import models as open_api_models
from alibabacloud_tea_util_sse import models as util_models
import asyncio
import json

class RunDataAnalysis:
    def __init__(self) -> None:
        self.endpoint = None
        self._client = None
        self._api_info = self._create_api_info()
        self._runtime = util_models.RuntimeOptions(read_timeout=1000 * 100)
        self._init_app()

    def _init_app(self):
        endpoint = 'dataanalysisgbi.cn-beijing.aliyuncs.com'
        access_key_id = '${access_key_id}'
        access_key_secret = '${access_key_secret}'
        assert endpoint is not None and access_key_id is not None and access_key_secret is not None

        self._client = self._create_client(access_key_id, access_key_secret, endpoint)

    def _create_client(
            self,
            access_key_id: str,
            access_key_secret: str,
            endpoint: str,
    ) -> OpenApiClient:
        config = open_api_models.Config(
            access_key_id=access_key_id,
            access_key_secret=access_key_secret
        )
        config.endpoint = endpoint if endpoint is not None else 'dataanalysisgbi.cn-beijing.aliyuncs.com'
        return OpenApiClient(config)

    def _create_api_info(self) -> open_api_models.Params:
        """
        API-related information
        @param path: params
        @return: OpenApi.Params
        """
        params = open_api_models.Params(
            # API operation name
            action='RunDataAnalysis',
            # API version
            version='2024-08-23',
            # API protocol
            protocol='HTTPS',
            # API HTTP method
            method='POST',
            auth_type='AK',
            style='RPC',
            # API path
            pathname='/${workspaceId}/gbi/runDataAnalysis',
            # Request body format
            req_body_type='json',
            # Response body format
            body_type='sse'
        )
        return params

    async def do_sse_query(self, query: str):
        assert self._client is not None
        assert isinstance(query, str), '"query" is mandatory and should be str'

        body = {
            'specificationType': 'STANDARD_MIX',
            'query': query,
        }
        request = open_api_models.OpenApiRequest(
            body=body
        )
        sse_receiver = self._client.call_sse_api_async(params=self._api_info, request=request, runtime=self._runtime)
        return sse_receiver


# Initialize the model

async def query():
    xiyan_gbi = RunDataAnalysis()
    frame_count = 0
    async for res in await xiyan_gbi.do_sse_query('Query all keyword data and display it in a pie chart'):
        try:
            data = json.loads(res.get('event').data)
            print(data)
        except json.JSONDecodeError:
            print('------json.JSONDecodeError--------')
            print(res.get('headers'))
            print(res.get('event').data)
            print('------json.JSONDecodeError-end--------')
            continue
    print('------end--------')


if __name__ == '__main__':
    asyncio.run(query())

Sample response

For parameter descriptions, see the Return parameters section of the RunDataAnalysis - Chat API.

{'data': {'requestId': '93DE1D26-153E-5386-BA8F-9D2E2F8B3381', 'sessionId': '10148716_1f8ebf09-df4b-4b0c-9493-66a1895a9ba4', 'event': 'rewrite', 'rewrite': 'Query all data from the user table and display it in a pie chart'}}
{'data': {'requestId': '93DE1D26-153E-5386-BA8F-9D2E2F8B3381', 'selector': ['user'], 'sessionId': '10148716_1f8ebf09-df4b-4b0c-9493-66a1895a9ba4', 'event': 'selector', 'rewrite': 'Query all data from the user table and display it in a pie chart'}}
{'data': {'evidence': 'KKK refers to the customer transaction value. KKK = Total Sales / Total Orders, rounded to two decimal places.', 'selector': ['user'], 'event': 'evidence', 'rewrite': 'Query all data from the user table and display it in a pie chart'}}
{'data': {'evidence': 'KKK refers to the customer transaction value. KKK = Total Sales / Total Orders, rounded to two decimal places.', 'requestId': '93DE1D26-153E-5386-BA8F-9D2E2F8B3381', 'selector': ['user'], 'sessionId': '10148716_1f8ebf09-5a9ba4', 'event': 'sql_part', 'rewrite': 'Query all data from the user table and display it in a pie chart', 'sql': ''}}
{'data': {'evidence': 'KKK refers to the customer transaction value. KKK = Total Sales / Total Orders, rounded to two decimal places.', 'requestId': '93DE1D26-153E-5386-BA8F-9D2E2F8B3381', 'selector': ['user'], 'sessionId': '10148716_1f8ebf09-5a9ba4', 'event': 'sql_part', 'rewrite': 'Query all data from the user table and display it in a pie chart', 'sql': 'select *'}}
{'data': {'evidence': 'KKK refers to the customer transaction value. KKK = Total Sales / Total Orders, rounded to two decimal places.', 'requestId': '93DE1D26-153E-5386-BA8F-9D2E2F8B3381', 'selector': ['user'], 'sessionId': '10148716_1f8ebf09-5a9ba4', 'event': 'sql_part', 'rewrite': 'Query all data from the user table and display it in a pie chart', 'sql': 'select * from user '}}
{'data': {'evidence': 'KKK refers to the customer transaction value. KKK = Total Sales / Total Orders, rounded to two decimal places.', 'requestId': '93DE1D26-153E-5386-BA8F-9D2E2F8B3381', 'selector': ['user'], 'sessionId': '10148716_1f8ebf09-5a9ba4', 'event': 'sql_part', 'rewrite': 'Query all data from the user table and display it in a pie chart', 'sql': 'select * from user '}}
{'data': {'evidence': 'KKK refers to the customer transaction value. KKK = Total Sales / Total Orders, rounded to two decimal places.', 'requestId': '93DE1D26-153E-5386-BA8F-9D2E2F8B3381', 'selector': ['user'], 'sessionId': '10148716_1f8ebf09-5a9ba4', 'event': 'sql', 'rewrite': 'Query all data from the user table and display it in a pie chart', 'sql': 'select * from user\n'}}
{'data': {'evidence': 'KKK refers to the customer transaction value. KKK = Total Sales / Total Orders, rounded to two decimal places.', 'requestId': '93DE1D26-153E-5386-BA8F-9D2E2F8B3381', 'selector': ['user'], 'sqlData': {}, 'sessionId': '101b0c-9493-66a1895a9ba4', 'event': 'sql_data', 'rewrite': 'Query all data from the user table and display it in a pie chart', 'sql': 'select * from user\n'}}
{'data': {'evidence': 'KKK refers to the customer transaction value. KKK = Total Sales / Total Orders, rounded to two decimal places.', 'requestId': '93DE1D26-153E-5386-BA8F-9D2E2F8B3381', 'selector': ['user'], 'sqlData': {}, 'sessionId': '101b0c-9493-66a1895a9ba4', 'event': 'result', 'rewrite': 'Query all data from the user table and display it in a pie chart', 'sql': 'select * from user\n'}}
------end--------

Go

Step 1: Install dependencies

Add the following information to the go.mod file of your Go project to specify the required module paths and versions.

go 1.16

require (
	github.com/alibabacloud-go/darabonba-openapi/v2 v2.1.2 // indirect
	github.com/alibabacloud-go/openapi-util v0.1.1 // indirect
	github.com/alibabacloud-go/tea v1.3.2 // indirect
	github.com/alibabacloud-go/tea-utils/v2 v2.0.7 // indirect
)

Step 2: Implement the intelligent data Q&A feature

The following is a code example for the RunDataAnalysis - Chat API of Xiyan GBI.

Replace accessKeyId, accessKeySecret, and workspaceId in the code example with your actual values to ensure that the code runs correctly and returns the expected results.

// This file is auto-generated, don't edit it. Thanks.
package main

import (
	"fmt"
	"io"
	"os"

	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	openapiutil "github.com/alibabacloud-go/openapi-util/service"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
)

/**
 * API-related information
 * @param path params
 * @return OpenApi.Params
 */
func CreateApiInfo() (_result *openapi.Params) {
	params := &openapi.Params{
		// API operation name
		Action: tea.String("RunDataAnalysis"),
		// API version
		Version: tea.String("2024-08-23"),
		// API protocol
		Protocol: tea.String("HTTPS"),
		// API HTTP method
		Method:   tea.String("POST"),
		AuthType: tea.String("AK"),
		Style:    tea.String("ROA"),
		// API path
		Pathname: tea.String("/{workspaceId}/gbi/runDataAnalysis"),
		// Request body format
		ReqBodyType: tea.String("json"),
		// Response body format. It must be binary so that CallApi can pass through the response body for ReadAsSSE.
		BodyType: tea.String("binary"), //sse binary
	}
	_result = params
	return _result
}

func _main(args []*string) (_err error) {
	// Leaking your project code may expose your AccessKey and compromise the security of all resources in your account. The following code is for reference only.
	// Use a more secure method, such as Security Token Service (STS). For more information about authentication methods, see https://help.aliyun.com/document_detail/378661.html.
	config := &openapi.Config{
		AccessKeyId:     tea.String("{accessKeyId}"),
		AccessKeySecret: tea.String("{accessKeySecret}"),
	}
	config.Endpoint = tea.String("dataanalysisgbi.cn-beijing.aliyuncs.com")
	client, err := openapi.NewClient(config)
	if err != nil {
		return err
	}

	params := CreateApiInfo()
	body := map[string]interface{}{
		"query":             "List 10 data entries",
		"specificationType": "STANDARD_MIX",
	}
	// runtime options
	runtime := &util.RuntimeOptions{}
	request := &openapi.OpenApiRequest{
		Body: openapiutil.Query(body),
	}
	// If you copy and run the code, print the API return value.
	// The return value is a map. You can get three types of data from the map: the response body, response headers, and the HTTP status code.
	resp, err := client.CallApi(params, request, runtime)
	if err != nil {
		return err
	}

	// Iteratively read the SSE content.
	events, err1 := util.ReadAsSSE(resp["body"].(io.ReadCloser))

	if err1 != nil {

	}

	for event := range events {
		fmt.Println("-------------------------------------")
		fmt.Printf("Event ID: %s, Event name: %s, Data: %s\n", tea.StringValue(event.ID), tea.StringValue(event.Event), tea.StringValue(event.Data))
	}
	return nil
}

func main() {
	err := _main(tea.StringSlice(os.Args[1:]))
	if err != nil {
		panic(err)
	}
}

Sample response

For parameter descriptions, see the Return parameters section of the RunDataAnalysis - Chat API.

-------------------------------------
Event ID: , Event name: rewrite, Data: {"data":{"requestId":"122453F5-B4F3-52B9-BCA5-3BA3097DA2D4","sessionId":"10204244_4e2e5e96-51c7-419b-8390-137f48b4459e","event":"rewrite","rewrite":"List 10 data entries"}}
-------------------------------------
Event ID: , Event name: selector, Data: {"data":{"requestId":"122453F5-B4F3-52B9-BCA5-3BA3097DA2D4","selector":["customers","products","orders"],"sessionId":"10204244_4e2e5e96-51c7-419b-8390-137f48b4459e","event":"selector","rewrite":"List 10 data entries"}}
-------------------------------------
Event ID: , Event name: refine, Data: {"data":{"requestId":"122453F5-B4F3-52B9-BCA5-3BA3097DA2D4","selector":["customers","products","orders"],"sessionId":"10204244_4e2e5e96-51c7-419b-8390-137f48b4459e","event":"refine","rewrite":"List 10 data entries","attempts":[{"sql":""}]}}
-------------------------------------
Event ID: , Event name: refine, Data: {"data":{"requestId":"122453F5-B4F3-52B9-BCA5-3BA3097DA2D4","selector":["customers","products","orders"],"sessionId":"10204244_4e2e5e96-51c7-419b-8390-137f48b4459e","event":"refine","rewrite":"List 10 data entries","attempts":[{"sql":"SELECT * FROM customers LIMIT"}]}}
-------------------------------------
Event ID: , Event name: refine, Data: {"data":{"requestId":"122453F5-B4F3-52B9-BCA5-3BA3097DA2D4","selector":["customers","products","orders"],"sessionId":"10204244_4e2e5e96-51c7-419b-8390-137f48b4459e","event":"refine","rewrite":"List 10 data entries","attempts":[{"sql":"SELECT * FROM customers LIMIT 10\n"}]}}
-------------------------------------
Event ID: , Event name: refine, Data: {"data":{"requestId":"122453F5-B4F3-52B9-BCA5-3BA3097DA2D4","selector":["customers","products","orders"],"sessionId":"10204244_4e2e5e96-51c7-419b-8390-137f48b4459e","event":"refine","rewrite":"List 10 data entries","attempts":[{"sql":"SELECT * FROM customers LIMIT 10\n"}]}}
-------------------------------------
Event ID: , Event name: refine, Data: {"data":{"requestId":"122453F5-B4F3-52B9-BCA5-3BA3097DA2D4","selector":["customers","products","orders"],"sessionId":"10204244_4e2e5e96-51c7-419b-8390-137f48b4459e","event":"refine","rewrite":"List 10 data entries","attempts":[{"sql":"SELECT * FROM customers LIMIT 10\n"}]}}
-------------------------------------
Event ID: , Event name: sql, Data: {"data":{"requestId":"122453F5-B4F3-52B9-BCA5-3BA3097DA2D4","selector":["customers","products","orders"],"sqlData":{"data":[{"join_date":"2023-10-25","name":"Duoliya","customer_id":"1","email":"tjia@example.com"},{"join_date":"2024-01-11","name":"Wanyan Lie","customer_id":"2","email":"yexiulan@example.com"},{"join_date":"2022-10-16","name":"Lin Dong","customer_id":"3","email":"gkang@example.net"},{"join_date":"2023-09-18","name":"He Hui","customer_id":"4","email":"taohe@example.net"},{"join_date":"2024-06-26","name":"Li Yuzhen","customer_id":"5","email":"zhouxiuying@example.com"},{"join_date":"2023-10-12","name":"Xiao Jian","customer_id":"6","email":"xiuying64@example.com"},{"join_date":"2023-04-17","name":"Deng Xiulan","customer_id":"7","email":"qiang76@example.org"},{"join_date":"2023-12-25","name":"Fu Wei","customer_id":"8","email":"guojie@example.org"},{"join_date":"2022-08-06","name":"Wang Lei","customer_id":"9","email":"li74@example.net"},{"join_date":"2022-12-18","name":"Gong Shuying","customer_id":"10","email":"qiangshi@example.net"}],"column":["customer_id","name","email","join_date"]},"sessionId":"10204244_4e2e5e96-51c7-419b-8390-137f48b4459e","event":"sql","rewrite":"List 10 data entries","sql":"SELECT * FROM customers LIMIT 10\n","attempts":[{"sql":"SELECT * FROM customers LIMIT 10\n"}]}}
-------------------------------------
Event ID: , Event name: sql_data, Data: {"data":{"requestId":"122453F5-B4F3-52B9-BCA5-3BA3097DA2D4","selector":["customers","products","orders"],"sqlData":{"data":[{"join_date":"2023-10-25","name":"Duoliya","customer_id":"1","email":"tjia@example.com"},{"join_date":"2024-01-11","name":"Wanyan Lie","customer_id":"2","email":"yexiulan@example.com"},{"join_date":"2022-10-16","name":"Lin Dong","customer_id":"3","email":"gkang@example.net"},{"join_date":"2023-09-18","name":"He Hui","customer_id":"4","email":"taohe@example.net"},{"join_date":"2024-06-26","name":"Li Yuzhen","customer_id":"5","email":"zhouxiuying@example.com"},{"join_date":"2023-10-12","name":"Xiao Jian","customer_id":"6","email":"xiuying64@example.com"},{"join_date":"2023-04-17","name":"Deng Xiulan","customer_id":"7","email":"qiang76@example.org"},{"join_date":"2023-12-25","name":"Fu Wei","customer_id":"8","email":"guojie@example.org"},{"join_date":"2022-08-06","name":"Wang Lei","customer_id":"9","email":"li74@example.net"},{"join_date":"2022-12-18","name":"Gong Shuying","customer_id":"10","email":"qiangshi@example.net"}],"column":["customer_id","name","email","join_date"]},"sessionId":"10204244_4e2e5e96-51c7-419b-8390-137f48b4459e","event":"sql_data","rewrite":"List 10 data entries","sql":"SELECT * FROM customers LIMIT 10\n","attempts":[{"sql":"SELECT * FROM customers LIMIT 10\n"}]}}
-------------------------------------
Event ID: , Event name: result, Data: {"data":{"visualization":{"text":"The query result lists 10 customer data entries, including customer ID, name, email, and join date. The join dates of these customers range from 2022 to 2024, covering different time periods."},"requestId":"122453F5-B4F3-52B9-BCA5-3BA3097DA2D4","selector":["customers","products","orders"],"sqlData":{"data":[{"join_date":"2023-10-25","name":"Duoliya","customer_id":"1","email":"tjia@example.com"},{"join_date":"2024-01-11","name":"Wanyan Lie","customer_id":"2","email":"yexiulan@example.com"},{"join_date":"2022-10-16","name":"Lin Dong","customer_id":"3","email":"gkang@example.net"},{"join_date":"2023-09-18","name":"He Hui","customer_id":"4","email":"taohe@example.net"},{"join_date":"2024-06-26","name":"Li Yuzhen","customer_id":"5","email":"zhouxiuying@example.com"},{"join_date":"2023-10-12","name":"Xiao Jian","customer_id":"6","email":"xiuying64@example.com"},{"join_date":"2023-04-17","name":"Deng Xiulan","customer_id":"7","email":"qiang76@example.org"},{"join_date":"2023-12-25","name":"Fu Wei","customer_id":"8","email":"guojie@example.org"},{"join_date":"2022-08-06","name":"Wang Lei","customer_id":"9","email":"li74@example.net"},{"join_date":"2022-12-18","name":"Gong Shuying","customer_id":"10","email":"qiangshi@example.net"}],"column":["customer_id","name","email","join_date"]},"sessionId":"10204244_4e2e5e96-51c7-419b-8390-137f48b4459e","event":"result","rewrite":"List 10 data entries","sql":"SELECT * FROM customers LIMIT 10\n","attempts":[{"sql":"SELECT * FROM customers LIMIT 10\n"}]}}