Java SDK

更新时间:

环境依赖

  1. Java 1.8+

  2. Maven/Gradle

安装

Maven用户

<dependency>
    <groupId>com.alibaba.xingchen</groupId>
    <artifactId>xingchen-java-client</artifactId>
    <version>1.1.1</version>
    <scope>compile</scope>
</dependency>

Gradle用户

compile "com.alibaba.xingchen:xingchen-java-client:1.1.1"

快速开始

import com.alibaba.xingchen.ApiClient;
import com.alibaba.xingchen.ApiException;
import com.alibaba.xingchen.api.ChatApiSub;
import com.alibaba.xingchen.auth.HttpBearerAuth;
import com.alibaba.xingchen.model.*;
import io.reactivex.Flowable;

import java.util.Arrays;

public class ChatApiSseExample {

    public static void main(String[] args) throws ApiException {
        ChatApiSub api = new ChatApiSub();
        ApiClient apiClient = new ApiClient();
        apiClient.setBasePath("https://nlp.aliyuncs.com");
        //开启SSE输出
        apiClient.addDefaultHeader("X-DashScope-SSE", "enable"); 

        // Configure HTTP bearer authorization: Authorization
        HttpBearerAuth authorization = (HttpBearerAuth) apiClient.getAuthentication("Authorization");
        authorization.setBearerToken("{API-KEY}");
        api.setApiClient(apiClient);

        Flowable<ChatResult> response =  api.streamOut(buildChatReqParams());

        response.blockingForEach(message -> {
            System.out.println(message.getChoices().get(0).getMessages().get(0).getContent());
        });
    }

    private static ChatReqParams buildChatReqParams() {
        return ChatReqParams.builder()
                .botProfile(
                        CharacterKey.builder()
                                // 星尘预制角色
                                .characterId("40f70d5466e1429ba9aa755842b35d9f")
                                .name("小婉")
                                .build()
                )
                .modelParameters(
                        ModelParameters.builder()
                                .seed(1683806810L)
                                .incrementalOutput(false)
                                .build()
                )
                .userProfile(
                        UserProfile.builder()
                                .userId("1234")
                                .build()
                )
                .messages(
                        Arrays.asList(
                                // 注意,自定义角色 prompt,用户问题需放到messages最后一条
                                Message.builder()
                                        .name("小明")
                                        .content("你今年多大?")
                                        .role("user")
                                        .build()
                        )
                )
                .context(
                        ChatContext.builder()
                                // 使用平台对话历史,messages 只能包含用户提问消息,不能包含其他信息
                                .useChatHistory(true) 
                                .build()
                )
                .build();
    }
}

固定角色对话

流式输出

import com.alibaba.xingchen.ApiClient;
import com.alibaba.xingchen.ApiException;
import com.alibaba.xingchen.api.ChatApiSub;
import com.alibaba.xingchen.auth.HttpBearerAuth;
import com.alibaba.xingchen.model.*;
import io.reactivex.Flowable;

import java.util.Arrays;

public class ChatApiSseExample {

    public static void main(String[] args) throws ApiException {
        ChatApiSub api = new ChatApiSub();
        ApiClient apiClient = new ApiClient();
        apiClient.setBasePath("https://nlp.aliyuncs.com");
        apiClient.addDefaultHeader("X-DashScope-SSE", "enable"); // 开启SSE输出

        // Configure HTTP bearer authorization: Authorization
        HttpBearerAuth authorization = (HttpBearerAuth) apiClient.getAuthentication("Authorization");
        authorization.setBearerToken("{API-KEY}");
        api.setApiClient(apiClient);

        Flowable<ChatResult> response =  api.streamOut(buildChatReqParams());

        response.blockingForEach(message -> {
            System.out.println(message.getChoices().get(0).getMessages().get(0).getContent());
        });
    }

