Skip to main content

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
Agent Development
Agent Context
Agent Governance & Evolution
Store
Application Marketplace