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");
        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(
                                Message.builder()
                                        .name("小明")
                                        .content("你叫什么名字?")
                                        .role("user")
                                        .build(),
                                Message.builder()
                                        .name("小婉")
                                        .content("我叫小婉啊。")
                                        .role("assistant")
                                        .build(),
                                Message.builder()
                                        .name("小明")
                                        .content("你今年多大?")
                                        .role("user")
                                        .build(),
                                Message.builder()
                                        .name("小婉")
                                        .content("我今年17岁了。")
                                        .role("assistant")
                                        .build(),
                                // 注意,自定义角色 prompt,用户问题需放到messages最后一条
                                Message.builder()
                                        .name("小明")
                                        .content("你今年多大?")
                                        .role("user")
                                        .build()
                        )
                )
                                .context(
                        ChatContext.builder()
                                .useChatHistory(false)
                                .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(
                                Message.builder()
                                        .name("小明")
                                        .content("你叫什么名字?")
                                        .role("user")
                                        .build(),
                                Message.builder()
                                        .name("小婉")
                                        .content("我叫小婉啊。")
                                        .role("assistant")
                                        .build(),
                                Message.builder()
                                        .name("小明")
                                        .content("你今年多大?")
                                        .role("user")
                                        .build(),
                                Message.builder()
                                        .name("小婉")
                                        .content("我今年17岁了。")
                                        .role("assistant")
                                        .build(),
                                // 注意,自定义角色 prompt,用户问题需放到messages最后一条
                                Message.builder()
                                        .name("小明")
                                        .content("你今年多大?")
                                        .role("user")
                                        .build()
                        )
                )
                                .context(
                        ChatContext.builder()
                                .useChatHistory(false)
                                .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(
                                Message.builder()
                                        .name("小明")
                                        .content("你叫什么名字?")
                                        .role("user")
                                        .build(),
                                Message.builder()
                                        .name("小婉")
                                        .content("我叫小婉啊。")
                                        .role("assistant")
                                        .build(),
                                Message.builder()
                                        .name("小明")
                                        .content("你今年多大?")
                                        .role("user")
                                        .build(),
                                Message.builder()
                                        .name("小婉")
                                        .content("我今年17岁了。")
                                        .role("assistant")
                                        .build(),
                                // 注意,自定义角色 prompt,用户问题需放到messages最后一条
                                Message.builder()
                                        .name("小明")
                                        .content("你今年多大?")
                                        .role("user")
                                        .build()
                        )
                )
                                .context(
                        ChatContext.builder()
                                .useChatHistory(false)
                                .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}}:吾姓关名羽,字长生,后改云长,河东解良人也。")
                .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("fc80436eb092455fbfccd86bb51f1f80"))	//绑定知识库,需注意有权限校验,必须是调用者在星辰创建的知识库

                                .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}}:吾姓关名羽,字长生,后改云长,河东解良人也。")
                .advancedConfig(
                        CharacterAdvancedConfig.builder()
                                .isRealTime(true)
                                .isRealInfo(true)
                                .searchKeyword("关云长") // 添加搜索关键词,在搜索时,会在query词前加上该关键词,以提高搜索相关性
                                .shortTermMemoryRound(20) // 短期记忆轮数,若使用平台对话历史,可以通过该参数获取指定轮数的对话历史作为短期记忆,超过该轮数,会到长期记忆库中搜索用户query相关问题答案
                                .knowledgeBases(Lists.newArrayList("fc80436eb092455fbfccd86bb51f1f80"))	//绑定知识库,需注意有权限校验,必须是调用者在星辰创建的知识库

                                .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 = "40f70d5466e1429ba9aa755842b35d9f";
        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");
        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;
        ResultDTOBoolean response = api.delete(characterId, null);

        // 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("40f70d5466e1429ba9aa755842b35d9f")
                                .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("b886b7790f044ac087602037717f210b")
                .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());
    }
}