    private static ChatReqParams buildChatReqParams() {
        return ChatReqParams.builder()
                .botProfile(
                        CharacterKey.builder()
                                // 星尘预制角色
                                .characterId("40f70d5466e1429ba9aa755842b35d9f")
                                .name("小婉")
                                .build()
                )
                .modelParameters(
                        ModelParameters.builder()
                                .seed(1683806810L)
                                .incrementalOutput(false)
                                .build()
                )
                .userProfile(
                        UserProfile.builder()
                                .userId("1234")
                                .build()
                )
                .messages(
                        Arrays.asList(
                                // 注意,自定义角色 prompt,用户问题需放到messages最后一条
                                Message.builder()
                                        .name("小明")
                                        .content("你今年多大?")
                                        .role("user")
                                        .build()
                        )
                )
                .context(
                        ChatContext.builder()
                                .useChatHistory(true)
                                .build()
                )
                .build();
    }
}

非增量输出

我今年
我今年17岁了,很快就要
我今年17岁了,很快就要步入大学了。
我今年17岁了,很快就要步入大学了。

增量输出

我今年
17岁了,很快就要
步入大学了。

非流式输出

package chat;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.xingchen.ApiClient;
import com.alibaba.xingchen.ApiException;
import com.alibaba.xingchen.api.ChatApiSub;
import com.alibaba.xingchen.auth.HttpBearerAuth;
import com.alibaba.xingchen.model.*;
import io.reactivex.Flowable;

import java.util.Arrays;

public class ChatApiExample {

    public static void main(String[] args) throws ApiException {
        ChatApiSub api = new ChatApiSub();
        ApiClient apiClient = new ApiClient();
        apiClient.setBasePath("https://nlp.aliyuncs.com");
        apiClient.addDefaultHeader("X-DashScope-SSE", "disable");

        // Configure HTTP bearer authorization: Authorization
        HttpBearerAuth authorization = (HttpBearerAuth) apiClient.getAuthentication("Authorization");
        authorization.setBearerToken("{API-KEY}");
        api.setApiClient(apiClient);

        ResultDTOChatResult result = api.chat(buildChatReqParams());

        System.out.println(JSONObject.toJSONString(result));

    }

    private static ChatReqParams buildChatReqParams() {
        return ChatReqParams.builder()
                .botProfile(
                        CharacterKey.builder()
                                // 星尘预制角色
                                .characterId("40f70d5466e1429ba9aa755842b35d9f")
                                .name("小婉")
                                .build()
                )
                .modelParameters(
                        ModelParameters.builder()
                                .seed(1683806810L)
                                .build()
                )
                .userProfile(
                        UserProfile.builder()
                                .userId("1234")
                                .build()
                )
                .messages(
                        Arrays.asList(
                                // 注意,自定义角色 prompt,用户问题需放到messages最后一条
                                Message.builder()
                                        .name("小明")
                                        .content("你今年多大?")
                                        .role("user")
                                        .build()
                        )
                )
                .context(
                        ChatContext.builder()
                                .useChatHistory(true) // 使用平台对话历史,messages 只能包含用户提问消息,不能包含其他信息
                                .build()
                )
                .build();
    }
}
{
    "code": 200,
    "data":
    {
        "choices":
        [
            {
                "messages":
                [
                    {
                        "content": "我今年17岁了,很快就要步入大学了。",
                        "finishReason": "stop",
                        "role": "assistant"
                    }
                ],
                "stopReason": "stop"
            }
        ],
        "context":
        {
            "chatId": "aa6410e37eff4bcfb8e5390143380416",
            "chatRoomId": 56127,
            "enableDataInspection": false,
            "messageId": "61ec58fcca3b40f4a220e4cfe99beafa",
            "modelRequestId": "f90ae919-e7aa-937b-99ec-7e449a3ff17f",
            "requestId": "b035feb1-db2c-47e1-a0f6-9d03a4571a22",
            "sessionId": "a3f6b6b772584406b4715705b781957c"
        },
        "requestId": "b035feb1-db2c-47e1-a0f6-9d03a4571a22",
        "usage":
        {
            "inputTokens": 371,
            "outputTokens": 17,
            "userTokens": 6
        }
    },
    "requestId": "b035feb1-db2c-47e1-a0f6-9d03a4571a22",
    "success": true
}

