Multimodal file operations
For a smoother experience with multimodal web search, use the file interface to pre-upload images to OSS and provide their OSS URLs to the web search agent during the Q&A session.
Get a pre-signed OSS upload URL
Retrieves a pre-signed URL for uploading files to OSS.
POST /web-search-agent/file/upload/apply HTTP/1.1
Request parameters
Parameter | Type | Required | Description |
|---|---|---|---|
input | object | Yes | A container for the request parameters. |
input.session_id | str | Yes | File operation session ID (user-defined) |
input.files | array | Yes | A list of files to upload. |
input.files[].file_name | str | Yes | The name of the file. |
input.files[].file_size | int | Yes | The size of the file in bytes. |
input.files[].content_type | str | Yes | The file MIME type |
parameters | object | Yes | Configuration parameters. |
parameters.agent_options | object | Yes | Agent configuration options |
parameters.agent_options.agent_id | str | Yes | The Agent ID. |
Response parameters
Parameter | Type | Required | Description |
|---|---|---|---|
code | str | Yes | The status code. A value of 200 indicates success. |
message | str | Yes | The status message. |
output | object | Yes | A container for the response data. |
output.request_id | str | No | The request ID. |
output.result | object | Yes | The file processing result. |
output.result.upload_tasks | array | Yes | A list of upload tasks. |
output.result.upload_tasks[].file_id | str | Yes | The file ID. |
output.result.upload_tasks[].file_name | str | Yes | The name of the file. |
output.result.upload_tasks[].upload_url | str | Yes | OSS pre-signed upload URL |
output.result.upload_tasks[].expire_at | int | Yes | Upload URL expiration time (Unix timestamp), valid for one hour by default |
Upload the file
After you get the OSS presigned upload URL, run the following command to upload your local file. The ${output.result.upload_tasks[].upload_url} placeholder is the presigned upload URL returned by the Get a pre-signed OSS upload URL operation.
curl -X PUT -T ./path/to/test.jpg -H "Content-Type: image/jpeg" ${output.result.upload_tasks[].upload_url}
Check file upload status
Call this endpoint to check the result of a file upload.
POST /web-search-agent/file/upload/callback HTTP/1.1
Request parameters
Parameter | Type | Required | Description |
|---|---|---|---|
input | object | Yes | Contains the request parameters. |
input.session_id | str | Yes | File operation session ID (user-defined) |
input.file_id | str | Yes | The file ID (returned when you request an upload URL) |
parameters | object | Yes | Configuration parameters. |
parameters.agent_options | object | Yes | Agent configuration options |
parameters.agent_options.agent_id | str | Yes | The Agent ID. |
Response parameters
Parameter | Type | Required | Description |
|---|---|---|---|
code | str | Yes | The status code. A value of 200 indicates success. |
message | str | Yes | The status message. |
output | object | Yes | Contains the response data. |
output.request_id | str | No | The unique ID for the request, which can be used for troubleshooting. |
output.result | object | Yes | Contains the result of the operation. |
output.result.status | str | Yes | The upload status. A value of SUCCESS indicates a successful upload. |
Get file information
Returns the status of one or more uploaded files.
POST /web-search-agent/file/info/get HTTP/1.1
Request parameters
Parameter | Type | Required | Description |
|---|---|---|---|
input | object | Yes | The request parameters. |
input.session_id | str | Yes | File operation session ID (user-defined) |
input.file_ids | array[str] | Yes | An array of file IDs. |
parameters | object | Yes | Configuration parameters. |
parameters.agent_options | object | Yes | Agent configuration options |
parameters.agent_options.agent_id | str | Yes | The agent ID. |
Response parameters
Parameter | Type | Required | Description |
|---|---|---|---|
code | str | Yes | The status code. A value of 200 indicates success. |
message | str | Yes | The status message. |
output | object | Yes | The response data. |
output.request_id | str | No | The request ID. |
output.result | object | Yes | The result of the operation. |
output.result[].file_id | str | Yes | The file ID. |
output.result[].file_name | str | Yes | The file name. |
output.result[].file_size | int | Yes | The file size, in bytes. |
output.result[].content_type | str | Yes | The file MIME type |
output.result[].preview_url | str | Yes | File preview URL (OSS pre-signed URL) |
output.result[].expire_at | int | Yes | Preview URL expiration time (Unix timestamp) |
output.result[].status | str | Yes | The status of the file. For example, 'done'. |
Delete file
Deletes uploaded files.
POST /web-search-agent/file/delete HTTP/1.1
Request parameters
Parameter | Type | Required | Description |
|---|---|---|---|
input | object | Yes | A container for the input parameters. |
input.session_id | str | Yes | File operation session ID (user-defined) |
input.file_ids | array[str] | Yes | A list of IDs for the files to be deleted. |
parameters | object | Yes | Specifies configuration parameters for the operation. |
parameters.agent_options | object | Yes | Agent configuration options |
parameters.agent_options.agent_id | str | Yes | The ID of the agent that performs the operation. |
Response parameters
Parameter | Type | Required | Description |
|---|---|---|---|
code | str | Yes | The status code. A value of 200 indicates success. |
message | str | Yes | A message that describes the status of the request. |
output | object | Yes | Contains the results of the operation. |
output.request_id | str | No | The unique ID for the request, used for troubleshooting. |
output.result | object | Yes | The results of the file deletion operation. |
output.result[].status | str | Yes | The deletion status. A value of SUCCESS indicates success. |
Example
# coding=utf-8
import os
import json
import requests
from http import HTTPStatus
# base URL
BASE_URL = "https://dashscope.aliyuncs.com/api/v2/apps/web-search-agent"
# Four API endpoint URLs
get_upload_url = f"{BASE_URL}/file/upload/apply"
upload_callback = f"{BASE_URL}/file/upload/callback"
get_file_info = f"{BASE_URL}/file/info/get"
delete_file = f"{BASE_URL}/file/delete"
# request header
headers = {
'Authorization': f'Bearer {os.getenv("DASHSCOPE_API_KEY", "")}', # Configure your API key
'Content-Type': 'application/json'
}
# agent options
AGENT_OPTIONS = {
"agent_id": "aid-xxx",
}
def call_get_upload_url(session_id: str, files: list) -> dict:
"""Gets the file upload URL.
Args:
session_id: The session ID.
files: A list of files. Each file contains file_name, file_size, content_type, and file_ext.
Returns:
The upload task information, which contains the upload_tasks list.
"""
params = {
"input": {
"session_id": session_id,
"files": files
},
"parameters": {
"agent_options": AGENT_OPTIONS
}
}
response = requests.post(get_upload_url, json=params, headers=headers)
if response.status_code == HTTPStatus.OK:
result = response.json()
print("Successfully retrieved the upload URL:")
print(json.dumps(result, indent=2, ensure_ascii=False))
return result["output"]["result"]
else:
print(f'Failed to get the upload URL: code={response.status_code}')
print(f'response={response.text}')
raise Exception(f"Failed to get the upload URL: {response.status_code}")
def call_upload_callback(session_id: str, file_id: str) -> dict:
"""Performs the upload callback after a file is uploaded.
Args:
session_id: The session ID.
file_id: The file ID.
Returns:
The callback result, which contains the status.
"""
params = {
"input": {
"session_id": session_id,
"file_id": file_id
},
"parameters": {
"agent_options": AGENT_OPTIONS
}
}
response = requests.post(upload_callback, json=params, headers=headers)
if response.status_code == HTTPStatus.OK:
result = response.json()
print("Upload callback successful:")
print(json.dumps(result, indent=2, ensure_ascii=False))
return result["output"]["result"]
else:
print(f'Upload callback failed: code={response.status_code}')
print(f'response={response.text}')
raise Exception(f"Upload callback failed: {response.status_code}")
def call_get_file_info(session_id: str, file_ids: list) -> dict:
"""Gets file info.
Args:
session_id: The session ID.
file_ids: A list of file IDs.
Returns:
A list of dictionaries containing file information, including file_name, file_size, content_type, preview_url, and more.
"""
params = {
"input": {
"session_id": session_id,
"file_ids": file_ids
},
"parameters": {
"agent_options": AGENT_OPTIONS
}
}
response = requests.post(get_file_info, json=params, headers=headers)
if response.status_code == HTTPStatus.OK:
result = response.json()
print("Successfully retrieved file info:")
print(json.dumps(result, indent=2, ensure_ascii=False))
return result["output"]["result"]
else:
print(f'Failed to get file info: code={response.status_code}')
print(f'response={response.text}')
raise Exception(f"Failed to get file info: {response.status_code}")
def call_delete_file(session_id: str, file_ids: list) -> dict:
"""Deletes files.
Args:
session_id: The session ID.
file_ids: A list of file IDs to delete.
Returns:
The deletion result, which contains the status.
"""
params = {
"input": {
"session_id": session_id,
"file_ids": file_ids
},
"parameters": {
"agent_options": AGENT_OPTIONS
}
}
response = requests.post(delete_file, json=params, headers=headers)
if response.status_code == HTTPStatus.OK:
result = response.json()
print("File deletion successful:")
print(json.dumps(result, indent=2, ensure_ascii=False))
return result["output"]["result"]
else:
print(f'File deletion failed: code={response.status_code}')
print(f'response={response.text}')
raise Exception(f"File deletion failed: {response.status_code}")
if __name__ == "__main__":
# Example usage
SESSION_ID = "session-456"
# 1. Get File Upload URL
print("=" * 50)
print("1. Get File Upload URL")
print("=" * 50)
upload_result = call_get_upload_url(SESSION_ID, [
{
"file_name": "test_1.jpg",
"file_size": 1024000,
"content_type": "image/jpeg",
"file_ext": "jpg"
}
])
# Get upload_tasks from the result
upload_tasks = upload_result.get("upload_tasks", [])
if upload_tasks:
task = upload_tasks[0]
file_id = task["file_id"]
upload_url = task["upload_url"]
print(f"\nfile_id: {file_id}")
print(f"upload_url: {upload_url}")
# 2. Upload file to OSS (use the PUT method)
print("\n" + "=" * 50)
print("2. Upload File to OSS")
print("=" * 50)
# You must use an actual file for the upload.
# with open("test_1.jpg", "rb") as f:
# response = requests.put(upload_url, data=f)
# if response.status_code == HTTPStatus.OK:
# print("File uploaded successfully")
# 3. Upload callback
print("\n" + "=" * 50)
print("3. Upload callback")
print("=" * 50)
callback_result = call_upload_callback(SESSION_ID, file_id)
# 4. Get file info
print("\n" + "=" * 50)
print("4. Get file info")
print("=" * 50)
file_info = call_get_file_info(SESSION_ID, [file_id])
# 5. Delete file (optional)
print("\n" + "=" * 50)
print("5. Delete file (optional)")
print("=" * 50)
delete_result = call_delete_file(SESSION_ID, [file_id])
import java.io.*;
import java.net.*;
import java.util.*;
import com.alibaba.fastjson2.*;
import java.nio.charset.StandardCharsets;
public class FileApiDemo {
private static final String BASE_URL = "https://dashscope.aliyuncs.com/api/v2/apps/web-search-agent";
private static final String GET_UPLOAD_URL = BASE_URL + "/file/upload/apply";
private static final String UPLOAD_CALLBACK = BASE_URL + "/file/upload/callback";
private static final String GET_FILE_INFO = BASE_URL + "/file/info/get";
private static final String DELETE_FILE = BASE_URL + "/file/delete";
private static final String AGENT_ID = "aid-2ea101badcd5438c8798794d6e47f6f9";
public static void main(String[] args) throws Exception {
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 sessionId = "session-456";
// 1. Get File Upload URL
System.out.println("=" .repeat(50));
System.out.println("1. Get File Upload URL");
System.out.println("=".repeat(50));
JSONObject uploadResult = callGetUploadUrl(apiKey, sessionId);
JSONObject uploadTask = uploadResult.getJSONArray("upload_tasks").getJSONObject(0);
String fileId = uploadTask.getString("file_id");
String uploadUrl = uploadTask.getString("upload_url");
String fileName = uploadTask.getString("file_name");
System.out.println("file_id: " + fileId);
System.out.println("upload_url: " + uploadUrl);
// 2. Upload file to OSS (use the PUT method)
System.out.println("\n" + "=".repeat(50));
System.out.println("2. Upload File to OSS");
System.out.println("=".repeat(50));
// You must use an actual file for the upload.
// uploadFileToOss(uploadUrl, filePath);
System.out.println("File upload example (requires an actual file path)");
// 3. Upload callback
System.out.println("\n" + "=".repeat(50));
System.out.println("3. Upload callback");
System.out.println("=".repeat(50));
JSONObject callbackResult = callUploadCallback(apiKey, sessionId, fileId);
System.out.println("callback status: " + callbackResult.getString("status"));
// 4. Get file info
System.out.println("\n" + "=".repeat(50));
System.out.println("4. Get file info");
System.out.println("=".repeat(50));
JSONArray fileInfoResult = callGetFileInfo(apiKey, sessionId, Arrays.asList(fileId));
System.out.println("file info: " + fileInfoResult.toJSONString());
// 5. Delete file
System.out.println("\n" + "=".repeat(50));
System.out.println("5. Delete file");
System.out.println("=".repeat(50));
JSONObject deleteResult = callDeleteFile(apiKey, sessionId, Arrays.asList(fileId));
System.out.println("delete status: " + deleteResult.getString("status"));
}
/**
* Gets the file upload URL.
*/
public static JSONObject callGetUploadUrl(String apiKey, String sessionId) throws Exception {
Map<String, Object> params = new HashMap<>();
params.put("input", new HashMap<String, Object>() {{
put("session_id", sessionId);
put("files", new JSONArray().fluentAdd(new HashMap<String, Object>() {{
put("file_name", "test_1.jpg");
put("file_size", 1024000);
put("content_type", "image/jpeg");
put("file_ext", "jpg");
}}));
}});
params.put("parameters", new HashMap<String, Object>() {{
put("agent_options", buildAgentOptions());
}});
return doPost(apiKey, GET_UPLOAD_URL, params).getJSONObject("output").getJSONObject("result");
}
/**
* Performs the upload callback.
*/
public static JSONObject callUploadCallback(String apiKey, String sessionId, String fileId) throws Exception {
Map<String, Object> params = new HashMap<>();
params.put("input", new HashMap<String, Object>() {{
put("session_id", sessionId);
put("file_id", fileId);
}});
params.put("parameters", new HashMap<String, Object>() {{
put("agent_options", buildAgentOptions());
}});
return doPost(apiKey, UPLOAD_CALLBACK, params).getJSONObject("output").getJSONObject("result");
}
/**
* Gets file info.
*/
public static JSONArray callGetFileInfo(String apiKey, String sessionId, List<String> fileIds) throws Exception {
Map<String, Object> params = new HashMap<>();
params.put("input", new HashMap<String, Object>() {{
put("session_id", sessionId);
put("file_ids", new JSONArray(fileIds));
}});
params.put("parameters", new HashMap<String, Object>() {{
put("agent_options", buildAgentOptions());
}});
return doPost(apiKey, GET_FILE_INFO, params).getJSONObject("output").getJSONArray("result");
}
/**
* Deletes files.
*/
public static JSONObject callDeleteFile(String apiKey, String sessionId, List<String> fileIds) throws Exception {
Map<String, Object> params = new HashMap<>();
params.put("input", new HashMap<String, Object>() {{
put("session_id", sessionId);
put("file_ids", new JSONArray(fileIds));
}});
params.put("parameters", new HashMap<String, Object>() {{
put("agent_options", buildAgentOptions());
}});
return doPost(apiKey, DELETE_FILE, params).getJSONObject("output").getJSONObject("result");
}
/**
* Builds the agent options.
*/
private static Map<String, Object> buildAgentOptions() {
return new HashMap<String, Object>() {{
put("agent_id", AGENT_ID);
}};
}
/**
* Sends a POST request.
*/
private static JSONObject doPost(String apiKey, String urlStr, Map<String, Object> params) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Authorization", "Bearer " + apiKey);
conn.setRequestProperty("Content-Type", "application/json");
try (OutputStream os = conn.getOutputStream()) {
os.write(JSON.toJSONString(params).getBytes(StandardCharsets.UTF_8));
}
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
String responseBody;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.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);
System.out.println(respJson.toJSONString());
return respJson;
} else {
System.out.println("code=" + conn.getResponseCode());
try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getErrorStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
throw new Exception("Request failed: " + conn.getResponseCode());
}
}
/**
* Uploads a file to OSS using the PUT method.
*/
private static void uploadFileToOss(String uploadUrl, String filePath) throws Exception {
URL url = new URL(uploadUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("PUT");
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream();
InputStream fis = new FileInputStream(filePath)) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
}
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
System.out.println("File uploaded successfully");
} else {
System.out.println("File upload failed: " + conn.getResponseCode());
}
}
}