All Products
Search
Document Center

Intelligent Media Services:Retrieve chat history

Last Updated:Dec 08, 2025

This topic describes how to retrieve the chat history of message conversations.

Feature description

In Real-time Conversational AI, a Session ID identifies the conversational relationship between a user and an agent, ensuring every interaction is fully recorded and traceable. Using this unique identifier, the system can recognize and organize multiple turns of dialogue initiated by the same user at different times, creating a coherent chat history. You can also use the Session ID to link all chat records between a user and both A/V call agents and chatbot agents.

Retrieve chat history of message conversations

Business flow

When a user starts a new conversation with an agent, it will be associated with the same Session ID, even if the user interacts with the agent at different times or on different devices. The generation and management of the mapping between a Session ID and a user are handled by your application.

Code implementation

Alibaba Cloud provides two methods for retrieving chat history: calling the AICallKit SDK API or using the OpenAPI.

Retrieve through AICallKit SDK

  1. Generate a Session ID in your application and pass it when calling the ARTCAIChatEngine.startChat() method.

  2. Create an ARTCAIChatMessageListRequest object and set the parameters for retrieving chat history, such as start/end time, page size, page number, and sort order (ascending/descending).

  3. Call the ARTCAIChatEngine.queryMessageList() method to retrieve the chat history. Sample code:

Android
1. Create ARTCAIChatEngine object and set SessionID
// SessionID is generated by your application. If empty, userId_agentId will be used as the unique identifier.
String mSessionId = "XXX";
// User ID: the unique identifier for the user in your system.
String mUserId = "XXX";
// Chatbot agent ID. Find it in the Real-time Conversational AI console.
String mAgentId = "XXX"
ARTCAIChatEngine mChatEngine = new ARTCAIChatEngineImpl(currentContext);
mChatEngine.startChat(
                new ARTCAIChatEngine.ARTCAIChatUserInfo(mUserId, ""),
                new ARTCAIChatEngine.ARTCAIChatAgentInfo(mAgentId), mSessionId);

2. Create ARTCAIChatMessageListRequest object and set the relevant parameters for retrieving chat history.
long endTime = System.currentTimeMillis() / 1000;
ARTCAIChatEngine.ARTCAIChatMessageListRequest messageListRequest =
                    new ARTCAIChatEngine.ARTCAIChatMessageListRequest(0, endTime, 1, 10, true);

3. Call the queryMessageList method of ARTCAIChatEngine to retrieve chat history.
mChatEngine.queryMessageList(messageListRequest, new ARTCAIChatEngine.IARTCAIChatHistoryMessageCallback() {
      @Override
      public void onSuccess(List<ARTCAIChatEngine.ARTCAIChatMessage> data) {
        // On success, process the messages.
                   
      }
      @Override
      public void onFailed(ARTCAIChatEngine.ARTCAIChatError error) {
          // On failure
      }
 });  

  
iOS
1. Create ARTCAIChatEngine object
// Create engine instance
let engine: ARTCAIChatEngineInterface = {
    return ARTCAICallEngineFactory.createChatEngine()
}()

// Configure callbacks
self.engine.delegate = self


2. Set SessionID when starting a conversation.
// We recommend using the user ID from your app after login.
let userId = "xxx"
// Set deviceId.
let deviceId = UIDevice.current.identifierForVendor?.uuidString
let userInfo = ARTCAIChatUserInfo(userId, deviceId)
// Set the agent. The agentId cannot be nil.
let agentInfo = ARTCAIChatAgentInfo(agentId: "xxx")
let sessionId = "\(userInfo.userId)_\(agentInfo.agentId)"
self.engine.startChat(userInfo: userInfo, agentInfo: agentInfo, sessionId: self.sessionId)


3. Create ARTCAIChatMessageListRequest object and set the relevant parameters for retrieving chat history.
var endTime = Date().timeIntervalSince1970
if let sendTime = self.listMessage.first?.message.sendTime {
    endTime = sendTime - 0.1
}
let req = ARTCAIChatMessageListRequest(startTime: 0, endTime: endTime, pageNumber: 1, pageSize: 10, isDesc: true)

4. Call the queryMessageList method of ARTCAIChatEngine to retrieve chat history.
self.engine.queryMessageList(request: req) { msgList, error in
    if let error = error {
        // On failure
    }
    else {
        // On success, process the messages
    }
}
  
Web
// 1. Create AIChatEngine object.
const engine = new AIChatEngine();

// 2. Set SessionID when starting a conversation.
// We recommend that you use the user ID from your app after login.
const userId = 'xxx';
// Set deviceId.
const deviceId = '';
const userInfo = new AIChatUserInfo(userId, deviceId);
// Set the agent. The agentId cannot be empty.
let agentInfo = new AIChatAgentInfo('xxx');
let sessionId = `${userInfo.userId}_${agentInfo.agentId}`;
await engine.startChat(userInfo, agentInfo, sessionId);

// 3. Create ARTCAIChatMessageListRequest object and set the relevant parameters for retrieving chat history.
const endTime = Date.now();

// 4. Call the queryMessageList method of ARTCAIChatEngine to retrieve chat history.
try {
  const msgList = await engine.queryMessageList({
    startTime: 0,
    endTime: endTime,
    pageNumber: 1,
    pageSize: 10,
    isDesc: true,
  });
  // On success, process the messages.
} catch (error) {
  // On failure
}

Retrieve through OpenAPI interface

Call the ListAIAgentDialogues API to retrieve the chat history between a user and an agent.

// This file is auto-generated, don't edit it. Thanks.
package com.aliyun.rtc;

import java.util.Arrays;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.ice20201109.models.StartAIAgentInstanceResponse;
import com.aliyun.tea.*;

public class Sample {

    /**
     * <b>description</b> :
     * <p>Use your AccessKey pair to initialize the client.</p>
     * @return Client
     * 
     * @throws Exception
     */
    public static com.aliyun.ice20201109.Client createClient() throws Exception {
        // Leaking your source code may expose your AccessKey pair and compromise the security of all your resources.
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // Required. Make sure that the following environment variable is set in the code runtime environment: ALIBABA_CLOUD_ACCESS_KEY_ID.
                .setAccessKeyId("yourak")
                // Required. Make sure that the following environment variable is set in the code runtime environment: ALIBABA_CLOUD_ACCESS_KEY_SECRET.
                .setAccessKeySecret("yoursk");
        // For Endpoint, refer to https://api.alibabacloud.com/product/ICE
        config.endpoint = "ice.cn-shanghai.aliyuncs.com";
        return new com.aliyun.ice20201109.Client(config);
    }


    private static void listAIAgentDialogues() throws Exception {
        com.aliyun.ice20201109.Client client =  createClient();

        com.aliyun.ice20201109.models.ListAIAgentDialoguesRequest request = new com.aliyun.ice20201109.models.ListAIAgentDialoguesRequest()
            .setSessionId("test")
            .setStartTime(0L)
            .setEndTime(100000000L);

            try {
                com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
                
                client.listAIAgentDialoguesWithOptions(request, runtime);
            } catch (TeaException error) {
                System.out.println(error.getMessage());
                com.aliyun.teautil.Common.assertAsString(error.message);
            } catch (Exception _error) {
                TeaException error = new TeaException(_error.getMessage(), _error);
                System.out.println(error.getMessage());
                com.aliyun.teautil.Common.assertAsString(error.message);
            }   
    }

    
    public static void main(String[] args) throws Exception {
        listAIAgentDialogues();
    }
}