角色管理

准备

import com.alibaba.xingchen.ApiClient;
import com.alibaba.xingchen.auth.HttpBearerAuth;

public class TestBaseV2 {
    public static String baseUrl = "https://nlp.aliyuncs.com";

    public ApiClient initClient() {

        ApiClient defaultClient = new ApiClient();
        defaultClient.setBasePath(baseUrl);

        // Configure HTTP bearer authorization: Authorization
        HttpBearerAuth authorization = (HttpBearerAuth) defaultClient.getAuthentication("Authorization");
        authorization.setBearerToken("{API-KEY}");

        return defaultClient;
    }
}

创建角色

import com.alibaba.fastjson.JSONObject;
import com.alibaba.xingchen.ApiClient;
import com.alibaba.xingchen.ApiException;
import com.alibaba.xingchen.api.CharacterApiSub;
import com.alibaba.xingchen.model.*;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class CharacterApiTest extends TestBaseV2 {
    private CharacterApiSub api = new CharacterApiSub();
    @Before
    public void init() {
        ApiClient apiClient = super.initClient();
        api.setApiClient(apiClient);
    }


    /**
     * 创建角色
     *
     * 基于角色名称、人设和对话示例定义角色,并返回角色ID
     */
    @Test
    public void createTest() throws ApiException {
        CharacterCreateDTO characterCreateDTO = CharacterCreateDTO.builder()
                .name("满腔忠义的关云长")
                .type("virtual")
                .avatar(
                        FileInfoVO.builder()
                                .fileUrl("https://gw.alicdn.com/imgextra/i3/O1CN01iVuwX11jCXzNxM4v9_!!6000000004512-0-tps-3000-2920.jpg")
                                .filename("关云长.jpg")
                                .build()
                )
                .introduction("满腔忠义的关云长")
                .traits("请在对话时尽可能的展现你的性格、感情, 用文言文回答, 并使用古人的语气和用词。")
                .openingLine("我是「关云长」,很高心与你玩游戏")
                .basicInformation("我们来玩一个角色扮演的游戏, 你是「满腔忠义的关云长」。")
                .chatExample("{{user}}:敢问阁下尊姓大名。\\n{{char}}:吾姓关名羽,字长生,后改云长,河东解良人也。")
        .roleTypes(Arrays.asList("三国"))
                .permConfig(
                        CharacterPermissionConfig.builder()
                                .allowApi(0)
                                .allowChat(0)
                                .isPublic(0)
                                .build()
                )
                .advancedConfig(
                        CharacterAdvancedConfig.builder()
                                .isRealTime(true)
                                .isRealInfo(true)
                                .searchKeyword("关云长") // 添加搜索关键词,在搜索时,会在query词前加上该关键词,以提高搜索相关性
                                .shortTermMemoryRound(20) // 短期记忆轮数,若使用平台对话历史,可以通过该参数获取指定轮数的对话历史作为短期记忆,超过该轮数,会到长期记忆库中搜索用户query相关问题答案
                                .knowledgeBases(Lists.newArrayList("fc80436eb092455fbxxxxx"))	//绑定知识库,需注意有权限校验,必须是调用者在星辰创建的知识库
                                .platformPlugins(
                                        Lists.newArrayList(
                                               TextToImagePlugin.builder().enabled(true).imageStyle("auto").positiveDesc("二次元,彩色").negativeDesc("多头多手指,多手多脚").build(),
                                               RejectAnswerPlugin.builder().enabled(true)
                                                       .rejectConditions(
                                                               Lists.newArrayList(
                                                                       RejectCondition.builder().enabled(true).conditionType("reject_rule").keywords(Lists.newArrayList(Keyword.builder().value("test").build())).build(),
                                                                       RejectCondition.builder().enabled(true).conditionType("passive_rule").keywords(Lists.newArrayList(Keyword.builder().value("test").build())).build(),
                                                                       RejectCondition.builder().enabled(true).conditionType("knowledge_domain_rule").subRejectCondition(
                                                                               RejectCondition.builder().enabled(true).conditionType("ancient").keywords(Lists.newArrayList(Keyword.builder().value("明朝").build())).build()
                                                                       ).build()
                                                               )
                                                       )
                                                       .build()
                                        )
                                )
                                .build()
                )
                .build();
        ResultDTOCharacterKey response = api.create(characterCreateDTO);
        System.out.println(JSONObject.toJSONString(response));
        Assert.assertTrue(response.getSuccess());
    }
}

