百炼平台Java 集成API上传文档到数据中心并添加索引

本文涉及的产品
NLP 自学习平台,3个模型定制额度 1个月
NLP自然语言处理_基础版,每接口每天50万次
NLP自然语言处理_高级版,每接口累计50万次
简介: 本文主要演示阿里云百炼产品,如何通过API实现数据中心文档的上传和索引的添加。

一、主要操作步骤

图片.png

二、参数获取

  • categoryId:数据中心类目id

图片.png

  • workspaceId:业务空间id

图片.png

  • indexId:索引id

图片.png

  • ak、sk

ACCESS_KEY_ID、ACCESS_KEY_SECRET参数获取地址

hiwspwhvrvbmc_2efd51003f384b0c8d043538cf44f1a7.png

三、完整的JAVA Code Sample

  • pom.xml
 <dependencies>

        <!-- https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>dashscope-sdk-java</artifactId>
            <version>2.15.1</version>
        </dependency>

        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>bailian20231229</artifactId>
            <version>1.4.1</version>
        </dependency>
    </dependencies>
  • Code

import com.google.gson.internal.LinkedTreeMap;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;

public class apply {

    public static void main(String[] args_) throws Exception {

        // 上传文件的本地路径地址
        String filePath = "C:\\Users\\*****\\1.0.01.04.36569.docx";
        String categoryId = "cate_d78d9993**********";//数据中心类目id
        String workspaceId = "llm-w*******"; //业务空间id
        String indexId = "eev*******";// 索引库索引id
        String ak = "LT*********";
        String sk = "8R**********";

        // 初始化参数
        String md5 = "";
        String byteLength = "";
        String fileName = "";

        try {
            Path path = Paths.get(filePath);
            fileName = path.getFileName().toString();
            // 读取文件内容到字节数组
            byte[] fileBytes = Files.readAllBytes(path);

            // 获取文件字节内容长度
            byteLength = fileBytes.length + "";
            // 计算MD5值
            md5 = calculateMD5(fileBytes);

        } catch (IOException | NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        // 初始化Client对象
        com.aliyun.teaopenapi.Client client = apply.createClient(ak, sk);

        //1、申请文件上传租约
        HashMap<String,Object> response = apply.applyFileUploadLease(client, fileName,md5,byteLength,categoryId,workspaceId);

        // 从response中提取data,获取上传文件必要的url和
        if(response.containsKey("body")){
            LinkedTreeMap<String, Object> body1 = (LinkedTreeMap<String, Object>) response.get("body");
            if (body1.containsKey("Data")) {
                LinkedTreeMap<String, Object> dataObject = (LinkedTreeMap<String, Object>) body1.get("Data");
                // 这里是你需要的Data对象
                String fileUploadLeaseId = (String) dataObject.get("FileUploadLeaseId");
                String type = (String) dataObject.get("Type");
                LinkedTreeMap<String, Object> param = (LinkedTreeMap<String, Object>) dataObject.get("Param");
                String preSignedUrl = (String) param.get("Url");

                LinkedTreeMap<String, Object> headers = (LinkedTreeMap<String, Object>) param.get("Headers");
                String contentType = (String) headers.get("Content-Type");
                String extra = (String) headers.get("X-bailian-extra");

                //2、使用租约上传文档
                uploadFile(preSignedUrl,filePath,extra,contentType,Integer.parseInt(byteLength));

                //3、addfile,添加上传的文档到百炼系统,系统自动解析文档
                String fileId = addFile(client, fileUploadLeaseId, workspaceId, categoryId);

                //4、将解析的文档添加到索引
                AddDocumentsJob(client,indexId,workspaceId,fileId,categoryId);

            }else {
                System.out.println("body not found in response.");
            }
        }
    }



    /**
     * <b>description</b> :
     * <p>使用AK & SK初始化账号Client</p>
     * @return Client
     *
     * @throws Exception
     */
    public static com.aliyun.teaopenapi.Client createClient(String ak, String sk) throws Exception {
        // 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        // 建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378657.html。
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId(ak)
                // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret(sk);
        // Endpoint 请参考 https://api.aliyun.com/product/bailian
        config.endpoint = "bailian.cn-beijing.aliyuncs.com";
        return new com.aliyun.teaopenapi.Client(config);
    }

    /**
     * <b>申请文档上传租约</b> :
     * <p>API 相关</p>
     * @return OpenApi.Params
     */
    public static com.aliyun.teaopenapi.models.Params createApplyFileUploadLeaseApiInfo(String CategoryId, String WorkspaceId) throws Exception {
        com.aliyun.teaopenapi.models.Params params = new com.aliyun.teaopenapi.models.Params()
                // 接口名称
                .setAction("ApplyFileUploadLease")
                // 接口版本
                .setVersion("2023-12-29")
                // 接口协议
                .setProtocol("HTTPS")
                // 接口 HTTP 方法
                .setMethod("POST")
                .setAuthType("AK")
                .setStyle("ROA")
                // 接口 PATH
                .setPathname("/" + WorkspaceId + "/datacenter/category/" + CategoryId + "")
                // 接口请求体内容格式
                .setReqBodyType("formData")
                // 接口响应体内容格式
                .setBodyType("json");
        return params;
    }

    public static HashMap<String,Object> applyFileUploadLease(com.aliyun.teaopenapi.Client client, String fileName, String md5, String byteLength, String categoryId, String workspaceId ) throws Exception{
        com.aliyun.teaopenapi.models.Params params = apply.createApplyFileUploadLeaseApiInfo(categoryId, workspaceId);
        // body params
        java.util.Map<String, Object> body = new java.util.HashMap<>();
        body.put("FileName", fileName);
        body.put("Md5", md5);
        body.put("SizeInBytes", byteLength);
        // runtime options
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        com.aliyun.teaopenapi.models.OpenApiRequest request = new com.aliyun.teaopenapi.models.OpenApiRequest()
                .setBody(body);
        // 返回值为 Map 类型,可从 Map 中获得三类数据:响应体 body、响应头 headers、HTTP 返回的状态码 statusCode。
        HashMap<String,Object> response = (HashMap<String, java.lang.Object>)  client.callApi(params, request, runtime);
        return response;
    }

    /**
     * 计算md5值
     * @param bytes
     * @return
     * @throws NoSuchAlgorithmException
     */
    private static String calculateMD5(byte[] bytes) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] digest = md.digest(bytes);
        return byteArrayToHexString(digest);
    }

    private static String byteArrayToHexString(byte[] bytes) {
        Formatter formatter = new Formatter();
        for (byte b : bytes) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    /**
     * 使用获取到的租约上传实际文件到数据中心,注意这一步上传后在数据中心还看不到文档,AddFile之后才可以在数据中心看到添加的文档
     * @param preSignedUrl
     * @param filePath
     * @param extra
     * @param contentType
     * @param length
     */
    public static void uploadFile(String preSignedUrl, String filePath,String extra,String contentType,int length ) {
        HttpURLConnection connection = null;
        try {
            // 创建URL对象

            URL url = new URL(preSignedUrl);
            connection = (HttpURLConnection) url.openConnection();
            // 设置请求⽅法为PUT,预签名URL默认⽤于PUT操作进⾏⽂件上传

            connection.setRequestMethod("PUT");
            // 允许向connection输出,因为这个连接是⽤于上传⽂件的

            connection.setDoOutput(true);
            // 设置请求头,这⾥可以根据需要设置⽐如Content-Type

            connection.setRequestProperty("X-bailian-extra", extra);
            connection.setRequestProperty("Content-Type", contentType);
            // 读取⽂件并通过连接上传

            try (DataOutputStream outStream = new DataOutputStream(connection.getOutputStream());
                 FileInputStream fileInputStream = new FileInputStream(filePath)) {
                byte[] buffer = new byte[length];
                int bytesRead;
                while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                    outStream.write(buffer, 0, bytesRead);
                }
                outStream.flush();
            }
            // 检查响应代码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // ⽂件上传成功处理

                System.out.println("File uploaded successfully.");
            } else {
                // ⽂件上传失败处理

                System.out.println("Failed to upload the file. ResponseCod e: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    /**
     * 构建添加文档API
     * @param WorkspaceId
     * @return
     * @throws Exception
     */
    public static com.aliyun.teaopenapi.models.Params createAddFileApiInfo(String WorkspaceId) throws Exception {
        com.aliyun.teaopenapi.models.Params params = new com.aliyun.teaopenapi.models.Params()
                // 接⼝名称
                .setAction("AddFile")
                // 接⼝版本
                .setVersion("2023-12-29")
                // 接⼝协议
                .setProtocol("HTTPS")
                // 接⼝ HTTP ⽅法
                .setMethod("PUT")
                .setAuthType("AK")
                .setStyle("ROA")
                // 接⼝ PATH
                .setPathname("/" + WorkspaceId + "/datacenter/file")
                // 接⼝请求体内容格式
                .setReqBodyType("formData")
                // 接⼝响应体内容格式
                .setBodyType("json");
        return params;
    }

    /**
     * AddFile
     * 该接口用于将已经成功上传的文档添加到百炼系统数据中心,添加成功之后,系统会自动启动文件的解析,在数据中心可以看到文档
     * @param client
     * @param leaseId
     * @param workSpaceId
     * @param categoryId
     * @throws Exception
     */
    public static String addFile(com.aliyun.teaopenapi.Client client,String leaseId,String workSpaceId,String categoryId) throws Exception {
        com.aliyun.teaopenapi.models.Params params = apply.createAddFileApiInfo(workSpaceId);
        // body params
        java.util.Map<String, Object> body = new java.util.HashMap<>();
        body.put("LeaseId", leaseId);
        body.put("Parser", "DASHSCOPE_DOCMIND");
        body.put("CategoryId", categoryId);
        // runtime options
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        com.aliyun.teaopenapi.models.OpenApiRequest request = new com.aliyun.teaopenapi.models.OpenApiRequest()
                .setBody(body);
        // 复制代码运行请自行打印 API 的返回值
        // 返回值为 Map 类型,可从 Map 中获得三类数据:响应体 body、响应头 headers、HTTP 返回的状态码 statusCode。
        HashMap<String,Object> response = (HashMap<String, Object>) client.callApi(params, request, runtime);

        LinkedTreeMap<String, Object> file_body = (LinkedTreeMap<String, Object>) response.get("body");
        LinkedTreeMap<String, Object> data = (LinkedTreeMap<String, Object>) file_body.get("Data");
        String fileId = (String) data.get("FileId");
        System.out.println("addFile:" + response.get("statusCode"));
        return fileId;
    }

    public static com.aliyun.teaopenapi.models.Params createSubmitIndexAddDocumentsJobApiInfo(String WorkspaceId) throws Exception {
        com.aliyun.teaopenapi.models.Params params = new com.aliyun.teaopenapi.models.Params()
                // 接口名称
                .setAction("SubmitIndexAddDocumentsJob")
                // 接口版本
                .setVersion("2023-12-29")
                // 接口协议
                .setProtocol("HTTPS")
                // 接口 HTTP 方法
                .setMethod("POST")
                .setAuthType("AK")
                .setStyle("ROA")
                // 接口 PATH
                .setPathname("/" + WorkspaceId + "/index/add_documents_to_index")
                // 接口请求体内容格式
                .setReqBodyType("json")
                // 接口响应体内容格式
                .setBodyType("json");
        return params;
    }

    /**
     * 追加以及添加到数据中心的文档到索引
     * @param client
     * @param indexId
     * @param workSpaceId
     * @param documentIds
     * @param categoryIds
     * @throws Exception
     */
    public static void AddDocumentsJob(com.aliyun.teaopenapi.Client client,String indexId,String workSpaceId,String documentIds, String categoryIds) throws Exception {
        com.aliyun.teaopenapi.models.Params params = apply.createSubmitIndexAddDocumentsJobApiInfo(workSpaceId);
        // query params
        java.util.Map<String, Object> queries = new java.util.HashMap<>();
        queries.put("IndexId", indexId);
        queries.put("SourceType", "DATA_CENTER_FILE");
        queries.put("DocumentIds", com.aliyun.openapiutil.Client.arrayToStringWithSpecifiedStyle(java.util.Arrays.asList(
                documentIds
        ), "DocumentIds", "json"));
        queries.put("CategoryIds", com.aliyun.openapiutil.Client.arrayToStringWithSpecifiedStyle(java.util.Arrays.asList(
                categoryIds
        ), "CategoryIds", "json"));
        // runtime options
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        com.aliyun.teaopenapi.models.OpenApiRequest request = new com.aliyun.teaopenapi.models.OpenApiRequest()
                .setQuery(com.aliyun.openapiutil.Client.query(queries));
        // 复制代码运行请自行打印 API 的返回值
        // 返回值为 Map 类型,可从 Map 中获得三类数据:响应体 body、响应头 headers、HTTP 返回的状态码 statusCode。
        HashMap<String,Object> response = (HashMap<String, Object>) client.callApi(params, request, runtime);
        System.out.println("AddDocumentsJob: " + response.get("statusCode"));
    }

}
  • 上传效果查看

图片.png

图片.png


四、更多参考

通过API上传文件

API参考地址

相关实践学习
如何快速体验知识检索增强应用
在应用广场中您可以挑选智能体API应用、官方预置完整工程链路的知识检索增强(RAG)应用、流程编排应用,以及官方最佳实践的写作应用妙笔等,通过应用快速将通义千问系列等大语言模型能力接入到业务解决方案中。
相关文章
|
2月前
|
自然语言处理 NoSQL API
基于百炼平台qwen-max的api 打造一套 检索增强 图谱增强 基于指令的智能工具调用决策 智能体
基于百炼平台的 `qwen-max` API,设计了一套融合检索增强、图谱增强及指令驱动的智能工具调用决策系统。该系统通过解析用户指令,智能选择调用检索、图谱推理或模型生成等工具,以提高问题回答的准确性和丰富性。系统设计包括指令解析、工具调用决策、检索增强、图谱增强等模块,旨在通过多种技术手段综合提升智能体的能力。
282 5
|
2天前
|
机器学习/深度学习 人工智能 Serverless
|
1天前
|
人工智能 自然语言处理 Shell
深度评测 | 仅用3分钟,百炼调用满血版 Deepseek-r1 API,百万Token免费用,简直不要太爽。
仅用3分钟,百炼调用满血版Deepseek-r1 API,享受百万免费Token。阿里云提供零门槛、快速部署的解决方案,支持云控制台和Cloud Shell两种方式,操作简便。Deepseek-r1满血版在推理能力上表现出色,尤其擅长数学、代码和自然语言处理任务,使用过程中无卡顿,体验丝滑。结合Chatbox工具,用户可轻松掌控模型,提升工作效率。阿里云大模型服务平台百炼不仅速度快,还确保数据安全,值得信赖。
76855 18
深度评测 | 仅用3分钟,百炼调用满血版 Deepseek-r1 API,百万Token免费用,简直不要太爽。
|
25天前
|
存储 缓存 Java
Java中的分布式缓存与Memcached集成实战
通过在Java项目中集成Memcached,可以显著提升系统的性能和响应速度。合理的缓存策略、分布式架构设计和异常处理机制是实现高效缓存的关键。希望本文提供的实战示例和优化建议能够帮助开发者更好地应用Memcached,实现高性能的分布式缓存解决方案。
38 9
|
2月前
|
人工智能 自然语言处理 Java
FastExcel:开源的 JAVA 解析 Excel 工具,集成 AI 通过自然语言处理 Excel 文件,完全兼容 EasyExcel
FastExcel 是一款基于 Java 的高性能 Excel 处理工具,专注于优化大规模数据处理,提供简洁易用的 API 和流式操作能力,支持从 EasyExcel 无缝迁移。
218 9
FastExcel:开源的 JAVA 解析 Excel 工具,集成 AI 通过自然语言处理 Excel 文件,完全兼容 EasyExcel
|
24天前
|
JavaScript Java 测试技术
基于Java+SpringBoot+Vue实现的车辆充电桩系统设计与实现(系统源码+文档+部署讲解等)
面向大学生毕业选题、开题、任务书、程序设计开发、论文辅导提供一站式服务。主要服务:程序设计开发、代码修改、成品部署、支持定制、论文辅导,助力毕设!
55 6
|
1月前
|
开发框架 数据可视化 .NET
.NET 中管理 Web API 文档的两种方式
.NET 中管理 Web API 文档的两种方式
42 14
|
1月前
|
Java API Apache
java集成stable diffusion
通过REST API和JNI两种方法,我们可以在Java应用程序中集成Stable Diffusion模型。REST API方法更加简单和易于维护,而JNI方法则提供更高的性能。根据具体应用场景和需求,选择合适的集成方法,可以充分利用Stable Diffusion的强大功能,实现高效的图像生成和处理。
66 15
|
1月前
|
API 开发者
通义灵码 API 开发文档自动生成场景DEMO
通义灵码API开发文档自动生成场景DEMO展示了通过自定义指令,大模型能快速根据类代码生成Markdown格式的API文档。文档详细描述API的入参、出参,并可生成测试代码等示例,帮助开发者快速创建美观的API文档。
|
2月前
|
自然语言处理 前端开发 Java
API管理平台:你用的到底是哪个?
本文介绍了多个API管理和文档工具,包括Apifox、Swagger及其增强版Knife4j和RapiDoc、阿里RAP、去哪儿YApi以及Redoc。这些工具各有特色,适用于不同的开发场景。Apifox提供一体化协作平台,支持API文档、调试、Mock和测试;Swagger结合Knife4j适合Java与前端团队,界面美观且功能丰富;YApi则适用于跨语言开发,支持多种API形式的管理;阿里RAP专注于接口文档管理和Mock服务;Redoc则是开源的现代化API文档浏览器。总结而言,选择工具应根据团队需求和技术栈来决定。
231 16