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"

非固定角色对话

流式调用

package chat;

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 com.alibaba.xingchen.model.ext.chat.ChatSampleItem;
import io.reactivex.Flowable;

import java.util.Arrays;

/**
 * @author zhiyong.***@alibaba-inc.com
 * @date 2023/10/17 11:26 AM
 * 非固定角色调用
 */
public class ChatApiSseExample2 {

    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");

        // 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()
                                // 星尘预制角色
                                .name("小婉")
                                .content("【你的人设】\n")
                                .traits("按照古代风格对话")
                                .build()
                )
                .modelParameters(
                        ModelParameters.builder()
                                .seed(1683806810L)
                                .topP(0.95)
                                .temperature(0.92)
                                .incrementalOutput(false)
                                .build()
                )
                .userProfile(
                        UserProfile.builder()
                                .userId("1234")
                                .build()
                )
                .sampleMessages(
                        Arrays.asList(
                                ChatSampleItem.builder()
                                        .name("小明")
                                        .role("user")
                                        .content("你在干嘛啊?")
                                        .build(),
                                ChatSampleItem.builder()
                                        .name("小婉")
                                        .role("assistant")
                                        .content("在想你啊~你呢?")
                                        .build(),
                                ChatSampleItem.builder()
                                        .name("小明")
                                        .role("user")
                                        .content("我在吃饭呢")
                                        .build(),
                                ChatSampleItem.builder()
                                        .name("小婉")
                                        .role("assistant")
                                        .content("我也是!你看我在吃沙拉~")
                                        .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()
                        )
                )
                .memory(
                        Memory.builder()
                                .summaries(Arrays.asList("user和assistant计划一起去打篮球"))
                                .originals(Arrays.asList(
                                                Message.builder()
                                                        .role("user")
                                                        .content("你叫什么名字")
                                                        .name("小明")
                                                        .build(),
                                                Message.builder()
                                                        .role("assistant")
                                                        .content("我叫小婉啊。").
                                                        name("小婉")
                                                        .build()
                                        )
                                )
                                .tags(Arrays.asList(
                                                ExtractData.builder()
                                                        .role("user")
                                                        .value(Arrays.asList("武术家"))
                                                        .key("职业")
                                                        .build(),
                                                ExtractData.builder()
                                                        .role("user")
                                                        .value(Arrays.asList("武术"))
                                                        .key("喜欢")
                                                        .build()
                                        )
                                )
                                .build()
                )
                .advancedSettings(
                        AdvancedSettings.builder()
                                .enableWebSearch(true)
                                .searchEnhancedKeyword("网络搜索关键字")
                                .enableCharacterKbSearch(true)
                                .knowledgeBases(Arrays.asList("fc80436eb092455fbfccd86bb51f1f80"))  //选择知识库,需注意有权限校验,必须是调用者在星辰创建的知识库
                                .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 com.alibaba.xingchen.model.ext.chat.ChatSampleItem;

import java.util.Arrays;

/**
 * @author zhiyong.***@alibaba-inc.com
 * @date 2023/10/17 11:26 AM
 * 非固定角色调用
 */
public class ChatApiExample2 {

    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()
                                // 星尘预制角色
                                .name("小婉")
                                .content("【你的人设】\n")
                                .build()
                )
                .modelParameters(
                        ModelParameters.builder()
                                .seed(1683806810L)
                                .topP(0.95)
                                .temperature(0.92)
                                .build()
                )
                .userProfile(
                        UserProfile.builder()
                                .userId("1234")
                                .build()
                )
                .sampleMessages(
                        Arrays.asList(
                                ChatSampleItem.builder()
                                        .name("小明")
                                        .role("user")
                                        .content("你在干嘛啊?")
                                        .build(),
                                ChatSampleItem.builder()
                                        .name("小婉")
                                        .role("assistant")
                                        .content("在想你啊~你呢?")
                                        .build(),
                                ChatSampleItem.builder()
                                        .name("小明")
                                        .role("user")
                                        .content("我在吃饭呢")
                                        .build(),
                                ChatSampleItem.builder()
                                        .name("小婉")
                                        .role("assistant")
                                        .content("我也是!你看我在吃沙拉~")
                                        .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()
                        )
                )
                .advancedSettings(
                        AdvancedSettings.builder()
                                .enableWebSearch(true)
                                .searchEnhancedKeyword("网络搜索关键字")
                                .enableCharacterKbSearch(true)
                                .knowledgeBases(Arrays.asList("fc80436eb092455fbfccd86bb51f1f80"))  //选择知识库,需注意有权限校验,必须是调用者在星辰创建的知识库
                                .build()
                )
                .build();
    }
}