更新角色

import com.alibaba.fastjson.JSONObject;
import com.alibaba.xingchen.ApiClient;
import com.alibaba.xingchen.ApiException;
import com.alibaba.xingchen.api.CharacterApiSub;
import com.alibaba.xingchen.model.*;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class CharacterApiTest extends TestBaseV2 {
    private CharacterApiSub api = new CharacterApiSub();
    @Before
    public void init() {
        ApiClient apiClient = super.initClient();
        api.setApiClient(apiClient);
    }

    /**
     * 更新角色信息
     *
     * 必须字段:characterId。返回成功或失败。
     *
     */
    @Test
    public void updateTest() throws ApiException {
        CharacterUpdateDTO characterUpdateDTO = CharacterUpdateDTO.builder()
                .characterId("346a45cbb8674cbca0f6d155762e56fb")
                .name("满腔忠义的关云长2")
                .type("virtual")
                .avatar(
                        FileInfoVO.builder()
                                .fileUrl("https://gw.alicdn.com/imgextra/i3/O1CN01iVuwX11jCXzNxM4v9_!!6000000004512-0-tps-3000-2920.jpg")
                                .filename("关云长.jpg")
                                .build()
                )
                .introduction("满腔忠义的关云长2")
                .traits("请在对话时尽可能的展现你的性格、感情, 用文言文回答, 并使用古人的语气和用词。")
                .openingLine("我是「关云长」,很高心与你玩游戏")
                .basicInformation("我们来玩一个角色扮演的游戏, 你是「满腔忠义的关云长」。")
                .chatExample("{{user}}:敢问阁下尊姓大名。\\n{{char}}:吾姓关名羽,字长生,后改云长,河东解良人也。")
                .roleTypes(Arrays.asList("三国"))
                .advancedConfig(
                        CharacterAdvancedConfig.builder()
                                .isRealTime(true)
                                .isRealInfo(true)
                                .searchKeyword("关云长") // 添加搜索关键词,在搜索时,会在query词前加上该关键词,以提高搜索相关性
                                .shortTermMemoryRound(20) // 短期记忆轮数,若使用平台对话历史,可以通过该参数获取指定轮数的对话历史作为短期记忆,超过该轮数,会到长期记忆库中搜索用户query相关问题答案
                                .knowledgeBases(Lists.newArrayList("fc80436eb092455fbfccd86bb51f1f80"))	//绑定知识库,需注意有权限校验,必须是调用者在星辰创建的知识库
                                .platformPlugins(
                                        Lists.newArrayList(
                                               TextToImagePlugin.builder().enabled(true).imageStyle("auto").positiveDesc("二次元,彩色").negativeDesc("多头多手指,多手多脚").build(),
                                               RejectAnswerPlugin.builder().enabled(true)
                                                       .rejectConditions(
                                                               Lists.newArrayList(
                                                                       RejectCondition.builder().enabled(true).conditionType("reject_rule").keywords(Lists.newArrayList(Keyword.builder().value("test").build())).build(),
                                                                       RejectCondition.builder().enabled(true).conditionType("passive_rule").keywords(Lists.newArrayList(Keyword.builder().value("test").build())).build(),
                                                                       RejectCondition.builder().enabled(true).conditionType("knowledge_domain_rule").subRejectCondition(
                                                                               RejectCondition.builder().enabled(true).conditionType("ancient").keywords(Lists.newArrayList(Keyword.builder().value("明朝").build())).build()
                                                                       ).build()
                                                               )
                                                       )
                                                       .build()
                                        )
                                )
                                .build()
                )
                .build();
        ResultDTOBoolean response = api.update(characterUpdateDTO);
        System.out.println(JSONObject.toJSONString(response));
        Assert.assertTrue(response.getSuccess());
    }
}

