API calls

更新时间:
复制 MD 格式

This topic describes how to find relevant fields and call OpenAPI operations when using AI Doc.

Step 1: Preparation

Before calling AI Doc OpenAPI operations, gather the template ID and folder ID. If you already have both, skip to Step 2.

Obtain the template ID

Log on to the AI Doc website, go to the template management page, and locate the Template ID field.

image

Obtain the folder ID

Log on to the AI Doc website, go to the document parsing page, select a folder, and find the folder ID in the panel on the right.

image

Step 2: Create an AccessKey pair for OpenAPI access

You can authenticate with the AccessKey pair of your Alibaba Cloud account or a RAM user. This example uses a RAM user.

Log on to the Alibaba Cloud RAM console, create a user, and select OpenAPI calling access.

image

Grant the AliyunEnergyFullAccess permission to the user.

image

Copy the AccessKey ID and AccessKey Secret for use in later steps.

Important

Save the AccessKey information immediately after enabling OpenAPI calling access. You cannot retrieve it after closing the page.

image

Step 3: Call OpenAPI operations using the SDK

Go to the Alibaba Cloud OpenAPI Portal and search for "AI document processing" to browse available operations, run online tests, or download SDK examples. You can also refer to the AI document processing API reference for details.

All document parsing and information extraction workflows follow the same two-step pattern:

  • Submit a document parsing or information extraction job.

  • Poll for results using the jobId returned in step 1.

The following examples use Java.

Import POM

    <dependency>
      <groupId>com.aliyun</groupId>
      <artifactId>energyexpertexternal20220923</artifactId>
      <version>${Please use the latest version}</version>
    </dependency>

Local testing environment variable settings

Set the following environment variables before running the examples:

Variable

Description

ALIBABA_CLOUD_ACCESS_KEY_ID

AccessKey ID

ALIBABA_CLOUD_ACCESS_KEY_SECRET

AccessKey Secret

ENDPOINT

SDK access address. See Endpoints.

FILE_NAME

File name

FILE_URL

URL of the document to process

FILE_PATH

Local file path (for file stream uploads)

FOLDER_ID

Folder ID. See Obtain the folder ID.

TEMPLATE_ID

Template ID (information extraction only). See Obtain the template ID.

Document parsing example

package com.aliyun.aidoc.sample;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import com.aliyun.energyexpertexternal20220923.Client;
import com.aliyun.energyexpertexternal20220923.models.*;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;

/**
 * @author Energy Expert AI DOC
 *
 */
public class DocParsingSample {
    static String ACCESS_ID = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    static String ACCESS_KEY = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
    static String ENDPOINT = System.getenv("ENDPOINT");
    static String FOLDER_ID = System.getenv("FOLDER_ID");
    static String FILE_URL = System.getenv("FILE_URL");
    static String FILE_PATH = System.getenv("FILE_PATH");
    static String FILE_NAME = System.getenv("FILE_NAME");

    public static void main(String[] args) throws Exception {
        //Local file upload
        //String taskId = submitDocParsingTaskAdvance();

        //Using a publicly accessible URL
        String taskId = submitDocParsingTask();
        //Asynchronously submit document parsing task, processing time depends on file size, need to wait for a while to get results
        //getDocParsingResult(taskId);

    }

