1. 初始化客户端在开始上传文档和创建知识库之前,您需要使用配置好的AccessKey和AccessKey Secret初始化客户端(Client),以完成身份验证和接入点endpoint 配置。 公网接入地址: 请确保您的客户端可以访问公网。 VPC接入地址: 若您的客户端部署在阿里云北京地域cn-beijing (公有云)或上海地域cn-shanghai-finance-1 (金融云),且处于VPC网络环境中,可以使用以下VPC接入地址(不支持跨地域访问)。
创建完成后,您将得到一个Client对象,用于后续的 API 调用。 | Pythondef create_client() -> bailian20231229Client:
"""
创建并配置客户端(Client)。
返回:
bailian20231229Client: 配置好的客户端(Client)。
"""
config = open_api_models.Config(
access_key_id=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_ID'),
access_key_secret=os.environ.get('ALIBABA_CLOUD_ACCESS_KEY_SECRET')
)
# 下方接入地址以公有云的公网接入地址为例,可按需更换接入地址。
config.endpoint = 'bailian.cn-beijing.aliyuncs.com'
return bailian20231229Client(config)
Java/**
* 初始化客户端(Client)。
*
* @return 配置好的客户端对象
*/
public com.aliyun.bailian20231229.Client createClient() throws Exception {
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
// 下方接入地址以公有云的公网接入地址为例,可按需更换接入地址。
config.endpoint = "bailian.cn-beijing.aliyuncs.com";
return new com.aliyun.bailian20231229.Client(config);
}
PHP/**
* 初始化客户端(Client)。
*
* @return Bailian 配置好的客户端对象(Client)。
*/
public function createClient(){
$config = new Config([
"accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
"accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
]);
// 下方接入地址以公有云的公网接入地址为例,可按需更换接入地址。
$config->endpoint = 'bailian.cn-beijing.aliyuncs.com';
return new Bailian($config);
}
Node.js/**
* 创建并配置客户端(Client)
* @return Client
* @throws Exception
*/
function createClient() {
const config = new OpenApi.Config({
accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET
});
// 下方接入地址以公有云的公网接入地址为例,可按需更换接入地址
config.endpoint = `bailian.cn-beijing.aliyuncs.com`;
return new bailian20231229.default(config);
}
C#/// <summary>
/// 初始化客户端(Client)。
/// </summary>
/// <returns>配置好的客户端对象</returns>
/// <exception cref="Exception">初始化过程中发生错误时抛出异常</exception>
public AlibabaCloud.SDK.Bailian20231229.Client CreateClient()
{
var config = new AlibabaCloud.OpenApiClient.Models.Config
{
AccessKeyId = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
AccessKeySecret = Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
};
// 下方接入地址以公有云的公网接入地址为例,可按需更换接入地址.
config.Endpoint = "bailian.cn-beijing.aliyuncs.com";
return new AlibabaCloud.SDK.Bailian20231229.Client(config);
}
Go// CreateClient 创建并配置客户端(Client)。
//
// 返回:
// - *client.Bailian20231229Client: 配置好的客户端(Client)。
// - error: 错误信息。
func CreateClient() (_result *bailian20231229.Client, _err error) {
config := &openapi.Config{
AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
}
// 下方接入地址以公有云的公网接入地址为例,可按需更换接入地址。
config.Endpoint = tea.String("bailian.cn-beijing.aliyuncs.com")
_result = &bailian20231229.Client{}
_result, _err = bailian20231229.NewClient(config)
return _result, _err
}
|
2. 上传知识库文档 |
2.1. 申请文档上传租约在创建知识库前,您需先将文档上传至同一业务空间,作为知识库的知识来源。上传文档前,需调用ApplyFileUploadLease接口申请一个文档上传租约。该租约是一个临时的授权,允许您在限定时间内(有效期为分钟级)上传文档。 workspace_id:如何获取业务空间ID category_id:本示例中,请传入default 。阿里云百炼使用类目管理您上传的文档,系统会自动创建一个默认类目。您亦可调用AddCategory接口创建新类目,并获取对应的category_id 。 file_name:请传入上传文档的名称(包括后缀)。其值必须与实际文档名一致。例如,上传图中的文档时,请传入阿里云百炼系列手机产品介绍.docx 。 
file_md5:请传入上传文档的MD5值(但当前阿里云不对该值进行校验,便于您使用URL地址上传文档)。 以Python为例,MD5值可使用hashlib模块获取。其他语言请参见完整示例代码。 代码示例 import hashlib
def calculate_md5(file_path):
"""
计算文档的MD5值。
参数:
file_path (str): 文档本地路径。
返回:
str: 文档的MD5值。
"""
md5_hash = hashlib.md5()
# 以二进制形式读取文档
with open(file_path, "rb") as f:
# 按块读取文档,避免大文档占用过多内存
for chunk in iter(lambda: f.read(4096), b""):
md5_hash.update(chunk)
return md5_hash.hexdigest()
# 使用示例
file_path = "请替换为您需要上传文档的实际本地路径,例如/xxx/xxx/xxx/阿里云百炼系列手机产品介绍.docx"
md5_value = calculate_md5(file_path)
print(f"文档的MD5值为: {md5_value}")
将代码中的file_path 变量替换为文档的实际本地路径后运行,即可获取目标文档的MD5值(下方为示例值): 文档的MD5值为: 2ef7361ea907f3a1b91e3b9936f5643a
file_size:请传入上传文档的字节大小。 以Python为例,该值可使用os模块获取。其他语言请参见完整示例代码。 代码示例 import os
def get_file_size(file_path: str) -> int:
"""
获取文档的字节大小(以字节为单位)。
参数:
file_path (str): 文档的实际本地路径。
返回:
int: 文档大小(以字节为单位)。
"""
return os.path.getsize(file_path)
# 使用示例
file_path = "请替换为您需要上传文档的实际本地路径,例如/xxx/xxx/xxx/阿里云百炼系列手机产品介绍.docx"
file_size = get_file_size(file_path)
print(f"文档的字节大小为: {file_size}")
将代码中的file_path 变量替换为文档的实际本地路径后运行,即可获取目标文档的字节大小(下方为示例值): 文档的字节大小为: 14015
申请临时上传租约成功后,您将获得: 一组临时上传参数: 一个临时上传URL:Data.Param.Url
您将在下一步中用到它们。 | Pythondef apply_lease(client, category_id, file_name, file_md5, file_size, workspace_id):
"""
从阿里云百炼服务申请文档上传租约。
参数:
client (bailian20231229Client): 客户端(Client)。
category_id (str): 类目ID。
file_name (str): 文档名称。
file_md5 (str): 文档的MD5值。
file_size (int): 文档大小(以字节为单位)。
workspace_id (str): 业务空间ID。
返回:
阿里云百炼服务的响应。
"""
headers = {}
request = bailian_20231229_models.ApplyFileUploadLeaseRequest(
file_name=file_name,
md_5=file_md5,
size_in_bytes=file_size,
)
runtime = util_models.RuntimeOptions()
return client.apply_file_upload_lease_with_options(category_id, workspace_id, request, headers, runtime)
Java/**
* 申请文档上传租约。
*
* @param client 客户端对象
* @param categoryId 类目ID
* @param fileName 文档名称
* @param fileMd5 文档的MD5值
* @param fileSize 文档大小(以字节为单位)
* @param workspaceId 业务空间ID
* @return 阿里云百炼服务的响应对象
*/
public ApplyFileUploadLeaseResponse applyLease(com.aliyun.bailian20231229.Client client, String categoryId, String fileName, String fileMd5, String fileSize, String workspaceId) throws Exception {
Map<String, String> headers = new HashMap<>();
com.aliyun.bailian20231229.models.ApplyFileUploadLeaseRequest applyFileUploadLeaseRequest = new com.aliyun.bailian20231229.models.ApplyFileUploadLeaseRequest();
applyFileUploadLeaseRequest.setFileName(fileName);
applyFileUploadLeaseRequest.setMd5(fileMd5);
applyFileUploadLeaseRequest.setSizeInBytes(fileSize);
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
ApplyFileUploadLeaseResponse applyFileUploadLeaseResponse = null;
applyFileUploadLeaseResponse = client.applyFileUploadLeaseWithOptions(categoryId, workspaceId, applyFileUploadLeaseRequest, headers, runtime);
return applyFileUploadLeaseResponse;
}
PHP/**
* 申请文档上传租约。
*
* @param Bailian $client 客户端(Client)。
* @param string $categoryId 类目ID。
* @param string $fileName 文档名称。
* @param string $fileMd5 文档的MD5值。
* @param int $fileSize 文档大小(以字节为单位)。
* @param string $workspaceId 业务空间ID。
* @return ApplyFileUploadLeaseResponse 阿里云百炼服务的响应。
*/
public function applyLease($client, $categoryId, $fileName, $fileMd5, $fileSize, $workspaceId) {
$headers = [];
$applyFileUploadLeaseRequest = new ApplyFileUploadLeaseRequest([
"fileName" => $fileName,
"md5" => $fileMd5,
"sizeInBytes" => $fileSize
]);
$runtime = new RuntimeOptions([]);
return $client->applyFileUploadLeaseWithOptions($categoryId, $workspaceId, $applyFileUploadLeaseRequest, $headers, $runtime);
}
Node.js/**
* 申请文档上传租约
* @param {Bailian20231229Client} client - 客户端(Client)
* @param {string} categoryId - 类目ID
* @param {string} fileName - 文档名称
* @param {string} fileMd5 - 文档的MD5值
* @param {string} fileSize - 文档大小(以字节为单位)
* @param {string} workspaceId - 业务空间ID
* @returns {Promise<bailian20231229.ApplyFileUploadLeaseResponse>} - 阿里云百炼服务的响应
*/
async function applyLease(client, categoryId, fileName, fileMd5, fileSize, workspaceId) {
const headers = {};
const req = new bailian20231229.ApplyFileUploadLeaseRequest({
md5: fileMd5,
fileName,
sizeInBytes: fileSize
});
const runtime = new Util.RuntimeOptions({});
return await client.applyFileUploadLeaseWithOptions(
categoryId,
workspaceId,
req,
headers,
runtime
);
}
C#/// <summary>
/// 申请文档上传租约。
/// </summary>
/// <param name="client">客户端对象</param>
/// <param name="categoryId">类目ID</param>
/// <param name="fileName">文档名称</param>
/// <param name="fileMd5">文档的MD5值</param>
/// <param name="fileSize">文档大小(以字节为单位)</param>
/// <param name="workspaceId">业务空间ID</param>
/// <returns>阿里云百炼服务的响应对象</returns>
/// <exception cref="Exception">调用过程中发生错误时抛出异常</exception>
public AlibabaCloud.SDK.Bailian20231229.Models.ApplyFileUploadLeaseResponse ApplyLease(
AlibabaCloud.SDK.Bailian20231229.Client client,
string categoryId,
string fileName,
string fileMd5,
string fileSize,
string workspaceId)
{
var headers = new Dictionary<string, string>() { };
var applyFileUploadLeaseRequest = new AlibabaCloud.SDK.Bailian20231229.Models.ApplyFileUploadLeaseRequest
{
FileName = fileName,
Md5 = fileMd5,
SizeInBytes = fileSize
};
var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
return client.ApplyFileUploadLeaseWithOptions(categoryId, workspaceId, applyFileUploadLeaseRequest, headers, runtime);
}
Go// ApplyLease 从阿里云百炼服务申请文档上传租约。
//
// 参数:
// - client (bailian20231229.Client): 客户端(Client)。
// - categoryId (string): 类目ID。
// - fileName (string): 文档名称。
// - fileMD5 (string): 文档的MD5值。
// - fileSize (string): 文档大小(以字节为单位)。
// - workspaceId (string): 业务空间ID。
//
// 返回:
// - *bailian20231229.ApplyFileUploadLeaseResponse: 阿里云百炼服务的响应。
// - error: 错误信息。
func ApplyLease(client *bailian20231229.Client, categoryId, fileName, fileMD5 string, fileSize string, workspaceId string) (_result *bailian20231229.ApplyFileUploadLeaseResponse, _err error) {
headers := make(map[string]*string)
applyFileUploadLeaseRequest := &bailian20231229.ApplyFileUploadLeaseRequest{
FileName: tea.String(fileName),
Md5: tea.String(fileMD5),
SizeInBytes: tea.String(fileSize),
}
runtime := &util.RuntimeOptions{}
return client.ApplyFileUploadLeaseWithOptions(tea.String(categoryId), tea.String(workspaceId), applyFileUploadLeaseRequest, headers, runtime)
}
请求示例 {
"CategoryId": "default",
"FileName": "阿里云百炼系列手机产品介绍.docx",
"Md5": "2ef7361ea907f3a1b91e3b9936f5643a",
"SizeInBytes": "14015",
"WorkspaceId": "llm-4u5xpd1xdjqpxxxx"
}
响应示例 {
"RequestId": "778C0B3B-59C2-5FC1-A947-36EDD1XXXXXX",
"Success": true,
"Message": "",
"Code": "success",
"Status": "200",
"Data": {
"FileUploadLeaseId": "1e6a159107384782be5e45ac4759b247.1719325231035",
"Type": "HTTP",
"Param": {
"Method": "PUT",
"Url": "https://bailian-datahub-data-origin-prod.oss-cn-hangzhou.aliyuncs.com/1005426495169178/10024405/68abd1dea7b6404d8f7d7b9f7fbd332d.1716698936847.pdf?Expires=1716699536&OSSAccessKeyId=TestID&Signature=HfwPUZo4pR6DatSDym0zFKVh9Wg%3D",
"Headers": " \"X-bailian-extra\": \"MTAwNTQyNjQ5NTE2OTE3OA==\",\n \"Content-Type\": \"application/pdf\""
}
}
}
|
2.2. 上传文档到临时存储取得上传租约后,您即可使用租约中的临时上传参数和临时上传URL,将本地存储或可通过公网访问的文档上传至阿里云百炼服务器。请注意,每个业务空间最多支持10万个文档。目前支持上传的格式包括:PDF、DOCX、DOC、TXT、Markdown、PPTX、PPT、XLSX、XLS、HTML、PNG、JPG、JPEG、BMP 和 GIF。 | 本地上传Pythonimport requests
from urllib.parse import urlparse
def upload_file(pre_signed_url, file_path):
"""
将本地文档上传至临时存储。
参数:
pre_signed_url (str): 上传租约中的URL。
file_path (str): 文档本地路径。
返回:
阿里云百炼服务的响应。
"""
try:
# 设置请求头
headers = {
"X-bailian-extra": "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param.Headers中X-bailian-extra字段的值",
"Content-Type": "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param.Headers中Content-Type字段的值(返回空值时,传空值即可)"
}
# 读取文档并上传
with open(file_path, 'rb') as file:
# 下方设置请求方法用于文档上传,需与您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param中Method字段的值一致
response = requests.put(pre_signed_url, data=file, headers=headers)
# 检查响应状态码
if response.status_code == 200:
print("File uploaded successfully.")
else:
print(f"Failed to upload the file. ResponseCode: {response.status_code}")
except Exception as e:
print(f"An error occurred: {str(e)}")
if __name__ == "__main__":
pre_signed_url_or_http_url = "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param中Url字段的值"
# 将本地文档上传至临时存储
file_path = "请替换为您需要上传文档的实际本地路径(以Linux为例:/xxx/xxx/阿里云百炼系列手机产品介绍.docx)"
upload_file(pre_signed_url_or_http_url, file_path)
Javaimport java.io.DataOutputStream;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class UploadFile {
public static void uploadFile(String preSignedUrl, String filePath) {
HttpURLConnection connection = null;
try {
// 创建URL对象
URL url = new URL(preSignedUrl);
connection = (HttpURLConnection) url.openConnection();
// 设置请求方法用于文档上传,需与您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param中Method字段的值一致
connection.setRequestMethod("PUT");
// 允许向connection输出,因为这个连接是用于上传文档的
connection.setDoOutput(true);
connection.setRequestProperty("X-bailian-extra", "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param.Headers中X-bailian-extra字段的值");
connection.setRequestProperty("Content-Type", "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param.Headers中Content-Type字段的值(返回空值时,传空值即可)");
// 读取文档并通过连接上传
try (DataOutputStream outStream = new DataOutputStream(connection.getOutputStream());
FileInputStream fileInputStream = new FileInputStream(filePath)) {
byte[] buffer = new byte[4096];
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. ResponseCode: " + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
public static void main(String[] args) {
String preSignedUrlOrHttpUrl = "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param中Url字段的值";
// 将本地文档上传至临时存储
String filePath = "请替换为您需要上传文档的实际本地路径(以Linux为例:/xxx/xxx/阿里云百炼系列手机产品介绍.docx)";
uploadFile(preSignedUrlOrHttpUrl, filePath);
}
}
PHP<?php
/**
* 将本地文档上传至临时存储
*
* @param string $preSignedUrl 从 ApplyFileUploadLease 接口获取的预签名 URL 或 HTTP 地址
* @param array $headers 包含 "X-bailian-extra" 和 "Content-Type" 的请求头数组
* @param string $filePath 本地文档路径
* @throws Exception 如果上传失败
*/
function uploadFile($preSignedUrl, $headers, $filePath) {
// 读取文件内容
$fileContent = file_get_contents($filePath);
if ($fileContent === false) {
throw new Exception("无法读取文件: " . $filePath);
}
// 初始化 cURL 会话
$ch = curl_init();
// 设置 cURL 选项
curl_setopt($ch, CURLOPT_URL, $preSignedUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); // 使用 PUT 方法
curl_setopt($ch, CURLOPT_POSTFIELDS, $fileContent); // 设置请求体为文档内容
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 返回响应结果而不是直接输出
// 构建请求头
$uploadHeaders = [
"X-bailian-extra: " . $headers["X-bailian-extra"],
"Content-Type: " . $headers["Content-Type"]
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $uploadHeaders);
// 执行请求
$response = curl_exec($ch);
// 获取 HTTP 响应码
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 关闭 cURL 会话
curl_close($ch);
// 检查响应码
if ($httpCode != 200) {
throw new Exception("上传失败,HTTP 状态码: " . $httpCode . ",错误信息: " . $response);
}
// 上传成功
echo "File uploaded successfully.\n";
}
/**
* 主函数:本地文档上传
*/
function main() {
// 请替换为您在上一步中调用 ApplyFileUploadLease 接口实际返回的 Data.Param 中 Url 字段的值
$preSignedUrl = "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param中Url字段的值";
// 请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param.Headers中的 X-bailian-extra 和 Content-Type
$headers = [
"X-bailian-extra" => "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param.Headers中X-bailian-extra字段的值",
"Content-Type" => "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param.Headers中Content-Type字段的值(返回空值时,传空值即可)"
];
// 将本地文档上传至临时存储
$filePath = "请替换为您需要上传文档的实际本地路径(以Linux为例:/xxx/xxx/阿里云百炼系列手机产品介绍.docx)";
try {
uploadFile($preSignedUrl, $headers, $filePath);
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
}
// 调用主函数
main();
?>
Node.jsconst fs = require('fs');
const axios = require('axios');
/**
* 将本地文档上传至临时存储
*
* @param {string} preSignedUrl - 上传租约中的URL
* @param {Object} headers - 上传请求的头部
* @param {string} filePath - 文档本地路径
* @throws {Error} 如果上传失败
*/
async function uploadFile(preSignedUrl, headers, filePath) {
// 构建上传所需的请求头
const uploadHeaders = {
"X-bailian-extra": headers["X-bailian-extra"],
"Content-Type": headers["Content-Type"]
};
// 创建文件读取流
const fileStream = fs.createReadStream(filePath);
try {
// 使用 axios 发送 PUT 请求
const response = await axios.put(preSignedUrl, fileStream, {
headers: uploadHeaders
});
// 检查响应状态码
if (response.status === 200) {
console.log("File uploaded successfully.");
} else {
console.error(`Failed to upload the file. ResponseCode: ${response.status}`);
throw new Error(`Upload failed with status code: ${response.status}`);
}
} catch (error) {
// 处理错误
console.error("Error during upload:", error.message);
throw new Error(`上传失败: ${error.message}`);
}
}
/**
* 主函数:本地文档上传
*/
function main() {
const preSignedUrl = "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param中Url字段的值";
const headers = {
"X-bailian-extra": "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param.Headers中X-bailian-extra字段的值",
"Content-Type": "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param.Headers中Content-Type字段的值(返回空值时,传空值即可)"
};
// 将本地文档上传至临时存储
const filePath = "请替换为您需要上传文档的实际本地路径(以Linux为例:/xxx/xxx/阿里云百炼系列手机产品介绍.docx)";
uploadFile(preSignedUrl, headers, filePath)
.then(() => {
console.log("Upload completed.");
})
.catch((err) => {
console.error("Upload failed:", err.message);
});
}
// 调用主函数
main();
C#using System;
using System.IO;
using System.Net;
public class UploadFilExample
{
public static void UploadFile(string preSignedUrl, string filePath)
{
HttpWebRequest connection = null;
try
{
// 创建 URL 对象
Uri url = new Uri(preSignedUrl);
connection = (HttpWebRequest)WebRequest.Create(url);
// 设置请求方法用于文档上传,需与您在上一步中调用 ApplyFileUploadLease 接口实际返回的 Data.Param 中 Method 字段的值一致
connection.Method = "PUT";
// 允许向 connection 输出,因为这个连接是用于上传文档的
connection.AllowWriteStreamBuffering = false;
connection.SendChunked = false;
// 设置请求头,需与您在上一步中调用 ApplyFileUploadLease 接口实际返回的 Data.Param.Headers 中的字段值一致
connection.Headers["X-bailian-extra"] = "请替换为您在上一步中调用 ApplyFileUploadLease 接口实际返回的 Data.Param.Headers 中 X-bailian-extra 字段的值";
connection.ContentType = "请替换为您在上一步中调用 ApplyFileUploadLease 接口实际返回的 Data.Param.Headers 中 Content-Type 字段的值(返回空值时,传空值即可)";
// 读取文档并通过连接上传
using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
using (var requestStream = connection.GetRequestStream())
{
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
requestStream.Write(buffer, 0, bytesRead);
}
requestStream.Flush();
}
// 检查响应
using (HttpWebResponse response = (HttpWebResponse)connection.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
// 文档上传成功处理
Console.WriteLine("File uploaded successfully.");
}
else
{
// 文档上传失败处理
Console.WriteLine($"Failed to upload the file. ResponseCode: {response.StatusCode}");
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
e.StackTrace.ToString();
}
finally
{
if (connection != null)
{
connection.Abort();
}
}
}
public static void Main(string[] args)
{
string preSignedUrlOrHttpUrl = "请替换为您在上一步中调用 ApplyFileUploadLease 接口实际返回的 Data.Param 中 Url 字段的值";
// 将本地文档上传至临时存储
string filePath = "请替换为您需要上传文档的实际本地路径(以Linux为例:/xxx/xxx/阿里云百炼系列手机产品介绍.docx)";
UploadFile(preSignedUrlOrHttpUrl, filePath);
}
}
Gopackage main
import (
"fmt"
"io"
"os"
"github.com/go-resty/resty/v2"
)
// UploadFile 将本地文档上传至临时存储。
//
// 参数:
// - preSignedUrl (string): 上传租约中的 URL。
// - headers (map[string]string): 上传请求的头部。
// - filePath (string): 文档本地路径。
//
// 返回:
// - error: 如果上传失败返回错误信息,否则返回 nil
func UploadFile(preSignedUrl string, headers map[string]string, filePath string) error {
// 打开本地文件
file, err := os.Open(filePath)
if err != nil {
return fmt.Errorf("打开文件失败: %w", err)
}
defer file.Close()
// 读取内容
body, err := io.ReadAll(file)
if err != nil {
return fmt.Errorf("读取文件失败: %w", err)
}
// 创建 REST 客户端
client := resty.New()
// 构建上传所需的请求头
uploadHeaders := map[string]string{
"X-bailian-extra": headers["X-bailian-extra"],
"Content-Type": headers["Content-Type"],
}
// 发送 PUT 请求
resp, err := client.R().
SetHeaders(uploadHeaders).
SetBody(body).
Put(preSignedUrl)
if err != nil {
return fmt.Errorf("发送请求失败: %w", err)
}
// 检查 HTTP 响应状态码
if resp.IsError() {
return fmt.Errorf("HTTP 错误: %d", resp.StatusCode())
}
fmt.Println("File uploaded successfully.")
return nil
}
// main 主函数
func main() {
// 请替换为您在上一步中调用 ApplyFileUploadLease 接口实际返回的 Data.Param 中 Url 字段的值
preSignedUrl := "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param中Url字段的值"
// 请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param.Headers中的 X-bailian-extra 和 Content-Type
headers := map[string]string{
"X-bailian-extra": "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param.Headers中X-bailian-extra字段的值",
"Content-Type": "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param.Headers中Content-Type字段的值(返回空值时,传空值即可)",
}
// 将本地文档上传至临时存储
filePath := "请替换为您需要上传文档的实际本地路径(以Linux为例:/xxx/xxx/阿里云百炼系列手机产品介绍.docx)"
// 调用上传函数
err := UploadFile(preSignedUrl, headers, filePath)
if err != nil {
fmt.Printf("上传失败: %v\n", err)
}
}
URL地址上传请确保URL公开可访问且指向一个有效的文档。 Pythonimport requests
from urllib.parse import urlparse
def upload_file_link(pre_signed_url, source_url_string):
"""
将可通过公网访问的文档上传至临时存储。
参数:
pre_signed_url (str): 上传租约中的 URL。
source_url_string (str): 文档的URL地址。
返回:
阿里云百炼服务的响应。
"""
try:
# 设置请求头
headers = {
"X-bailian-extra": "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param.Headers中X-bailian-extra字段的值",
"Content-Type": "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param.Headers中Content-Type字段的值(返回空值时,传空值即可)"
}
# 设置访问文档URL地址的请求方法为GET
source_response = requests.get(source_url_string)
if source_response.status_code != 200:
raise RuntimeError("Failed to get source file.")
# 下方设置请求方法用于文档上传,需与您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param中Method字段的值一致
response = requests.put(pre_signed_url, data=source_response.content, headers=headers)
# 检查响应状态码
if response.status_code == 200:
print("File uploaded successfully.")
else:
print(f"Failed to upload the file. ResponseCode: {response.status_code}")
except Exception as e:
print(f"An error occurred: {str(e)}")
if __name__ == "__main__":
pre_signed_url_or_http_url = "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param中Url字段的值(返回空值时,传空值即可)"
# 文档的URL地址
source_url = "请替换为您需要上传文档的URL地址"
upload_file_link(pre_signed_url_or_http_url, source_url)
Javaimport java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class UploadFile {
public static void uploadFileLink(String preSignedUrl, String sourceUrlString) {
HttpURLConnection connection = null;
try {
// 创建URL对象
URL url = new URL(preSignedUrl);
connection = (HttpURLConnection) url.openConnection();
// 设置请求方法用于文档上传,需与您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param中Method字段的值一致
connection.setRequestMethod("PUT");
// 允许向connection输出,因为这个连接是用于上传文档的
connection.setDoOutput(true);
connection.setRequestProperty("X-bailian-extra", "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param.Headers中X-bailian-extra字段的值");
connection.setRequestProperty("Content-Type", "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param.Headers中Content-Type字段的值(返回空值时,传空值即可)");
URL sourceUrl = new URL(sourceUrlString);
HttpURLConnection sourceConnection = (HttpURLConnection) sourceUrl.openConnection();
// 设置访问文档URL地址的请求方法为GET
sourceConnection.setRequestMethod("GET");
// 获取响应码,200表示请求成功
int sourceFileResponseCode = sourceConnection.getResponseCode();
// 从URL地址读取文档并通过连接上传
if (sourceFileResponseCode != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("Failed to get source file.");
}
try (DataOutputStream outStream = new DataOutputStream(connection.getOutputStream());
InputStream in = new BufferedInputStream(sourceConnection.getInputStream())) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = in.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. ResponseCode: " + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
public static void main(String[] args) {
String preSignedUrlOrHttpUrl = "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param中Url字段的值";
String sourceUrl = "请替换为您需要上传文档的URL地址";
uploadFileLink(preSignedUrlOrHttpUrl, sourceUrl);
}
}
PHP<?php
/**
* 将可通过公网访问的文档上传至临时存储
*
* @param string $preSignedUrl 从 ApplyFileUploadLease 接口获取的预签名 URL 或 HTTP 地址
* @param array $headers 包含 "X-bailian-extra" 和 "Content-Type" 的请求头数组
* @param string $sourceUrl 文档的URL地址
* @throws Exception 如果上传失败
*/
function uploadFile($preSignedUrl, $headers, $sourceUrl) {
$fileContent = file_get_contents($sourceUrl);
if ($fileContent === false) {
throw new Exception("无法从给定的URL地址下载文档: " . $sourceUrl);
}
// 初始化 cURL 会话
$ch = curl_init();
// 设置 cURL 选项
curl_setopt($ch, CURLOPT_URL, $preSignedUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); // 使用 PUT 方法
curl_setopt($ch, CURLOPT_POSTFIELDS, $fileContent); // 设置请求体为文档内容
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 返回响应结果而不是直接输出
// 构建请求头
$uploadHeaders = [
"X-bailian-extra: " . $headers["X-bailian-extra"],
"Content-Type: " . $headers["Content-Type"]
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $uploadHeaders);
// 执行请求
$response = curl_exec($ch);
// 获取 HTTP 响应码
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 关闭 cURL 会话
curl_close($ch);
// 检查响应码
if ($httpCode != 200) {
throw new Exception("上传失败,HTTP 状态码: " . $httpCode . ",错误信息: " . $response);
}
// 上传成功
echo "File uploaded successfully.\n";
}
/**
* 主函数:将可通过公网访问的文档上传至临时存储
*/
function main() {
// 请替换为您在上一步中调用 ApplyFileUploadLease 接口实际返回的 Data.Param 中 Url 字段的值
$preSignedUrl = "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param中Url字段的值";
// 请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param.Headers中的 X-bailian-extra 和 Content-Type
$headers = [
"X-bailian-extra" => "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param.Headers中X-bailian-extra字段的值",
"Content-Type" => "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param.Headers中Content-Type字段的值(返回空值时,传空值即可)"
];
$sourceUrl = "请替换为您需要上传文档的URL地址";
try {
uploadFile($preSignedUrl, $headers, $sourceUrl);
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
}
// 调用主函数
main();
?>
Node.jsconst axios = require('axios');
/**
* 将可通过公网访问的文档上传至临时存储
*
* @param {string} preSignedUrl - 上传租约中的URL
* @param {Object} headers - 上传请求的头部
* @param {string} sourceUrl - 文档的URL地址
* @throws {Error} 如果上传失败
*/
async function uploadFileFromUrl(preSignedUrl, headers, sourceUrl) {
// 构建上传所需的请求头
const uploadHeaders = {
"X-bailian-extra": headers["X-bailian-extra"],
"Content-Type": headers["Content-Type"]
};
try {
// 从给定的URL地址下载文档
const response = await axios.get(sourceUrl, {
responseType: 'stream'
});
// 使用 axios 发送 PUT 请求
const uploadResponse = await axios.put(preSignedUrl, response.data, {
headers: uploadHeaders
});
// 检查响应状态码
if (uploadResponse.status === 200) {
console.log("File uploaded successfully from URL.");
} else {
console.error(`Failed to upload the file. ResponseCode: ${uploadResponse.status}`);
throw new Error(`Upload failed with status code: ${uploadResponse.status}`);
}
} catch (error) {
// 处理错误
console.error("Error during upload:", error.message);
throw new Error(`上传失败: ${error.message}`);
}
}
/**
* 主函数:将一个可公开直接下载的文档上传到临时存储
*/
function main() {
const preSignedUrl = "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param中Url字段的值";
const headers = {
"X-bailian-extra": "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param.Headers中X-bailian-extra字段的值",
"Content-Type": "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param.Headers中Content-Type字段的值(返回空值时,传空值即可)"
};
const sourceUrl = "请替换为您需要上传文档的URL地址";
uploadFileFromUrl(preSignedUrl, headers, sourceUrl)
.then(() => {
console.log("Upload completed.");
})
.catch((err) => {
console.error("Upload failed:", err.message);
});
}
// 调用主函数
main();
C#using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
public class UploadFileExample
{
public static async Task UploadFileFromUrl(string preSignedUrl, string url)
{
try
{
// 创建 HTTP 客户端从给定的URL地址下载文档
using (HttpClient httpClient = new HttpClient())
{
HttpResponseMessage response = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
response.EnsureSuccessStatusCode();
// 获取文件流
using (Stream fileStream = await response.Content.ReadAsStreamAsync())
{
// 创建 URL 对象
Uri urlObj = new Uri(preSignedUrl);
HttpWebRequest connection = (HttpWebRequest)WebRequest.Create(urlObj);
// 设置请求方法用于文档上传
connection.Method = "PUT";
connection.AllowWriteStreamBuffering = false;
connection.SendChunked = false;
// 设置请求头(请替换为实际值)
connection.Headers["X-bailian-extra"] = "请替换为您在上一步中调用 ApplyFileUploadLease 接口实际返回的 Data.Param.Headers 中 X-bailian-extra 字段的值";
connection.ContentType = "请替换为您在上一步中调用 ApplyFileUploadLease 接口实际返回的 Data.Param.Headers 中 Content-Type 字段的值(返回空值时,传空值即可)";
// 获取请求流并写入文件流
using (Stream requestStream = connection.GetRequestStream())
{
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = await fileStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
await requestStream.WriteAsync(buffer, 0, bytesRead);
}
await requestStream.FlushAsync();
}
// 检查响应
using (HttpWebResponse responseResult = (HttpWebResponse)connection.GetResponse())
{
if (responseResult.StatusCode == HttpStatusCode.OK)
{
Console.WriteLine("File uploaded successfully from URL.");
}
else
{
Console.WriteLine($"Failed to upload the file. ResponseCode: {responseResult.StatusCode}");
}
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
}
}
public static async Task Main(string[] args)
{
string preSignedUrlOrHttpUrl = "请替换为您在上一步中调用 ApplyFileUploadLease 接口实际返回的 Data.Param 中 Url 字段的值";
string url = "请替换为您需要上传文档的URL地址";
await UploadFileFromUrl(preSignedUrlOrHttpUrl, url);
}
}
Gopackage main
import (
"fmt"
"net/http"
"github.com/go-resty/resty/v2"
)
// UploadFileFromUrl 将可通过公网访问的文档上传至临时存储。
//
// 参数:
// - preSignedUrl (string): 上传租约中的 URL。
// - headers (map[string]string): 上传请求的头部。
// - sourceUrl (string): 文档的URL地址。
//
// 返回:
// - error: 如果上传失败返回错误信息,否则返回 nil
func UploadFileFromUrl(preSignedUrl string, headers map[string]string, sourceUrl string) error {
// 从给定的URL地址下载文档
resp, err := http.Get(sourceUrl)
if err != nil {
return fmt.Errorf("获取文档失败: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("获取文档失败,状态码: %d", resp.StatusCode)
}
// 创建 REST 客户端
client := resty.New()
// 构建上传所需的请求头
uploadHeaders := map[string]string{
"X-bailian-extra": headers["X-bailian-extra"],
"Content-Type": headers["Content-Type"],
}
// 发送 PUT 请求
response, err := client.R().
SetHeaders(uploadHeaders).
SetBody(resp.Body).
Put(preSignedUrl)
if err != nil {
return fmt.Errorf("发送请求失败: %w", err)
}
if err != nil {
return fmt.Errorf("发送请求失败: %w", err)
}
// 检查 HTTP 响应状态码
if response.IsError() {
return fmt.Errorf("HTTP 错误: %d", response.StatusCode())
}
fmt.Println("File uploaded successfully from URL.")
return nil
}
// main 主函数
func main() {
// 请替换为您在上一步中调用 ApplyFileUploadLease 接口实际返回的 Data.Param 中 Url 字段的值
preSignedUrl := "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param中Url字段的值"
// 请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param.Headers中的 X-bailian-extra 和 Content-Type
headers := map[string]string{
"X-bailian-extra": "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param.Headers中X-bailian-extra字段的值",
"Content-Type": "请替换为您在上一步中调用ApplyFileUploadLease接口实际返回的Data.Param.Headers中Content-Type字段的值(返回空值时,传空值即可)",
}
sourceUrl := "请替换为您需要上传文档的URL地址"
// 调用上传函数
err := UploadFileFromUrl(preSignedUrl, headers, sourceUrl)
if err != nil {
fmt.Printf("上传失败: %v\n", err)
}
}
|
2.3. 添加文档到类目中阿里云百炼使用类目管理您上传的文档。因此,接下来您需要调用AddFile接口将已上传的文档添加到同一业务空间下的类目中。 parser:请传入DASHSCOPE_DOCMIND 。 lease_id:请传入申请文档上传租约时接口返回的Data.FileUploadLeaseId 。 category_id:本示例中,请传入default 。若您使用了自建类目上传,则需传入对应的category_id 。
完成添加后,阿里云百炼将返回该文档的FileId ,并自动开始解析您的文档。同时lease_id (租约ID)随即失效,请勿再使用相同的租约ID重复提交。 | Pythondef add_file(client: bailian20231229Client, lease_id: str, parser: str, category_id: str, workspace_id: str):
"""
将文档添加到阿里云百炼服务的指定类目中。
参数:
client (bailian20231229Client): 客户端(Client)。
lease_id (str): 租约ID。
parser (str): 用于文档的解析器。
category_id (str): 类目ID。
workspace_id (str): 业务空间ID。
返回:
阿里云百炼服务的响应。
"""
headers = {}
request = bailian_20231229_models.AddFileRequest(
lease_id=lease_id,
parser=parser,
category_id=category_id,
)
runtime = util_models.RuntimeOptions()
return client.add_file_with_options(workspace_id, request, headers, runtime)
Java/**
* 将文档添加到类目中。
*
* @param client 客户端对象
* @param leaseId 租约ID
* @param parser 用于文档的解析器
* @param categoryId 类目ID
* @param workspaceId 业务空间ID
* @return 阿里云百炼服务的响应对象
*/
public AddFileResponse addFile(com.aliyun.bailian20231229.Client client, String leaseId, String parser, String categoryId, String workspaceId) throws Exception {
Map<String, String> headers = new HashMap<>();
com.aliyun.bailian20231229.models.AddFileRequest addFileRequest = new com.aliyun.bailian20231229.models.AddFileRequest();
addFileRequest.setLeaseId(leaseId);
addFileRequest.setParser(parser);
addFileRequest.setCategoryId(categoryId);
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
return client.addFileWithOptions(workspaceId, addFileRequest, headers, runtime);
}
PHP/**
* 将文档添加到类目中。
*
* @param Bailian $client 客户端(Client)。
* @param string $leaseId 租约ID。
* @param string $parser 用于文档的解析器。
* @param string $categoryId 类目ID。
* @param string $workspaceId 业务空间ID。
* @return AddFileResponse 阿里云百炼服务的响应。
*/
public function addFile($client, $leaseId, $parser, $categoryId, $workspaceId) {
$headers = [];
$addFileRequest = new AddFileRequest([
"leaseId" => $leaseId,
"parser" => $parser,
"categoryId" => $categoryId
]);
$runtime = new RuntimeOptions([]);
return $client->addFileWithOptions($workspaceId, $addFileRequest, $headers, $runtime);
}
Node.js/**
* 添加文档到类目中
* @param {Bailian20231229Client} client - 客户端(Client)
* @param {string} leaseId - 租约ID
* @param {string} parser - 用于文档的解析器
* @param {string} categoryId - 类目ID
* @param {string} workspaceId - 业务空间ID
* @returns {Promise<bailian20231229.AddFileResponse>} - 阿里云百炼服务的响应
*/
async function addFile(client, leaseId, parser, categoryId, workspaceId) {
const headers = {};
const req = new bailian20231229.AddFileRequest({
leaseId,
parser,
categoryId
});
const runtime = new Util.RuntimeOptions({});
return await client.addFileWithOptions(workspaceId, req, headers, runtime);
}
C#/// <summary>
/// 将文档添加到类目中。
/// </summary>
/// <param name="client">客户端对象</param>
/// <param name="leaseId">租约ID</param>
/// <param name="parser">用于文档的解析器</param>
/// <param name="categoryId">类目ID</param>
/// <param name="workspaceId">业务空间ID</param>
/// <returns>阿里云百炼服务的响应对象</returns>
/// <exception cref="Exception">调用过程中发生错误时抛出异常</exception>
public AlibabaCloud.SDK.Bailian20231229.Models.AddFileResponse AddFile(
AlibabaCloud.SDK.Bailian20231229.Client client,
string leaseId,
string parser,
string categoryId,
string workspaceId)
{
var headers = new Dictionary<string, string>() { };
var addFileRequest = new AlibabaCloud.SDK.Bailian20231229.Models.AddFileRequest
{
LeaseId = leaseId,
Parser = parser,
CategoryId = categoryId
};
var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
return client.AddFileWithOptions(workspaceId, addFileRequest, headers, runtime);
}
Go// AddFile 将文档添加到阿里云百炼服务的指定类目中。
//
// 参数:
// - client (bailian20231229.Client): 客户端(Client)。
// - leaseId (string): 租约ID。
// - parser (string): 用于文档的解析器。
// - categoryId (string): 类目ID。
// - workspaceId (string): 业务空间ID。
//
// 返回:
// - *bailian20231229.AddFileResponse: 阿里云百炼服务的响应。
// - error: 错误信息。
func AddFile(client *bailian20231229.Client, leaseId, parser, categoryId, workspaceId string) (_result *bailian20231229.AddFileResponse, _err error) {
headers := make(map[string]*string)
addFileRequest := &bailian20231229.AddFileRequest{
LeaseId: tea.String(leaseId),
Parser: tea.String(parser),
CategoryId: tea.String(categoryId),
}
runtime := &util.RuntimeOptions{}
return client.AddFileWithOptions(tea.String(workspaceId), addFileRequest, headers, runtime)
}
请求示例 {
"CategoryId": "default",
"LeaseId": "d92bd94fa9b54326a2547415e100c9e2.1742195250069",
"Parser": "DASHSCOPE_DOCMIND",
"WorkspaceId": "llm-4u5xpd1xdjqpxxxx"
}
响应示例 {
"Status": "200",
"Message": "",
"RequestId": "5832A1F4-AF91-5242-8B75-35BDC9XXXXXX",
"Data": {
"FileId": "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx",
"Parser": "DASHSCOPE_DOCMIND"
},
"Code": "Success",
"Success": "true"
}
|
2.4. 查询文档的解析状态未解析完成的文档无法用于知识库,在请求高峰时段,该过程可能需要数小时。您可以调用DescribeFile接口查询文档的解析状态。 当本接口返回的Data.Status 字段值为PARSE_SUCCESS 时,表示文档已解析完成,可以将其导入知识库。 | Pythondef describe_file(client, workspace_id, file_id):
"""
获取文档的基本信息。
参数:
client (bailian20231229Client): 客户端(Client)。
workspace_id (str): 业务空间ID。
file_id (str): 文档ID。
返回:
阿里云百炼服务的响应。
"""
headers = {}
runtime = util_models.RuntimeOptions()
return client.describe_file_with_options(workspace_id, file_id, headers, runtime)
Java/**
* 查询文档的基本信息。
*
* @param client 客户端对象
* @param workspaceId 业务空间ID
* @param fileId 文档ID
* @return 阿里云百炼服务的响应对象
*/
public DescribeFileResponse describeFile(com.aliyun.bailian20231229.Client client, String workspaceId, String fileId) throws Exception {
Map<String, String> headers = new HashMap<>();
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
return client.describeFileWithOptions(workspaceId, fileId, headers, runtime);
}
PHP/**
* 查询文档的基本信息。
*
* @param Bailian $client 客户端(Client)。
* @param string $workspaceId 业务空间ID。
* @param string $fileId 文档ID。
* @return DescribeFileResponse 阿里云百炼服务的响应。
*/
public function describeFile($client, $workspaceId, $fileId) {
$headers = [];
$runtime = new RuntimeOptions([]);
return $client->describeFileWithOptions($workspaceId, $fileId, $headers, $runtime);
}
Node.js/**
* 查询文档的解析状态
* @param {Bailian20231229Client} client - 客户端(Client)
* @param {string} workspaceId - 业务空间ID
* @param {string} fileId - 文档ID
* @returns {Promise<bailian20231229.DescribeFileResponse>} - 阿里云百炼服务的响应
*/
async function describeFile(client, workspaceId, fileId) {
const headers = {};
const runtime = new Util.RuntimeOptions({});
return await client.describeFileWithOptions(workspaceId, fileId, headers, runtime);
}
C#/// <summary>
/// 查询文档的基本信息。
/// </summary>
/// <param name="client">客户端对象</param>
/// <param name="workspaceId">业务空间ID</param>
/// <param name="fileId">文档ID</param>
/// <returns>阿里云百炼服务的响应对象</returns>
/// <exception cref="Exception">调用过程中发生错误时抛出异常</exception>
public AlibabaCloud.SDK.Bailian20231229.Models.DescribeFileResponse DescribeFile(
AlibabaCloud.SDK.Bailian20231229.Client client,
string workspaceId,
string fileId)
{
var headers = new Dictionary<string, string>() { };
var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
return client.DescribeFileWithOptions(workspaceId, fileId, headers, runtime);
}
Go// DescribeFile 获取文档的基本信息。
//
// 参数:
// - client (bailian20231229.Client): 客户端(Client)。
// - workspaceId (string): 业务空间ID。
// - fileId (string): 文档ID。
//
// 返回:
// - any: 阿里云百炼服务的响应。
// - error: 错误信息。
func DescribeFile(client *bailian20231229.Client, workspaceId, fileId string) (_result *bailian20231229.DescribeFileResponse, _err error) {
headers := make(map[string]*string)
runtime := &util.RuntimeOptions{}
return client.DescribeFileWithOptions(tea.String(workspaceId), tea.String(fileId), headers, runtime)
}
请求示例 {
"FileId": "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx",
"WorkspaceId": "llm-4u5xpd1xdjqpxxxx"
}
响应示例 {
"Status": "200",
"Message": "",
"RequestId": "B9246251-987A-5628-8E1E-17BB39XXXXXX",
"Data": {
"CategoryId": "cate_206ea350f0014ea4a324adff1ca13011_10xxxxxx",
"Status": "PARSE_SUCCESS",
"FileType": "docx",
"CreateTime": "2025-03-17 15:47:13",
"FileName": "阿里云百炼系列手机产品介绍.docx",
"FileId": "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx",
"SizeInBytes": "14015",
"Parser": "DASHSCOPE_DOCMIND"
},
"Code": "Success",
"Success": "true"
}
|
3. 创建知识库 |
3.1. 初始化知识库文档解析完成后,您即可将其导入同一业务空间下的知识库。初始化(非最终提交)一个非结构化知识库,可以调用CreateIndex接口。 workspace_id:如何获取业务空间ID file_id:请传入添加文档到类目中时接口返回的FileId 。 若source_type为DATA_CENTER_FILE ,则该参数为必传,否则接口将报错。 structure_type:本示例中,请传入unstructured 。 结构化知识库不支持通过API创建,请使用阿里云百炼控制台创建。 source_type:本示例中,请传入DATA_CENTER_FILE 。 sink_type:本示例中,请传入BUILT_IN 。
本接口返回的Data.Id 字段值即为知识库ID,用于后续的索引构建。 请您妥善保管知识库ID,后续该知识库所有相关API操作都将用到它。 | Pythondef create_index(client, workspace_id, file_id, name, structure_type, source_type, sink_type):
"""
在阿里云百炼服务中创建知识库(初始化)。
参数:
client (bailian20231229Client): 客户端(Client)。
workspace_id (str): 业务空间ID。
file_id (str): 文档ID。
name (str): 知识库名称。
structure_type (str): 知识库的数据类型。
source_type (str): 应用数据的数据类型,支持类目类型和文档类型。
sink_type (str): 知识库的向量存储类型。
返回:
阿里云百炼服务的响应。
"""
headers = {}
request = bailian_20231229_models.CreateIndexRequest(
structure_type=structure_type,
name=name,
source_type=source_type,
sink_type=sink_type,
document_ids=[file_id]
)
runtime = util_models.RuntimeOptions()
return client.create_index_with_options(workspace_id, request, headers, runtime)
Java/**
* 在阿里云百炼服务中创建知识库(初始化)。
*
* @param client 客户端对象
* @param workspaceId 业务空间ID
* @param fileId 文档ID
* @param name 知识库名称
* @param structureType 知识库的数据类型
* @param sourceType 应用数据的数据类型,支持类目类型和文档类型
* @param sinkType 知识库的向量存储类型
* @return 阿里云百炼服务的响应对象
*/
public CreateIndexResponse createIndex(com.aliyun.bailian20231229.Client client, String workspaceId, String fileId, String name, String structureType, String sourceType, String sinkType) throws Exception {
Map<String, String> headers = new HashMap<>();
com.aliyun.bailian20231229.models.CreateIndexRequest createIndexRequest = new com.aliyun.bailian20231229.models.CreateIndexRequest();
createIndexRequest.setStructureType(structureType);
createIndexRequest.setName(name);
createIndexRequest.setSourceType(sourceType);
createIndexRequest.setSinkType(sinkType);
createIndexRequest.setDocumentIds(Collections.singletonList(fileId));
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
return client.createIndexWithOptions(workspaceId, createIndexRequest, headers, runtime);
}
PHP/**
* 在阿里云百炼服务中创建知识库(初始化)。
*
* @param Bailian $client 客户端(Client)。
* @param string $workspaceId 业务空间ID。
* @param string $fileId 文档ID。
* @param string $name 知识库名称。
* @param string $structureType 知识库的数据类型。
* @param string $sourceType 应用数据的数据类型,支持类目类型和文档类型。
* @param string $sinkType 知识库的向量存储类型。
* @return CreateIndexResponse 阿里云百炼服务的响应。
*/
public function createIndex($client, $workspaceId, $fileId, $name, $structureType, $sourceType, $sinkType) {
$headers = [];
$createIndexRequest = new CreateIndexRequest([
"structureType" => $structureType,
"name" => $name,
"sourceType" => $sourceType,
"documentIds" => [
$fileId
],
"sinkType" => $sinkType
]);
$runtime = new RuntimeOptions([]);
return $client->createIndexWithOptions($workspaceId, $createIndexRequest, $headers, $runtime);
}
Node.js/**
* 初始化知识库(索引)
* @param {Bailian20231229Client} client - 客户端(Client)
* @param {string} workspaceId - 业务空间ID
* @param {string} fileId - 文档ID
* @param {string} name - 知识库名称
* @param {string} structureType - 知识库的数据类型
* @param {string} sourceType - 应用数据的数据类型,支持类目类型和文档类型
* @param {string} sinkType - 知识库的向量存储类型
* @returns {Promise<bailian20231229.CreateIndexResponse>} - 阿里云百炼服务的响应
*/
async function createIndex(client, workspaceId, fileId, name, structureType, sourceType, sinkType) {
const headers = {};
const req = new bailian20231229.CreateIndexRequest({
name,
structureType,
documentIds: [fileId],
sourceType,
sinkType
});
const runtime = new Util.RuntimeOptions({});
return await client.createIndexWithOptions(workspaceId, req, headers, runtime);
}
C#/// <summary>
/// 在阿里云百炼服务中创建知识库(初始化)。
/// </summary>
/// <param name="client">客户端对象</param>
/// <param name="workspaceId">业务空间ID</param>
/// <param name="fileId">文档ID</param>
/// <param name="name">知识库名称</param>
/// <param name="structureType">知识库的数据类型</param>
/// <param name="sourceType">应用数据的数据类型,支持类目类型和文档类型</param>
/// <param name="sinkType">知识库的向量存储类型</param>
/// <returns>阿里云百炼服务的响应对象</returns>
/// <exception cref="Exception">调用过程中发生错误时抛出异常</exception>
public AlibabaCloud.SDK.Bailian20231229.Models.CreateIndexResponse CreateIndex(
AlibabaCloud.SDK.Bailian20231229.Client client,
string workspaceId,
string fileId,
string name,
string structureType,
string sourceType,
string sinkType)
{
var headers = new Dictionary<string, string>() { };
var createIndexRequest = new AlibabaCloud.SDK.Bailian20231229.Models.CreateIndexRequest
{
StructureType = structureType,
Name = name,
SourceType = sourceType,
SinkType = sinkType,
DocumentIds = new List<string> { fileId }
};
var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
return client.CreateIndexWithOptions(workspaceId, createIndexRequest, headers, runtime);
}
Go// CreateIndex 在阿里云百炼服务中创建知识库(初始化)。
//
// 参数:
// - client (bailian20231229.Client): 客户端(Client)。
// - workspaceId (string): 业务空间ID。
// - fileId (string): 文档ID。
// - name (string): 知识库名称。
// - structureType (string): 知识库的数据类型。
// - sourceType (string): 应用数据的数据类型,支持类目类型和文档类型。
// - sinkType (string): 知识库的向量存储类型。
//
// 返回:
// - *bailian20231229.CreateIndexResponse: 阿里云百炼服务的响应。
// - error: 错误信息。
func CreateIndex(client *bailian20231229.Client, workspaceId, fileId, name, structureType, sourceType, sinkType string) (_result *bailian20231229.CreateIndexResponse, _err error) {
headers := make(map[string]*string)
createIndexRequest := &bailian20231229.CreateIndexRequest{
StructureType: tea.String(structureType),
Name: tea.String(name),
SourceType: tea.String(sourceType),
SinkType: tea.String(sinkType),
DocumentIds: []*string{tea.String(fileId)},
}
runtime := &util.RuntimeOptions{}
return client.CreateIndexWithOptions(tea.String(workspaceId), createIndexRequest, headers, runtime)
}
请求示例 {
"Name": "阿里云百炼手机知识库",
"SinkType": "BUILT_IN",
"SourceType": "DATA_CENTER_FILE",
"StructureType": "unstructured",
"WorkspaceId": "llm-4u5xpd1xdjqpxxxx",
"DocumentIds": [
"file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx"
]
}
响应示例 {
"Status": "200",
"Message": "success",
"RequestId": "87CB0999-F1BB-5290-8C79-A875B2XXXXXX",
"Data": {
"Id": "mymxbdxxxx"
},
"Code": "Success",
"Success": "true"
}
|
3.2. 提交索引任务初始化知识库后,您需要调用SubmitIndexJob接口提交索引任务,以启动知识库的索引构建。 完成提交后,阿里云百炼随即以异步任务方式开始构建索引。本接口返回的Data.Id 为对应的任务ID。下一步中,您将用到此ID查询任务的最新状态。 | Pythondef submit_index(client, workspace_id, index_id):
"""
向阿里云百炼服务提交索引任务。
参数:
client (bailian20231229Client): 客户端(Client)。
workspace_id (str): 业务空间ID。
index_id (str): 知识库ID。
返回:
阿里云百炼服务的响应。
"""
headers = {}
submit_index_job_request = bailian_20231229_models.SubmitIndexJobRequest(
index_id=index_id
)
runtime = util_models.RuntimeOptions()
return client.submit_index_job_with_options(workspace_id, submit_index_job_request, headers, runtime))
Java/**
* 向阿里云百炼服务提交索引任务。
*
* @param client 客户端对象
* @param workspaceId 业务空间ID
* @param indexId 知识库ID
* @return 阿里云百炼服务的响应对象
*/
public SubmitIndexJobResponse submitIndex(com.aliyun.bailian20231229.Client client, String workspaceId, String indexId) throws Exception {
Map<String, String> headers = new HashMap<>();
com.aliyun.bailian20231229.models.SubmitIndexJobRequest submitIndexJobRequest = new com.aliyun.bailian20231229.models.SubmitIndexJobRequest();
submitIndexJobRequest.setIndexId(indexId);
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
return client.submitIndexJobWithOptions(workspaceId, submitIndexJobRequest, headers, runtime);
}
PHP/**
* 向阿里云百炼服务提交索引任务。
*
* @param Bailian $client 客户端(Client)。
* @param string $workspaceId 业务空间ID。
* @param string $indexId 知识库ID。
* @return SubmitIndexJobResponse 阿里云百炼服务的响应。
*/
public static function submitIndex($client, $workspaceId, $indexId) {
$headers = [];
$submitIndexJobRequest = new SubmitIndexJobRequest([
'indexId' => $indexId
]);
$runtime = new RuntimeOptions([]);
return $client->submitIndexJobWithOptions($workspaceId, $submitIndexJobRequest, $headers, $runtime);
}
Node.js/**
* 提交索引任务
* @param {Bailian20231229Client} client - 客户端(Client)
* @param {string} workspaceId - 业务空间ID
* @param {string} indexId - 知识库ID
* @returns {Promise<bailian20231229.SubmitIndexJobResponse>} - 阿里云百炼服务的响应
*/
async function submitIndex(client, workspaceId, indexId) {
const headers = {};
const req = new bailian20231229.SubmitIndexJobRequest({ indexId });
const runtime = new Util.RuntimeOptions({});
return await client.submitIndexJobWithOptions(workspaceId, req, headers, runtime);
}
C#/// <summary>
/// 向阿里云百炼服务提交索引任务。
/// </summary>
/// <param name="client">客户端对象</param>
/// <param name="workspaceId">业务空间ID</param>
/// <param name="indexId">知识库ID</param>
/// <returns>阿里云百炼服务的响应对象</returns>
/// <exception cref="Exception">调用过程中发生错误时抛出异常</exception>
public AlibabaCloud.SDK.Bailian20231229.Models.SubmitIndexJobResponse SubmitIndex(
AlibabaCloud.SDK.Bailian20231229.Client client,
string workspaceId,
string indexId)
{
var headers = new Dictionary<string, string>() { };
var submitIndexJobRequest = new AlibabaCloud.SDK.Bailian20231229.Models.SubmitIndexJobRequest
{
IndexId = indexId
};
var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
return client.SubmitIndexJobWithOptions(workspaceId, submitIndexJobRequest, headers, runtime);
}
Go// SubmitIndex 提交索引任务。
//
// 参数:
// - client (bailian20231229.Client): 客户端(Client)。
// - workspaceId (string): 业务空间ID。
// - indexId (string): 知识库ID。
//
// 返回:
// - *bailian20231229.SubmitIndexJobResponse: 阿里云百炼服务的响应。
// - error: 错误信息。
func SubmitIndex(client *bailian20231229.Client, workspaceId, indexId string) (_result *bailian20231229.SubmitIndexJobResponse, _err error) {
headers := make(map[string]*string)
submitIndexJobRequest := &bailian20231229.SubmitIndexJobRequest{
IndexId: tea.String(indexId),
}
runtime := &util.RuntimeOptions{}
return client.SubmitIndexJobWithOptions(tea.String(workspaceId), submitIndexJobRequest, headers, runtime)
}
请求示例 {
"IndexId": "mymxbdxxxx",
"WorkspaceId": "llm-4u5xpd1xdjqpxxxx"
}
响应示例 {
"Status": "200",
"Message": "success",
"RequestId": "7774575F-571D-5854-82C2-634AB8XXXXXX",
"Data": {
"IndexId": "mymxbdxxxx",
"Id": "3cd6fb57aaf44cd0b4dd2ca584xxxxxx"
},
"Code": "Success",
"Success": "true"
}
|
3.3. 等待索引任务完成索引任务的执行需要一定时间,在请求高峰时段,该过程可能需要数小时。查询其执行状态可以调用GetIndexJobStatus接口。 当本接口返回的Data.Status 字段值为COMPLETED 时,表示知识库已创建完成。 | Pythondef get_index_job_status(client, workspace_id, index_id, job_id):
"""
查询索引任务状态。
参数:
client (bailian20231229Client): 客户端(Client)。
workspace_id (str): 业务空间ID。
index_id (str): 知识库ID。
job_id (str): 任务ID。
返回:
阿里云百炼服务的响应。
"""
headers = {}
get_index_job_status_request = bailian_20231229_models.GetIndexJobStatusRequest(
index_id=index_id,
job_id=job_id
)
runtime = util_models.RuntimeOptions()
return client.get_index_job_status_with_options(workspace_id, get_index_job_status_request, headers, runtime)
Java/**
* 查询索引任务状态。
*
* @param client 客户端对象
* @param workspaceId 业务空间ID
* @param jobId 任务ID
* @param indexId 知识库ID
* @return 阿里云百炼服务的响应对象
*/
public GetIndexJobStatusResponse getIndexJobStatus(com.aliyun.bailian20231229.Client client, String workspaceId, String jobId, String indexId) throws Exception {
Map<String, String> headers = new HashMap<>();
com.aliyun.bailian20231229.models.GetIndexJobStatusRequest getIndexJobStatusRequest = new com.aliyun.bailian20231229.models.GetIndexJobStatusRequest();
getIndexJobStatusRequest.setIndexId(indexId);
getIndexJobStatusRequest.setJobId(jobId);
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
GetIndexJobStatusResponse getIndexJobStatusResponse = null;
getIndexJobStatusResponse = client.getIndexJobStatusWithOptions(workspaceId, getIndexJobStatusRequest, headers, runtime);
return getIndexJobStatusResponse;
}
PHP/**
* 查询索引任务状态。
*
* @param Bailian $client 客户端(Client)。
* @param string $workspaceId 业务空间ID。
* @param string $indexId 知识库ID。
* @param string $jobId 任务ID。
* @return GetIndexJobStatusResponse 阿里云百炼服务的响应。
*/
public function getIndexJobStatus($client, $workspaceId, $jobId, $indexId) {
$headers = [];
$getIndexJobStatusRequest = new GetIndexJobStatusRequest([
'indexId' => $indexId,
'jobId' => $jobId
]);
$runtime = new RuntimeOptions([]);
return $client->getIndexJobStatusWithOptions($workspaceId, $getIndexJobStatusRequest, $headers, $runtime);
}
Node.js/**
* 查询索引任务状态
* @param {Bailian20231229Client} client - 客户端(Client)
* @param {string} workspaceId - 业务空间ID
* @param {string} jobId - 任务ID
* @param {string} indexId - 知识库ID
* @returns {Promise<bailian20231229.GetIndexJobStatusResponse>} - 阿里云百炼服务的响应
*/
async function getIndexJobStatus(client, workspaceId, jobId, indexId) {
const headers = {};
const req = new bailian20231229.GetIndexJobStatusRequest({ jobId, indexId });
const runtime = new Util.RuntimeOptions({});
return await client.getIndexJobStatusWithOptions(workspaceId, req, headers, runtime);
}
C#/// <summary>
/// 查询索引任务状态。
/// </summary>
/// <param name="client">客户端对象</param>
/// <param name="workspaceId">业务空间ID</param>
/// <param name="jobId">任务ID</param>
/// <param name="indexId">知识库ID</param>
/// <returns>阿里云百炼服务的响应对象</returns>
/// <exception cref="Exception">调用过程中发生错误时抛出异常</exception>
public AlibabaCloud.SDK.Bailian20231229.Models.GetIndexJobStatusResponse GetIndexJobStatus(
AlibabaCloud.SDK.Bailian20231229.Client client,
string workspaceId,
string jobId,
string indexId)
{
var headers = new Dictionary<string, string>() { };
var getIndexJobStatusRequest = new AlibabaCloud.SDK.Bailian20231229.Models.GetIndexJobStatusRequest
{
IndexId = indexId,
JobId = jobId
};
var runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
return client.GetIndexJobStatusWithOptions(workspaceId, getIndexJobStatusRequest, headers, runtime);
}
Go// GetIndexJobStatus 查询索引任务状态。
//
// 参数:
// - client (bailian20231229.Client): 客户端(Client)。
// - workspaceId (string): 业务空间ID。
// - jobId (string): 任务ID。
// - indexId (string): 知识库ID。
//
// 返回:
// - *bailian20231229.GetIndexJobStatusResponse: 阿里云百炼服务的响应。
// - error: 错误信息。
func GetIndexJobStatus(client *bailian20231229.Client, workspaceId, jobId, indexId string) (_result *bailian20231229.GetIndexJobStatusResponse, _err error) {
headers := make(map[string]*string)
getIndexJobStatusRequest := &bailian20231229.GetIndexJobStatusRequest{
JobId: tea.String(jobId),
IndexId: tea.String(indexId),
}
runtime := &util.RuntimeOptions{}
return client.GetIndexJobStatusWithOptions(tea.String(workspaceId), getIndexJobStatusRequest, headers, runtime)
}
请求示例 {
"IndexId": "mymxbdxxxx",
"JobId": "3cd6fb57aaf44cd0b4dd2ca584xxxxxx",
"WorkspaceId": "llm-4u5xpd1xdjqpxxxx"
}
响应示例 {
"Status": "200",
"Message": "success",
"RequestId": "E83423B9-7D6D-5283-836B-CF7EAEXXXXXX",
"Data": {
"Status": "COMPLETED",
"Documents": [
{
"Status": "FINISH",
"DocId": "file_0b21e0a852cd40cd9741c54fefbb61cd_10xxxxxx",
"Message": "导入成功",
"DocName": "阿里云百炼系列手机产品介绍",
"Code": "FINISH"
}
],
"JobId": "3cd6fb57aaf44cd0b4dd2ca584xxxxxx"
},
"Code": "Success",
"Success": "true"
}
|