角色详情

import com.alibaba.fastjson.JSONObject;
import com.alibaba.xingchen.ApiClient;
import com.alibaba.xingchen.ApiException;
import com.alibaba.xingchen.api.CharacterApiSub;
import com.alibaba.xingchen.model.*;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class CharacterApiTest extends TestBaseV2 {
    private CharacterApiSub api = new CharacterApiSub();
    @Before
    public void init() {
        ApiClient apiClient = super.initClient();
        api.setApiClient(apiClient);
    }

    /**
     * 角色详情
     *
     * 获取角色详细信息
     */
    @Test
    public void characterDetailsTest() throws ApiException {
        String characterId = "40f70d5466e1429ba9aa7xxxxxxxxxxxxxx";
        ResultDTOCharacterDTO response = api.characterDetails(characterId, 1);
        System.out.println(response.getData());
        Assert.assertTrue(response.getSuccess());

    }
}

角色查询

import com.alibaba.fastjson.JSONObject;
import com.alibaba.xingchen.ApiClient;
import com.alibaba.xingchen.ApiException;
import com.alibaba.xingchen.api.CharacterApiSub;
import com.alibaba.xingchen.model.*;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class CharacterApiTest extends TestBaseV2 {
    private CharacterApiSub api = new CharacterApiSub();
    @Before
    public void init() {
        ApiClient apiClient = super.initClient();
        api.setApiClient(apiClient);
    }

    @Test
    public void searchTest() throws ApiException {
        CharacterQueryDTO characterQueryDTO = new CharacterQueryDTO();
        characterQueryDTO.setPageNum(1L);
        characterQueryDTO.setPageSize(10L);
        CharacterQueryWhere where=new CharacterQueryWhere();

        //查询我的角色
        where.setScope("my");
        //查询预置角色
//        where.setScope("pre_configured");
        //查询标签下的角色
        //where.setRoleTypes(Arrays.asList("三国"));
        characterQueryDTO.setWhere(where);
        ResultDTOPageResultCharacterDTO response = api.search(characterQueryDTO);
        System.out.println(JSONObject.toJSONString(response));
        Assert.assertTrue(response.getSuccess());
    }

}

删除角色

import com.alibaba.fastjson.JSONObject;
import com.alibaba.xingchen.ApiClient;
import com.alibaba.xingchen.ApiException;
import com.alibaba.xingchen.api.CharacterApiSub;
import com.alibaba.xingchen.model.*;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class CharacterApiTest extends TestBaseV2 {
    private CharacterApiSub api = new CharacterApiSub();
    @Before
    public void init() {
        ApiClient apiClient = super.initClient();
        api.setApiClient(apiClient);
    }

    /**
     * 删除角色
     *
     * (逻辑)删除 character。返回成功或失败。
     */
    @Test
    public void deleteTest() throws ApiException {
        String characterId = null;
        Integer version = null;
        ResultDTOBoolean response = api.delete(characterId, version);

        // TODO: test validations
    }
}

对话历史

准备

import com.alibaba.xingchen.ApiClient;
import com.alibaba.xingchen.auth.HttpBearerAuth;

