Upload a file
Use the dynamic file operation APIs to retrieve information about processed files. Agent applications can use these APIs to inject file data into the Dynamic Document Parsing tool using the parameters.agent_options.session_files parameter in your API calls.
File upload credential
Obtain a temporary dynamic file upload credential for subsequent document parsing operations.
Request syntax
POST /deep-search-agent/file/lease/apply HTTP/1.1
Request parameters
Parameter | Type | Required | Description |
|---|---|---|---|
input | object | Yes | The input field. |
input.request_id | string | No | A custom request ID for your business. |
input.file_name | string | Yes | The name of the file to upload. |
input.file_md5 | string | Yes | The MD5 hash of the file to upload. |
input.file_size | int | Yes | The size of the file to upload. |
parameters | object | Yes | Configuration parameters. Leave this empty {} for this API. |
Response parameters
Parameter | Type | Required | Description |
|---|---|---|---|
code | string | Yes | The status code. A value of 200 indicates success. |
message | string | Yes | The status message. |
output | object | Yes | The output field. |
output.request_id | string | No | A custom request ID for your business. |
output.result | object | Yes | The file processing result. |
output.result.headers | map[str, str] | Yes | The header information for uploading the file. |
output.result.lease_id | string | Yes | The credential ID. |
output.result.pre_signed_url | string | Yes | The pre-signed URL for Object Storage Service (OSS). |
Examples
Request example
{
"input": {
"request_id": "8d1c3d50-b761-4730-ac1a-27a248fa08b5",
"file_name": "deep_search_test_document.txt",
"file_md5": "****",
"file_size": 512
},
"parameters": {},
"stream": false
}
Response example
{
"code": "200",
"message": "Success",
"output": {
"request_id": "8d1c3d50-b761-4730-ac1a-27a248fa08b5",
"result": {
"headers": {
"Content-Type": "text/plain",
"x-bailian-extra": "MTU***U5Mw=="
},
"lease_id": "c00863829e***8218548747",
"pre_signed_url": "https://das***center.oss-cn-beijing.aliyuncs.com***b71234fae68.1758218548747.txt?Exp***"
}
}
}
Upload a file
You can upload the file from your client. The following code shows how to upload a file using the file upload credential.
import requests
from http import HTTPStatus
headers = {
"Content-Type": "$output.result.headers['Content-Type']",
"x-bailian-extra": "$output.result.headers['x-bailian-extra']"
}
pre_signed_url = "$output.result.pre_signed_url"
file_path = "deep_search_test_document.txt"
with open(file_path, 'rb') as file:
response = requests.put(pre_signed_url, data=file, headers=headers)
if response.status_code == HTTPStatus.OK:
print("File uploaded successfully.")
else:
print(f"File upload failed, {response.status_code}")
Submit a file for parsing
After you upload the temporary dynamic file, you can submit the document for parsing using the file upload credential.
Request syntax
POST /deep-search-agent/file/parse/submit HTTP/1.1
Request parameters
Parameter name | Type | Required | Description |
|---|---|---|---|
input | object | Yes | The input field. |
input.request_id | string | No | A custom request ID for your business. |
input.lease_id | str | Yes | The credential ID of the uploaded file. |
parameters | object | Yes | Configuration parameters. Leave this empty {} for this API. |
Response parameters
Parameter | Type | Required | Description |
|---|---|---|---|
code | string | Yes | The status code. A value of 200 indicates success. |
message | string | Yes | The status message. |
output | object | Yes | The output field. |
output.request_id | string | No | A custom request ID for your business. |
output.result | array<object> | Yes | The file processing result. |
output.result.file_id | string | Yes | The ID of the file submitted for parsing. |
Examples
Request example
{
"input": {
"request_id": "4fc80fa9-b66a-4c6a-9dab-1a79ecd972f2",
"lease_id": "c00863829e***8218548747"
},
"parameters": {}
}
Response example
{
"code": "200",
"message": "Success",
"output": {
"request_id": "4fc80fa9-b66a-4c6a-9dab-1a79ecd972f2",
"result": [
{
"file_id": "file_session_ec4803e***409"
}
]
}
}
Get parsing status
After you submit a temporary dynamic file for parsing, you can query the parsing status using the file ID.
Request syntax
POST /deep-search-agent/file/parse/status HTTP/1.1
Request parameters
Parameter | Type | Required | Description |
|---|---|---|---|
input | object | Yes | The input field. |
input.request_id | string | No | A custom request ID for your business. |
input.file_ids | list[str] | Yes | A list of file IDs submitted for parsing. |
parameters | object | Yes | Configuration parameters. Leave this empty {} for this API. |
Response parameters
Parameter | Type | Required | Description |
|---|---|---|---|
code | string | Yes | The status code. A value of 200 indicates success. |
message | string | Yes | The status message. |
output | object | Yes | The output field. |
output.request_id | string | No | A custom request ID for your business. |
output.result | array<object> | Yes | The file processing result. |
output.result.[0].status | string | Yes | The processing status of the file submitted for parsing. |
File statuses
The file status can be one of the following:
- Note: You must wait until the status is FILE_IS_READY before you can perform Q&A pairs.
- File parsing
● INIT: Pending parsing.
● PARSING: Parsing.
● PARSE_SUCCESS: Parsing completed.
● PARSE_FAILED: Parsing failed.
- Index building
● SAFE_CHECKING: Security check in progress.
● SAFE_CHECK_FAILED: Security check failed.
● INDEX_BUILDING: Building index.
● INDEX_BUILD_SUCCESS: Index built successfully.
● INDEX_BUILDING_FAILED: Index building failed.
● INDEX_DELETED: File index deleted.
● FILE_IS_READY: File is ready.
● FILE_EXPIRED: File expired.
Examples
Request example
{
"input": {
"request_id": "bbe29140-766b-4caf-8558-2c703d9cb641",
"file_ids": [
"file_session_ec4803e***409"
]
},
"parameters": {}
}
Response example
{
"code": "200",
"message": "Success",
"output": {
"request_id": "bbe29140-766b-4caf-8558-2c703d9cb641",
"result": [
{
"status": "FILE_IS_READY"
}
]
}
}
Call examples
# coding=utf-8
import os
import sys
import uuid
import json
import time
import hashlib
import requests
from http import HTTPStatus
apply_lease_url = "https://dashscope.aliyuncs.com/api/v2/apps/deep-search-agent/file/lease/apply"
submit_file_url = "https://dashscope.aliyuncs.com/api/v2/apps/deep-search-agent/file/parse/submit"
parse_status_url = "https://dashscope.aliyuncs.com/api/v2/apps/deep-search-agent/file/parse/status"
headers = {
'Authorization': f'Bearer {os.getenv("DASHSCOPE_API_KEY", "")}', # Configure the API key.
'Content-Type': 'application/json'
}
def get_file_upload_info(file_path: str) -> dict:
if not os.path.exists(file_path):
raise Exception("file not exists")
file_name = os.path.basename(file_path)
file_size = os.path.getsize(file_path)
with open(file_path, 'rb') as f:
md5 = hashlib.md5()
while True:
data = f.read(4096)
if not data:
break
md5.update(data)
file_md5 = md5.hexdigest()
return {"file_name": file_name, "file_size": file_size, "md5": file_md5}
if __name__ == "__main__":
if len(sys.argv) != 2:
print("usage: python deep_search_demo.py <file_path>")
exit(1)
file_path = sys.argv[1]
file_info = get_file_upload_info(file_path)
file_name: str = file_info["file_name"]
file_size: int = file_info["file_size"]
file_md5: str = file_info["md5"]
# 1. Apply for a lease.
apply_lease_params = {
"request_id": str(uuid.uuid4()),
"input": {
"file_name": file_name,
"file_size": file_size,
"file_md5": file_md5
},
"parameters": {}
}
response = requests.post(apply_lease_url, json=apply_lease_params, headers=headers)
lease_data = {}
if response.status_code == HTTPStatus.OK:
print("1. Lease applied successfully.")
lease_data = response.json()["output"]["result"]
print(json.dumps(lease_data, indent=2, ensure_ascii=False))
else:
print(f'code={response.status_code}')
exit(1)
# 2. Upload the file.
upload_headers = lease_data["headers"]
lease_id = lease_data["lease_id"]
pre_signed_url = lease_data["pre_signed_url"]
with open(file_path, 'rb') as file:
# The request method used for the upload must match the Method value returned by the ApplyFileUploadLease API in the previous step.
response = requests.put(pre_signed_url, data=file, headers=upload_headers)
if response.status_code == HTTPStatus.OK:
print("2. File uploaded successfully.")
else:
print(f"Failed to upload the file. ResponseCode: {response.status_code}")
exit(1)
# 3. Submit for parsing.
submit_file_params = {
"request_id": str(uuid.uuid4()),
"input": {
"lease_id": lease_data["lease_id"]
},
"parameters": {}
}
response = requests.post(submit_file_url, json=submit_file_params, headers=headers)
if response.status_code == HTTPStatus.OK:
print("3. File submitted for parsing successfully.")
submit_data = response.json()["output"]["result"][0]
print(json.dumps(response.json(), indent=2, ensure_ascii=False))
else:
submit_data = response.json()
print(f'response={response.json()}')
print(f'code={response.status_code}')
exit(1)
# 4. Get the parsing status.
parse_status_params = {
"request_id": str(uuid.uuid4()),
"input": {
"file_ids": [
submit_data["file_id"]
]
},
"parameters": {}
}
_start_time = time.time()
while True:
response = requests.post(parse_status_url, json=parse_status_params, headers=headers)
_process_time = time.time() - _start_time
if response.status_code == HTTPStatus.OK:
parse_status = response.json()["output"]["result"]
print(json.dumps(parse_status, indent=2, ensure_ascii=False))
file_status = parse_status[0]["status"]
print(f"4. Check file process status: {file_status}. process time: {_process_time}")
if file_status == "FILE_IS_READY":
print("5. File processed successfully.")
exit(0)
else:
print(f'response={response.json()}')
print(f'code={response.status_code}')
try:
if _process_time > 1800:
print(f'File processing timed out [>1800s]: {_process_time}')
exit(1)
time.sleep(10)
except Exception as e:
pass
import java.io.*;
import java.net.*;
import java.util.*;
import java.nio.file.*;
import java.security.MessageDigest;
import com.alibaba.fastjson.*;
import java.nio.charset.StandardCharsets;
public class DeepSearchDemo {
private static final String APPLY_LEASE_URL = "https://dashscope.aliyuncs.com/api/v2/apps/deep-search-agent/file/lease/apply";
private static final String SUBMIT_FILE_URL = "https://dashscope.aliyuncs.com/api/v2/apps/deep-search-agent/file/parse/submit";
private static final String PARSE_STATUS_URL = "https://dashscope.aliyuncs.com/api/v2/apps/deep-search-agent/file/parse/status";
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.out.println("usage: java DeepSearchDemo <file_path>");
System.exit(1);
}
String apiKey = System.getenv("DASHSCOPE_API_KEY");
if (apiKey == null || apiKey.isEmpty()) {
System.out.println("Please set the DASHSCOPE_API_KEY environment variable.");
System.exit(1);
}
String filePath = args[0];
File file = new File(filePath);
if (!file.exists()) {
throw new Exception("file not exists");
}
String fileName = file.getName();
long fileSize = file.length();
String fileMd5 = calculateMD5(filePath);
// 1. Apply for a lease.
Map<String, Object> applyLeaseParams = new HashMap<>();
applyLeaseParams.put("request_id", UUID.randomUUID().toString());
// input
Map<String, Object> applyLeaseInput = new HashMap<>();
applyLeaseInput.put("file_name", fileName);
applyLeaseInput.put("file_size", fileSize);
applyLeaseInput.put("file_md5", fileMd5);
applyLeaseParams.put("input", applyLeaseInput);
applyLeaseParams.put("parameters", new HashMap<>());
// HTTP request
URL applyLeaseUrl = new URL(APPLY_LEASE_URL);
HttpURLConnection applyLeaseConn = (HttpURLConnection) applyLeaseUrl.openConnection();
applyLeaseConn.setRequestMethod("POST");
applyLeaseConn.setDoOutput(true);
applyLeaseConn.setRequestProperty("Authorization", "Bearer " + apiKey);
applyLeaseConn.setRequestProperty("Content-Type", "application/json");
// Send the body.
try (OutputStream os = applyLeaseConn.getOutputStream()) {
os.write(JSON.toJSONString(applyLeaseParams).getBytes(StandardCharsets.UTF_8));
}
JSONObject leaseData = null;
if (applyLeaseConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
System.out.println("1. Lease applied successfully.");
String responseBody;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(applyLeaseConn.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
responseBody = sb.toString();
}
JSONObject respJson = JSON.parseObject(responseBody);
leaseData = respJson.getJSONObject("output").getJSONObject("result");
System.out.println(leaseData.toJSONString());
} else {
System.out.println("code=" + applyLeaseConn.getResponseCode());
// Print the error response.
try (BufferedReader reader = new BufferedReader(new InputStreamReader(applyLeaseConn.getErrorStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
System.exit(1);
}
}
// 2. Upload the file.
String uploadHeaders = leaseData.getString("headers");
String preSignedUrl = leaseData.getString("pre_signed_url");
URL uploadUrl = new URL(preSignedUrl);
HttpURLConnection uploadConn = (HttpURLConnection) uploadUrl.openConnection();
uploadConn.setRequestMethod("PUT");
uploadConn.setDoOutput(true);
JSONObject uploadHeadersObject = JSON.parseObject(uploadHeaders);
for (Map.Entry<String, Object> entry : uploadHeadersObject.entrySet()) {
uploadConn.setRequestProperty(entry.getKey(), entry.getValue().toString());
}
try (OutputStream os = uploadConn.getOutputStream(); InputStream fis = Files.newInputStream(Paths.get(filePath))) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
}
if (uploadConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
System.out.println("2. File uploaded successfully.");
} else {
System.out.println("Failed to upload the file. ResponseCode: " + uploadConn.getResponseCode());
System.exit(1);
}
// 3. Submit for parsing.
Map<String, Object> submitFileParams = new HashMap<>();
submitFileParams.put("request_id", UUID.randomUUID().toString());
// input
Map<String, Object> submitFileInput = new HashMap<>();
submitFileInput.put("lease_id", leaseData.getString("lease_id"));
submitFileParams.put("input", submitFileInput);
submitFileParams.put("parameters", new HashMap<>());
URL submitFileUrl = new URL(SUBMIT_FILE_URL);
HttpURLConnection submitFileConn = (HttpURLConnection) submitFileUrl.openConnection();
submitFileConn.setRequestMethod("POST");
submitFileConn.setDoOutput(true);
submitFileConn.setRequestProperty("Authorization", "Bearer " + apiKey);
submitFileConn.setRequestProperty("Content-Type", "application/json");
try (OutputStream os = submitFileConn.getOutputStream()) {
os.write(JSON.toJSONString(submitFileParams).getBytes(StandardCharsets.UTF_8));
}
JSONObject submitData = null;
if (submitFileConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
System.out.println("3. File submitted for parsing successfully.");
String responseBody;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(submitFileConn.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
responseBody = sb.toString();
}
JSONObject respJson = JSON.parseObject(responseBody);
JSONArray resultArr = respJson.getJSONObject("output").getJSONArray("result");
submitData = resultArr.getJSONObject(0);
System.out.println(submitData.toJSONString());
} else {
System.out.println("code=" + submitFileConn.getResponseCode());
System.exit(1);
}
// 4. Get the parsing status.
Map<String, Object> parseStatusParams = new HashMap<>();
parseStatusParams.put("request_id", UUID.randomUUID().toString());
// input
Map<String, Object> parseStatusInput = new HashMap<>();
parseStatusInput.put("file_ids", new JSONArray().fluentAdd(submitData.getString("file_id")));
long startTime = System.currentTimeMillis();
while (true) {
URL parseStatusUrl = new URL(PARSE_STATUS_URL);
HttpURLConnection parseStatusConn = (HttpURLConnection) parseStatusUrl.openConnection();
parseStatusConn.setRequestMethod("POST");
parseStatusConn.setDoOutput(true);
parseStatusConn.setRequestProperty("Authorization", "Bearer " + apiKey);
parseStatusConn.setRequestProperty("Content-Type", "application/json");
try (OutputStream os = parseStatusConn.getOutputStream()) {
os.write(JSON.toJSONString(parseStatusParams).getBytes(StandardCharsets.UTF_8));
}
JSONArray parseStatusData = null;
if (parseStatusConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
String responseBody;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(parseStatusConn.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
responseBody = sb.toString();
}
JSONObject respJson = JSON.parseObject(responseBody);
parseStatusData = respJson.getJSONObject("output").getJSONArray("result");
System.out.println(parseStatusData.toJSONString());
String fileStatus = parseStatusData.getJSONObject(0).getString("status");
if ("FILE_IS_READY".equals(fileStatus)) {
System.out.println("5. File processed successfully.");
System.exit(0);
}
} else {
System.out.println("code=" + parseStatusConn.getResponseCode());
}
long processTime = (System.currentTimeMillis() - startTime) / 1000;
if (processTime > 1800) {
System.out.println("File processing timed out [>1800s]: " + processTime);
System.exit(1);
}
Thread.sleep(10000);
}
}
private static String calculateMD5(String filePath) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
try (InputStream is = Files.newInputStream(Paths.get(filePath))) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
md.update(buffer, 0, bytesRead);
}
}
byte[] digest = md.digest();
StringBuilder sb = new StringBuilder();
for (byte b : digest) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
}