{
        "code": 200,
        "data":
        {
        "choices":
        [
        {
        "messages":
        [
        {
        "content": "我今年17岁了,是国家美术学院的大一学生。",
        "finishReason": "stop",
        "role": "assistant"
        }
        ],
        "stopReason": "stop"
        }
        ],
        "context":
        {
        "modelRequestId": "1cfac470-9c1d-9aa9-8a29-53abd7c6a6eb",
        "requestId": "1d251d0d-4069-49c6-a907-9b2b31f13963"
        },
        "requestId": "1d251d0d-4069-49c6-a907-9b2b31f13963",
        "usage":
        {
        "inputTokens": 1532,
        "outputTokens": 20,
        "userTokens": 6
        }
        },
        "requestId": "1d251d0d-4069-49c6-a907-9b2b31f13963",
        "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;
    }
}

kv抽取

import com.alibaba.fastjson.JSONObject;
import com.alibaba.xingchen.ApiClient;
import com.alibaba.xingchen.ApiException;
import com.alibaba.xingchen.api.ChatExtractMessageApiSub;
import com.alibaba.xingchen.model.*;
import com.google.common.collect.Lists;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

@Ignore
public class ChatExtractMessageApiTest extends TestBaseV2 {

    private ChatExtractMessageApiSub api = new ChatExtractMessageApiSub();

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

  
    @Test
    public void extractKVTest() throws ApiException {
        ExtractMemoryRequest request = ExtractMemoryRequest.builder()
                .messages(Lists.newArrayList(
                        Message.builder().content("你好").role("user").build(),
                        Message.builder().content("你好呀").role("assistant").build(),
                        Message.builder().content("我们喜欢打篮球,你呢").role("user").build(),
                        Message.builder().content("我喜欢踢足球").role("assistant").build()
                ))
                .modelParameter(ModelParameters.builder().modelName("xingchen-base").build())
                .kvMemoryConfigs(Lists.newArrayList(
                        KVMemoryConfig.builder().enabled(true).memoryText("职业").build(),
                        KVMemoryConfig.builder().enabled(true).memoryText("喜欢").build(),
                        KVMemoryConfig.builder().enabled(true).memoryText("性别").build()
                ))
                .build();
        ResultDTOExtractKVDTO response = api.extractMemoryKV(request);
        Assert.assertTrue(response.getSuccess());
        System.out.println(JSONObject.toJSONString(response));
    }
}

summary抽取

import com.alibaba.fastjson.JSONObject;
import com.alibaba.xingchen.ApiClient;
import com.alibaba.xingchen.ApiException;
import com.alibaba.xingchen.api.ChatExtractMessageApiSub;
import com.alibaba.xingchen.model.*;
import com.google.common.collect.Lists;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

/**
 * @author: wangzhan
 * @create: 2024-04-15 12:01
 **/
@Ignore
public class ChatExtractMessageApiTest extends TestBaseV2 {

    private ChatExtractMessageApiSub api = new ChatExtractMessageApiSub();

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


    @Test
    public void extractSummaryTest() throws ApiException {
        ExtractMemoryRequest request = ExtractMemoryRequest.builder()
                .messages(Lists.newArrayList(
                        Message.builder().content("你好").role("user").build(),
                        Message.builder().content("你好呀,今天天气真好").role("assistant").build(),
                        Message.builder().content("我们一起去打篮球把").role("user").build(),
                        Message.builder().content("好的呀,那我们一起去打球吧,打完篮球我们去吃火锅").role("assistant").build()
                ))
                .modelParameter(ModelParameters.builder().modelName("xingchen-base").build()).build();
        ResultDTOExtractSummaryDTO response = api.extractMemorySummary(request);
        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.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("0b14c2a917038182306264126ef010").content("测试终止对话").build());
        Assert.assertTrue(response.getSuccess());
        System.out.println(JSONObject.toJSONString(response));
    }
}