public class TestBaseV2 {
    public static String baseUrl = "https://nlp.aliyuncs.com";

    public ApiClient initClient() {

        ApiClient defaultClient = new ApiClient();
        defaultClient.setBasePath(baseUrl);

        // Configure HTTP bearer authorization: Authorization
        HttpBearerAuth authorization = (HttpBearerAuth) defaultClient.getAuthentication("Authorization");
        authorization.setBearerToken("{API-KEY}");

        return defaultClient;
    }
}

对话历史查询

import com.alibaba.fastjson.JSONObject;
import com.alibaba.xingchen.ApiClient;
import com.alibaba.xingchen.ApiException;
import com.alibaba.xingchen.api.ChatMessageApiSub;
import com.alibaba.xingchen.enums.Version;
import com.alibaba.xingchen.model.*;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

import java.util.Date;

/**
 * API tests for ChatMessageApiSub
 */
@Ignore
public class ChatMessageApiTest extends TestBaseV2 {

    private  ChatMessageApiSub api = new ChatMessageApiSub();
    @Before
    public void init() {
        ApiClient apiClient = super.initClient();
        api.setApiClient(apiClient);
    }

    /**
     * 对话历史
     *
     *  用户与角色的对话历史查询: -
     *  where: 查询条件:必传
     *  - characterId: 必传
     *  - userId: 必传
     *  - startTime:开始时间戳,选传
     *  - endTime: 结束时间戳,选传
     *  - sessionId: 会话ID,宣传
     *  - 排序:必传,默认根据创建时间倒排
     *  - pageSize: 分页大小,选传,默认10
     *  - pageNumber: 分页页码,宣传,默认1
     */
    @Test
    public void chatHistoriesTest() throws ApiException {
        ChatHistoryQueryDTO chatHistoryQueryDTO = ChatHistoryQueryDTO.builder()
                .where(
                        ChatHistoryQueryWhere.builder()
                                .characterId("40f70d5466e1429bxxxxxxxxxxxxxxxx")
                                .bizUserId("1234")
                                .endTime(new Date().getTime())
                                .build()
                )
                .pageSize(10)
                .build();
        ResultDTOPageResultChatMessageDTO response = api.chatHistories(chatHistoryQueryDTO);
        System.out.println(JSONObject.toJSONString(response));
        Assert.assertTrue(response.getSuccess());
    }
}

对话历史评价

import com.alibaba.fastjson.JSONObject;
import com.alibaba.xingchen.ApiClient;
import com.alibaba.xingchen.ApiException;
import com.alibaba.xingchen.api.ChatMessageApiSub;
import com.alibaba.xingchen.enums.Version;
import com.alibaba.xingchen.model.*;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

import java.util.Date;


@Ignore
public class ChatMessageApiTest extends TestBaseV2 {

    private  ChatMessageApiSub api = new ChatMessageApiSub();
    @Before
    public void init() {
        ApiClient apiClient = super.initClient();
        api.setApiClient(apiClient);
    }


    /**
     * 消息评分
     *
     *  评分请求参数: 
     * - 消息ID:必传 
     * - 评分:必传,整型,[0-5]
     *
     */
    @Test
    public void rateMessageTest() throws ApiException {
        MessageRatingRequest messageRatingRequest = MessageRatingRequest.builder()
                .messageId("40f70d5466e1429ba9aa755842b35d9f")
                .rating(0)
                .build();
        ResultDTOBoolean response = api.rateMessage(messageRatingRequest);
        Assert.assertTrue(response.getSuccess());
    }
}

系统推荐

import com.alibaba.fastjson.JSONObject;
import com.alibaba.xingchen.ApiClient;
import com.alibaba.xingchen.ApiException;
import com.alibaba.xingchen.api.ChatMessageApiSub;
import com.alibaba.xingchen.enums.Version;
import com.alibaba.xingchen.model.*;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