    static public void getDocParsingResult(String taskId)  {

        GetDocParsingResultRequest request = new GetDocParsingResultRequest();
        request.setTaskId(taskId);

        try {
            Client client = createClient();
            // Write your code to display the response of the operation if necessary.
            GetDocParsingResultResponse response = client.getDocParsingResult(request);
            System.out.println(com.aliyun.teautil.Common.toJSONString(response));
        } catch (TeaException error) {
            // Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
            // The error message.
            System.out.println(error.getMessage());
            // Display the troubleshooting information.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
            // The error message.
            System.out.println(error.getMessage());
            // Display the troubleshooting information.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }

    }

    static public String submitDocParsingTaskAdvance() throws Exception {
        File file = new File(FILE_PATH);
        InputStream inputStream = new FileInputStream(file);

        SubmitDocParsingTaskAdvanceRequest request = new SubmitDocParsingTaskAdvanceRequest();
        request.setFolderId(FOLDER_ID);
        request.setFileName(FILE_NAME);
        request.setNeedAnalyzeImg(true);
        request.setFileUrlObject(inputStream);

        try {
            Client client = createClient();

            // Write your code to display the response of the operation if necessary.
            RuntimeOptions runtimeOptions = new RuntimeOptions();
            SubmitDocParsingTaskResponse response = client.submitDocParsingTaskAdvance(request, null, runtimeOptions);
            System.out.println(com.aliyun.teautil.Common.toJSONString(response));
            return response.getBody().getData().getTaskId();
        } catch (TeaException error) {
            // Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
            // The error message.
            System.out.println(error.getMessage());
            // Display the troubleshooting information.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
            // The error message.
            System.out.println(error.getMessage());
            // Display the troubleshooting information.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }

        return null;
    }

    static public String submitDocParsingTask()  {
        SubmitDocParsingTaskRequest request = new SubmitDocParsingTaskRequest();
        request.setFolderId(FOLDER_ID);
        request.setFileName(FILE_NAME);
        request.setFileUrl(FILE_URL);
        request.setNeedAnalyzeImg(true);

        try {
            Client client = createClient();
            // Write your code to display the response of the operation if necessary.
            SubmitDocParsingTaskResponse response = client.submitDocParsingTask(request);
            System.out.println(com.aliyun.teautil.Common.toJSONString(response));
            return response.getBody().getData().getTaskId();
        } catch (TeaException error) {
            // Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
            // The error message.
            System.out.println(error.getMessage());
            // Display the troubleshooting information.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
            // The error message.
            System.out.println(error.getMessage());
            // Display the troubleshooting information.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }

        return null;
    }

    public static Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setReadTimeout(30 * 1000)
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment.
                .setAccessKeyId(ACCESS_ID)
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment.
                .setAccessKeySecret(ACCESS_KEY);

        // Endpoint, refer to https://api.aliyun.com/product/energyExpertExternal
        config.endpoint = ENDPOINT;
        return new Client(config);
    }
}

RAG and long text understanding information extraction example

package com.aliyun.aidoc.sample;

import com.aliyun.energyexpertexternal20220923.Client;
import com.aliyun.energyexpertexternal20220923.models.*;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * @author Energy Expert AI DOC
 *
 */
public class DocExtractionSample {
    static String ACCESS_ID = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    static String ACCESS_KEY = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
    static String ENDPOINT = System.getenv("ENDPOINT");
    static String FOLDER_ID = System.getenv("FOLDER_ID");
    static String TEMPLATE_ID = System.getenv("TEMPLATE_ID");
    static String FILE_URL = System.getenv("FILE_URL");
    static String FILE_PATH = System.getenv("FILE_PATH");
    static String FILE_NAME = System.getenv("FILE_NAME");

    public static void main(String[] args) throws Exception {
        //Local file upload
        //String taskId = submitDocExtractionTaskAdvance();

        //Using a publicly accessible URL
        String taskId = submitDocExtractionTask();
        //Asynchronously submit document parsing task, processing time depends on file size, need to wait for a while to get results
        getDocExtractionResult(taskId);

    }

    static public void getDocExtractionResult(String taskId) throws Exception {
        Client client = DocParsingSample.createClient();

        GetDocExtractionResultRequest request = new GetDocExtractionResultRequest();
        request.setTaskId(taskId);

        try {
            // Write your code to display the response of the operation if necessary.
            GetDocExtractionResultResponse response = client.getDocExtractionResult(request);
            System.out.println(com.aliyun.teautil.Common.toJSONString(response));
        } catch (TeaException error) {
            // Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
            // The error message.
            System.out.println(error.getMessage());
            // Display the troubleshooting information.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
            // The error message.
            System.out.println(error.getMessage());
            // Display the troubleshooting information.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }

    }

    static public String submitDocExtractionTaskAdvance() throws Exception {
        File file = new File(FILE_PATH);
        InputStream inputStream = new FileInputStream(file);

        SubmitDocExtractionTaskAdvanceRequest request = new SubmitDocExtractionTaskAdvanceRequest();
        request.setFolderId(FOLDER_ID);
        request.setTemplateId(TEMPLATE_ID);
        request.setExtractType("rag");
        request.setFileName(FILE_NAME);
        request.setFileUrlObject(inputStream);

        Client client = DocParsingSample.createClient();

        try {
            // Write your code to display the response of the operation if necessary.
            RuntimeOptions runtimeOptions = new RuntimeOptions();
            SubmitDocExtractionTaskResponse response = client.submitDocExtractionTaskAdvance(request, null, runtimeOptions);
            System.out.println(com.aliyun.teautil.Common.toJSONString(response));
            return response.getBody().getData().getTaskId();
        } catch (TeaException error) {
            // Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
            // The error message.
            System.out.println(error.getMessage());
            // Display the troubleshooting information.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
            // The error message.
            System.out.println(error.getMessage());
            // Display the troubleshooting information.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }

        return null;
    }

    static public String submitDocExtractionTask() throws Exception {
        SubmitDocExtractionTaskRequest request = new SubmitDocExtractionTaskRequest();
        request.setFolderId(FOLDER_ID);
        request.setTemplateId(TEMPLATE_ID);
        request.setFileName(FILE_NAME);
        request.setFileUrl(FILE_URL);
        request.setExtractType("rag");

        Client client = DocParsingSample.createClient();
        try {
            // Write your code to display the response of the operation if necessary.
            SubmitDocExtractionTaskResponse response = client.submitDocExtractionTask(request);
            System.out.println(com.aliyun.teautil.Common.toJSONString(response));
            return response.getBody().getData().getTaskId();
        } catch (TeaException error) {
            // Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
            // The error message.
            System.out.println(error.getMessage());
            // Display the troubleshooting information.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
            // The error message.
            System.out.println(error.getMessage());
            // Display the troubleshooting information.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }

        return null;
    }

    public static Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setReadTimeout(30 * 1000)
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment.
                .setAccessKeyId(ACCESS_ID)
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment.
                .setAccessKeySecret(ACCESS_KEY);

        // Endpoint, refer to https://api.aliyun.com/product/energyExpertExternal
        config.endpoint = ENDPOINT;
        return new Client(config);
    }
}

VL information extraction example

package com.aliyun.aidoc.sample;

import com.aliyun.energyexpertexternal20220923.Client;
import com.aliyun.energyexpertexternal20220923.models.*;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * @author Energy Expert AI DOC
 *
 */
public class VLExtractionSample {
    static String ACCESS_ID = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    static String ACCESS_KEY = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
    static String ENDPOINT = System.getenv("ENDPOINT");
    static String FOLDER_ID = System.getenv("FOLDER_ID");
    static String TEMPLATE_ID = System.getenv("TEMPLATE_ID");
    static String FILE_URL = System.getenv("FILE_URL");
    static String FILE_PATH = System.getenv("FILE_PATH");
    static String FILE_NAME = System.getenv("FILE_NAME");

    public static void main(String[] args) throws Exception {
        //Local file upload
        //String taskId = submitVLExtractionTaskAdvance();

        //Using a publicly accessible URL
        String taskId = submitVLExtractionTask();
        //Asynchronously submit document parsing task, processing time depends on file size, need to wait for a while to get results
        getVLExtractionResult(taskId);

    }

    static public void getVLExtractionResult(String taskId)  {

        GetVLExtractionResultRequest request = new GetVLExtractionResultRequest();
        request.setTaskId(taskId);

        try {
            Client client = createClient();
            // Write your code to display the response of the operation if necessary.
            GetVLExtractionResultResponse response = client.getVLExtractionResult(request);
            System.out.println(com.aliyun.teautil.Common.toJSONString(response));
        } catch (TeaException error) {
            // Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
            // The error message.
            System.out.println(error.getMessage());
            // Display the troubleshooting information.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
            // The error message.
            System.out.println(error.getMessage());
            // Display the troubleshooting information.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }

    }

    static public String submitVLExtractionTaskAdvance() throws Exception {
        File file = new File(FILE_PATH);
        InputStream inputStream = new FileInputStream(file);

        SubmitVLExtractionTaskAdvanceRequest request = new SubmitVLExtractionTaskAdvanceRequest();
        request.setFolderId(FOLDER_ID);
        request.setTemplateId(TEMPLATE_ID);
        request.setFileName(FILE_NAME);
        request.setFileUrlObject(inputStream);

        try {
            Client client = createClient();
            // Write your code to display the response of the operation if necessary.
            RuntimeOptions runtimeOptions = new RuntimeOptions();
            SubmitVLExtractionTaskResponse response = client.submitVLExtractionTaskAdvance(request, null, runtimeOptions);
            System.out.println(com.aliyun.teautil.Common.toJSONString(response));
            return response.getBody().getData().getTaskId();
        } catch (TeaException error) {
            // Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
            // The error message.
            System.out.println(error.getMessage());
            // Display the troubleshooting information.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
            // The error message.
            System.out.println(error.getMessage());
            // Display the troubleshooting information.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }

        return null;
    }

    static public String submitVLExtractionTask() {
        SubmitVLExtractionTaskRequest request = new SubmitVLExtractionTaskRequest();
        request.setFolderId(FOLDER_ID);
        request.setTemplateId(TEMPLATE_ID);
        request.setFileName(FILE_NAME);
        request.setFileUrl(FILE_URL);

        try {
            Client client = createClient();
            // Write your code to display the response of the operation if necessary.
            SubmitVLExtractionTaskResponse response = client.submitVLExtractionTask(request);
            System.out.println(com.aliyun.teautil.Common.toJSONString(response));
            return response.getBody().getData().getTaskId();
        } catch (TeaException error) {
            // Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
            // The error message.
            System.out.println(error.getMessage());
            // Display the troubleshooting information.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
            // The error message.
            System.out.println(error.getMessage());
            // Display the troubleshooting information.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }

        return null;
    }

    public static Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setReadTimeout(30 * 1000)
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment.
                .setAccessKeyId(ACCESS_ID)
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment.
                .setAccessKeySecret(ACCESS_KEY);

        // Endpoint, refer to https://api.aliyun.com/product/energyExpertExternal
        config.endpoint = ENDPOINT;
        return new Client(config);
    }
}

Knowledge base Q&A

Set ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET in your environment variables as authentication credentials, then follow these steps:

  1. Call GetChatFolderList to get the folderId. If no folder exists, log on to the platform to create one, submit document parsing and extraction jobs, and then start Q&A.

  2. Call CreateChatSession to create a session. Pass a userId that uniquely identifies the user — if omitted, the caller's ID is used by default.

  3. To resume a previous session, call GetChatSessionList to retrieve the sessionId.

  4. Call Chat to submit a question. Set the timeout to at least 20 seconds, as Q&A responses can take longer than standard API calls.

  5. To retrieve Q&A history, call GetChatList.

Java code reference:

package com.aliyun.aidoc.sample;

import com.aliyun.energyexpertexternal20220923.*;
import com.aliyun.energyexpertexternal20220923.models.*;
import com.aliyun.tea.*;

import java.util.List;

public class ChatSample {
    static String ACCESS_ID = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    static String ACCESS_KEY = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
    static String ENDPOINT = System.getenv("ENDPOINT");
    static String User_ID = System.getenv("User_ID");
    static String SESSION_NAME = System.getenv("SESSION_NAME");
    static String QUESTION = System.getenv("QUESTION");

    public static void main(String[] args_) throws Exception {
        String folderId = null;
        //Make sure a directory has been created on the platform, you can get the directory list through the getChatFolderList interface
        List<ChatFolderItem> folderItems = getChatFolderList();
        if (null != folderItems && folderItems.size() > 0) {
            folderId = folderItems.get(0).getFolderId();
        }
        CreateChatSessionResponseBody.CreateChatSessionResponseBodyData session = creatChatSession(folderId, User_ID, SESSION_NAME);
        String sessionId = session.getSessionId();
        //If you want to continue using historical Q&A, you need to call the session list interface to get the sessionId
        //getChatSessionList(userId);

        chat(sessionId, QUESTION);
        //You can call getChatList to get Q&A history records
        //getChatList(sessionId);

    }

    static public List<ChatFolderItem> getChatFolderList() throws Exception {
        Client client = ChatSample.createClient();

        try {
            // Write your code to display the response of the operation if necessary.
            GetChatFolderListResponse response = client.getChatFolderList();
            return response.getBody().getData();
        } catch (TeaException error) {
            // Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
            // The error message.
            System.out.println(error.getMessage());
            // Display the troubleshooting information.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
            // The error message.
            System.out.println(error.getMessage());
            // Display the troubleshooting information.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }

        return null;

    }

    static public List<GetChatSessionListResponseBody.GetChatSessionListResponseBodyDataSessionList> getChatSessionList(String userId) throws Exception {
        Client client = ChatSample.createClient();

        GetChatSessionListRequest request = new GetChatSessionListRequest();
        request.setCurrentPage(1);
        request.setPageSize(10);

        try {
            // Write your code to display the response of the operation if necessary.
            GetChatSessionListResponse response = client.getChatSessionList(request);
            return response.getBody().getData().getSessionList();
        } catch (TeaException error) {
            // Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
            // The error message.
            System.out.println(error.getMessage());
            // Display the troubleshooting information.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
            // The error message.
            System.out.println(error.getMessage());
            // Display the troubleshooting information.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }

        return null;

    }

    static public CreateChatSessionResponseBody.CreateChatSessionResponseBodyData creatChatSession(String folderId, String userId, String name) throws Exception {
        Client client = ChatSample.createClient();

        CreateChatSessionRequest request = new CreateChatSessionRequest();
        request.setFolderId(folderId);
        request.setUserId(userId);
        request.setName(name);

        try {
            // Write your code to display the response of the operation if necessary.
            CreateChatSessionResponse response = client.createChatSession(request);
            return response.getBody().getData();
        } catch (TeaException error) {
            // Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
            // The error message.
            System.out.println(error.getMessage());
            // Display the troubleshooting information.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
            // The error message.
            System.out.println(error.getMessage());
            // Display the troubleshooting information.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }

        return null;

    }

    static public void chat(String sessionId, String question) throws Exception {
        Client client = ChatSample.createClient();

        ChatRequest request = new ChatRequest();
        request.setSessionId(sessionId);
        request.setQuestion(question);

        try {
            // Write your code to display the response of the operation if necessary.
            ChatResponse response = client.chat(request);
            System.out.println(com.aliyun.teautil.Common.toJSONString(response));
        } catch (TeaException error) {
            // Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
            // The error message.
            System.out.println(error.getMessage());
            // Display the troubleshooting information.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
            // The error message.
            System.out.println(error.getMessage());
            // Display the troubleshooting information.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }

    }

    static public void getChatList(String sessionId) throws Exception {
        Client client = ChatSample.createClient();

        GetChatListRequest request = new GetChatListRequest();
        request.setCurrentPage("1");
        request.setPageSize("10");
        request.setSessionId(sessionId);

        try {
            // Write your code to display the response of the operation if necessary.
            GetChatListResponse response = client.getChatList(request);

            System.out.println(com.aliyun.teautil.Common.toJSONString(response));
        } catch (TeaException error) {
            // Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
            // The error message.
            System.out.println(error.getMessage());
            // Display the troubleshooting information.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // Handle exceptions with caution in actual business scenarios and do not ignore the exceptions in your project. In this example, exceptions are provided for reference only.
            // The error message.
            System.out.println(error.getMessage());
            // Display the troubleshooting information.
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }

    }

    public static Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setReadTimeout(30 * 1000)
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is configured in the code runtime environment.
                .setAccessKeyId(ACCESS_ID)
                // Required. Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is configured in the code runtime environment.
                .setAccessKeySecret(ACCESS_KEY);

        // Endpoint, refer to https://api.aliyun.com/product/energyExpertExternal
        config.endpoint = ENDPOINT;
        return new Client(config);
    }
}

Streaming Q&A

Use the asynchronous Java SDK for streaming Q&A.

package com.aliyun.sdk.service.energyexpertexternal20220923;

import com.alibaba.fastjson.JSON;
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.energyexpertexternal20220923.models.ChatStreamRequest;
import com.aliyun.sdk.service.energyexpertexternal20220923.models.ChatStreamResponseBody;
import darabonba.core.ResponseIterable;
import darabonba.core.ResponseIterator;
import darabonba.core.client.ClientOverrideConfiguration;

/**
 * @author daifeng.yxy 2025/6/30 10:15
 *
 */
public class ChatSample {
    static String ACCESS_ID = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
    static String ACCESS_KEY = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
    static String ENDPOINT = System.getenv("ENDPOINT");
    static String SESSION_ID = System.getenv("SESSION_ID");
    static String QUESTION = System.getenv("QUESTION");

    public static void main(String[] args) throws Exception {
        AsyncClient client = ChatSample.createClient();
        ChatStreamRequest request = ChatStreamRequest.builder()
                .sessionId(SESSION_ID)
                .question(QUESTION)
                .build();

        ResponseIterable<ChatStreamResponseBody> respStream = client.chatStreamWithResponseIterable(request);

        ResponseIterator<ChatStreamResponseBody> iterator = respStream.iterator();
        while (iterator.hasNext()) {
            System.out.println("----event----");
            ChatStreamResponseBody event = iterator.next();
            System.out.println(JSON.toJSONString(event.getData()));
        }

    }

    public static AsyncClient createClient() throws Exception {
        StaticCredentialProvider provider = StaticCredentialProvider.create(
                Credential.builder()
                        .accessKeyId(ACCESS_ID)
                        .accessKeySecret(ACCESS_KEY)
                        .build()
        );

        AsyncClient client = AsyncClient.builder()
                .credentialsProvider(provider)
                // Service-level configuration
                .serviceConfiguration(Configuration.create()
                        .setSignatureVersion(SignatureVersion.V3)
                )
                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setProtocol("HTTPS")
                                .setEndpointOverride(ENDPOINT)
                )
                .build();

        return client;
    }
}