import java.util.Date;

@Ignore
public class ChatMessageApiTest extends TestBaseV2 {

    private  ChatMessageApiSub api = new ChatMessageApiSub();
    @Before
    public void init() {
        ApiClient apiClient = super.initClient();
        api.setApiClient(apiClient);
    }

    /**
     * 系统提醒
     * 系统自动以某个用户的名义,向指定角色发起对话
     */
    @Test
    public void sysReminderTest() throws ApiException {
        SysReminderRequest sysReminderRequest = new SysReminderRequest();
        sysReminderRequest.setCharacterId("40f70d5466e1429ba9aa755842b35d9f");
        sysReminderRequest.setContent("你在干嘛?");
        sysReminderRequest.setBizUserId("fcf76e7b02914fa0b321cbf5662f3385");
        ResultDTOBoolean response = api.sysReminder(sysReminderRequest);
        System.out.println(response);
        Assert.assertTrue(response.getSuccess());
    }
}

重置对话(清除上下文)

import com.alibaba.fastjson.JSONObject;
import com.alibaba.xingchen.ApiClient;
import com.alibaba.xingchen.ApiException;
import com.alibaba.xingchen.api.ChatMessageApiSub;
import com.alibaba.xingchen.enums.Version;
import com.alibaba.xingchen.model.*;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

import java.util.Date;

@Ignore
public class ChatMessageApiTest extends TestBaseV2 {

    private  ChatMessageApiSub api = new ChatMessageApiSub();
    @Before
    public void init() {
        ApiClient apiClient = super.initClient();
        api.setApiClient(apiClient);
    }

    /**
     * 重置对话
     * 使用平台历史时,可通过该接口重置历史对话,开启新会话
     */
    @Test
    public void resetChatTest() throws ApiException {
        ApiResponse<ResultDTOBoolean> response = api.resetChatHistory(
                ChatResetRequest.builder()
                        .userId("12345")
                        .characterId("40f70d5xxxxxxxxxxx")
                        .build()
        );
        System.out.println(response.getData());
    }
}

其他

准备

import com.alibaba.xingchen.ApiClient;
import com.alibaba.xingchen.auth.HttpBearerAuth;

public class TestBaseV2 {
    public static String baseUrl = "https://nlp.aliyuncs.com";

    public ApiClient initClient() {

        ApiClient defaultClient = new ApiClient();
        defaultClient.setBasePath(baseUrl);

        // Configure HTTP bearer authorization: Authorization
        HttpBearerAuth authorization = (HttpBearerAuth) defaultClient.getAuthentication("Authorization");
        authorization.setBearerToken("{API-KEY}");

        return defaultClient;
    }
}

角色描述自动生成

import com.alibaba.fastjson.JSONObject;
import com.alibaba.xingchen.ApiClient;
import com.alibaba.xingchen.ApiException;
import com.alibaba.xingchen.api.CharacterApiSub;
import com.alibaba.xingchen.model.CharacterDescGeneratedRequest;
import com.alibaba.xingchen.model.ModelParameters;
import com.alibaba.xingchen.model.ResultDTOCharacterDescDTO;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;


public class CharacterApiTest extends TestBaseV2 {
    private CharacterApiSub api = new CharacterApiSub();

    @Before
    public void init() {
        ApiClient apiClient = super.initClient();
        api.setApiClient(apiClient);
    }

    @Test
    public void autoGenerateDescTest() throws ApiException {
                CharacterDescGeneratedRequest request = CharacterDescGeneratedRequest.builder()
                .type("file")
                .fileName("test.txt")
                .fileUrl("https://lang.alicdn.com/xingchen/guanyu.txt")
                .modelParameter(ModelParameters.builder().modelName("xingchen-base").build()).build();
        ResultDTOCharacterDescDTO response = api.autoGenerateDesc(request);
        System.out.println(JSONObject.toJSONString(response));
        Assert.assertTrue(response.getSuccess());
    }
}

excel转docx文件上传

import com.alibaba.fastjson.JSONObject;
import com.alibaba.xingchen.ApiClient;
import com.alibaba.xingchen.ApiException;
import com.alibaba.xingchen.api.CommonApiSub;
import com.alibaba.xingchen.model.FileConvertRequest;
import com.alibaba.xingchen.model.ResultDTOFileConvertDTO;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

@Ignore
public class CommonApiTest extends TestBaseV2 {

    private CommonApiSub api = new CommonApiSub();

    @Before
    public void init() {
        ApiClient apiClient = super.initClient();
        api.setApiClient(apiClient);
    }

    @Test
    public void fileConvertTest() throws ApiException {
        FileConvertRequest request = FileConvertRequest.builder().type("excelToDocx").sourceUrl("https://lang.alicdn.com/xingchen/%E6%B5%8B%E8%AF%95.xlsx").build();
        ResultDTOFileConvertDTO response = api.fileConvert(request);
        Assert.assertTrue(response.getSuccess());
        System.out.println(JSONObject.toJSONString(response));
    }
}

excel转docx文件结果下载

import com.alibaba.fastjson.JSONObject;
import com.alibaba.xingchen.ApiClient;
import com.alibaba.xingchen.ApiException;
import com.alibaba.xingchen.api.CommonApiSub;
import com.alibaba.xingchen.model.ResultDTOFileConvertDTO;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

@Ignore
public class CommonApiTest extends TestBaseV2 {

    private CommonApiSub api = new CommonApiSub();

    @Before
    public void init() {
        ApiClient apiClient = super.initClient();
        api.setApiClient(apiClient);
    }

    @Test
    public void fileConvertResultTest() throws ApiException {
        ResultDTOFileConvertDTO result = api.fileConvertResult(66633L);
        Assert.assertTrue(result.getSuccess());
        System.out.println(JSONObject.toJSONString(result));
    }
}

终止对话

import com.alibaba.fastjson.JSONObject;
import com.alibaba.xingchen.ApiClient;
import com.alibaba.xingchen.ApiException;
import com.alibaba.xingchen.api.ChatApiSub;
import com.alibaba.xingchen.enums.Version;
import com.alibaba.xingchen.model.ResultDTOBoolean;
import com.alibaba.xingchen.model.StopChatRequest;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;


public class ChatApiTest extends TestBaseV2 {

    private ChatApiSub api = new ChatApiSub();

    @Before
    public void init() {
        ApiClient apiClient = super.initClient();
        api.setApiClient(apiClient);
        api.setVersion(Version.v2);
    }

    @Test
    public void testStopChat() throws ApiException {
        ResultDTOBoolean response = api.stopChat(StopChatRequest.builder().requestId("0b14c2a9170381823062xxxxxxxxxxx").content("测试终止对话").build());
        Assert.assertTrue(response.getSuccess());
        System.out.println(JSONObject.toJSONString(response));
    }
}

轮询获取图片

import com.alibaba.fastjson.JSONObject;
import com.alibaba.xingchen.ApiClient;
import com.alibaba.xingchen.ApiException;
import com.alibaba.xingchen.api.ChatMessageApiSub;
import com.alibaba.xingchen.model.ResultDTOPollingImageDetailDTO;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;


@Ignore
public class ChatMessageApiTest extends TestBaseV2 {

    private  ChatMessageApiSub api = new ChatMessageApiSub();
    @Before
    public void init() {
        ApiClient apiClient = super.initClient();
        api.setApiClient(apiClient);
    }

    
    @Test
    public void pollingImageDetailTest() throws ApiException {
        ResultDTOPollingImageDetailDTO response = api.pollingImageDetail("dd5a632b6ec748fexxxxxxx", "165xxxx");
        Assert.assertTrue(response.getSuccess());
        System.out.println(JSONObject.toJSONString(response));
    }
}