Asynchronous invocation API
This topic describes how to make an asynchronous call to Alibaba Cloud Model Studio applications ( Agent and Workflow ) using the OpenAI-compatible Responses API. For long-running tasks, set the background parameter to true in your request. The API then immediately returns a task ID for querying and managing the task. This "submit first, query later" pattern helps avoid request timeouts and long waits.
References- Synchronous invocation: For immediate responses to real-time interactions, see the Synchronous Invocation API Reference.
- DashScope API: For additional capabilities, see DashScope API.
ImportantThis topic is applicable only to the China (Beijing) region.
NoteAsynchronous tasks do not support streaming output (stream=true).
Prerequisites
- You have obtained an API Key and set it as an environment variable. To make calls through the OpenAI SDK, you must also install the SDK.
- You have created an Alibaba Cloud Model Studio application and obtained its application ID. You can copy the ID from the application card on the Application Management page.
Quick start
This section provides complete Python and Java examples to demonstrate how to start an asynchronous task, poll for its status until it is complete, and retrieve the final result.
This example covers the core workflow for asynchronous invocation:
- Create a task: Call the
createmethod and setbackground=Trueto get the task ID. - Poll for status: Periodically call the
retrievemethod to query the task status. - Process the result: When the task status is
completed,failed, orcancelled, exit the loop and process the final result.
Workflow
The following sections describe the API operations for creating, querying, canceling, and deleting asynchronous tasks.
Create a task
Set the background parameter to true to enable asynchronous mode. This creates an asynchronous task and immediately returns a task ID.
Endpoint:POST https://dashscope.aliyuncs.com/api/v2/apps/agent/{APP_ID}/compatible-mode/v1/responses
Replace
{APP_ID}with your application ID.
Request example
Single-turn conversation
from openai import AsyncOpenAI
import asyncio
import os
# If the environment variable is not configured, replace the following line with your Model Studio API key: api_key="sk-xxx".
# However, to avoid security risks, we recommend not hard-coding the API key in production code.
api_key=os.getenv("DASHSCOPE_API_KEY")
app_id='APP_ID' # Replace with your actual application ID
base_url = f'https://dashscope.aliyuncs.com/api/v2/apps/agent/{app_id}/compatible-mode/v1/'
# Initialize the asynchronous client
client = AsyncOpenAI(
api_key=api_key,
base_url=base_url
)
async def main():
# Asynchronous call
response = await client.responses.create(
input="Who are you?",
background=True
)
# Print the complete response JSON object
print(response.model_dump_json(indent=2))
# Run the asynchronous main function
if __name__ == "__main__":
asyncio.run(main())
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class CreateTask {
public static void main(String[] args) throws Exception {
// If the environment variable is not configured, replace the following line with your Model Studio API key: apiKey="sk-xxx".
// However, to avoid security risks, we recommend not hard-coding the API key in production code.
String apiKey = System.getenv("DASHSCOPE_API_KEY");
String appId = "APP_ID"; // Replace with your actual application ID
String baseUrl = "https://dashscope.aliyuncs.com/api/v2/apps/agent/" + appId + "/compatible-mode/v1/";
OpenAIClient client = OpenAIOkHttpClient.builder()
.apiKey(apiKey)
.baseUrl(baseUrl)
.build();
// Asynchronous call
Response response = client.responses().create(
ResponseCreateParams.builder()
.input("Who are you?")
.background(true)
.build()
);
// Print the complete response JSON object
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
System.out.println(mapper.writeValueAsString(response));
}
}
# If the environment variable is not set, replace {DASHSCOPE_API_KEY} with your actual Model Studio API key.
# However, to avoid security risks, we recommend not hard-coding the API key in production code.
# Please replace APP_ID with your actual application ID.
# Remove comments before execution.
curl --location "https://dashscope.aliyuncs.com/api/v2/apps/agent/{APP_ID}/compatible-mode/v1/responses" \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer ${DASHSCOPE_API_KEY}" \
--data '{
"input": "Who are you?",
"background": true
}'
Parameter passing
Agent ApplicationconfigurationPlugin parameter passing: In your application, select a plugin and then click Publish.
Custom parameter passing
![]() | Plugin parameter passing
![]() |
API call
-
Custom parameters: Pass parameters using
biz_params. The parameter names and types must match those configured in the application.from openai import AsyncOpenAI import asyncio import os # If the environment variable is not configured, replace the following line with your Model Studio API key: api_key="sk-xxx". # However, to avoid security risks, we recommend not hard-coding the API key in production code. api_key=os.getenv("DASHSCOPE_API_KEY") app_id='APP_ID' # Replace with your actual application ID base_url = f'https://dashscope.aliyuncs.com/api/v2/apps/agent/{app_id}/compatible-mode/v1/' # Initialize the asynchronous client client = AsyncOpenAI( api_key=api_key, base_url=base_url ) async def main(): # Asynchronous call response = await client.responses.create( input="Hello", extra_body={ "biz_params": {"city": "Beijing"} }, background=True ) # Print the complete response JSON object print(response.model_dump_json(indent=2)) # Run the asynchronous main function if __name__ == "__main__": asyncio.run(main())import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.responses.*; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import java.util.HashMap; import java.util.Map; public class CreateTaskWithCustomParams { public static void main(String[] args) throws Exception { // If the environment variable is not configured, replace the following line with your Model Studio API key: apiKey="sk-xxx". // However, to avoid security risks, we recommend not hard-coding the API key in production code. String apiKey = System.getenv("DASHSCOPE_API_KEY"); String appId = "APP_ID"; // Replace with your actual application ID String baseUrl = "https://dashscope.aliyuncs.com/api/v2/apps/agent/" + appId + "/compatible-mode/v1/"; OpenAIClient client = OpenAIOkHttpClient.builder() .apiKey(apiKey) .baseUrl(baseUrl) .build(); // Asynchronous call, passing custom parameters via putAdditionalBodyProperty Map<String, Object> bizParams = new HashMap<>(); bizParams.put("city", "Beijing"); Response response = client.responses().create( ResponseCreateParams.builder() .input("Hello") .background(true) .putAdditionalBodyProperty("biz_params", com.openai.core.JsonValue.from(bizParams)) .build() ); // Print the complete response JSON object ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); System.out.println(mapper.writeValueAsString(response)); } }#!/bin/bash # ==================== Configuration ==================== # If the DASHSCOPE_API_KEY environment variable is not set, replace ${DASHSCOPE_API_KEY} # with your actual Model Studio API key. # To avoid security risks, we recommend not hard-coding the API key in production code. # Replace {APP_ID} with your actual application ID. # ==================== API Call ==================== curl --location "https://dashscope.aliyuncs.com/api/v2/apps/agent/{APP_ID}/compatible-mode/v1/responses" \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${DASHSCOPE_API_KEY}" \ --data '{ "input": "Who are you?", "background": true, "biz_params": { "city": "Hangzhou" } }' -
Plugin parameters: Pass parameters via
biz_params. Useuser_defined_paramsto pass plugin parameters anduser_defined_tokensto pass authentication tokens. The parameter names and types must match the plugin's configuration.""" Example of calling an Alibaba Cloud Model Studio application asynchronously. """ from openai import AsyncOpenAI import asyncio import os # ==================== Configuration ==================== # API key configuration # If the environment variable is not configured, you can replace the following line with: api_key="sk-xxx" # To avoid security risks, we recommend not hard-coding the API key in production code. api_key = os.getenv("DASHSCOPE_API_KEY") # Application ID (Get this from Model Studio console -> Applications -> Publish channels -> API) app_id = 'YOUR_APP_ID' # Replace with your actual application ID # Base URL base_url = f'https://dashscope.aliyuncs.com/api/v2/apps/agent/{app_id}/compatible-mode/v1/' # ==================== Client Initialization ==================== client = AsyncOpenAI( api_key=api_key, base_url=base_url ) # ==================== Business Parameter Configuration (Optional) ==================== # biz_params is used to pass custom parameters to plugins in the application. # Replace YOUR_PLUGIN_ID with the actual plugin ID from the plugin details page in the Model Studio console. biz_params = { # Custom parameters: Parameters passed to a specified plugin. "user_defined_params": { "YOUR_PLUGIN_ID": { # Replace with the actual plugin ID "article_index": 9 # Custom parameter, set according to the plugin's requirements. } }, # Custom tokens: Provide authentication information for the specified plugin. Replace YOUR_TOKEN with a valid authentication token. "user_defined_tokens": { "YOUR_PLUGIN_ID": { # Replace with the actual plugin ID "user_token": "YOUR_TOKEN" # The authentication token required by the plugin. } } } # ==================== Main Function ==================== async def main(): """Call the agent application asynchronously.""" # Make the asynchronous request # - input: The user's question or instruction. # - extra_body: Additional parameters, including biz_params. # - background: true indicates asynchronous execution. response = await client.responses.create( input="Hello", extra_body={ "biz_params": biz_params }, background=True ) # Print the complete response JSON object print(response.model_dump_json(indent=2)) # ==================== Program Entry Point ==================== if __name__ == "__main__": asyncio.run(main())import com.openai.client.OpenAIClient; import com.openai.client.okhttp.OpenAIOkHttpClient; import com.openai.models.responses.*; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import java.util.HashMap; import java.util.Map; public class CreateTaskWithPluginParams { public static void main(String[] args) throws Exception { // If the environment variable is not configured, replace the following line with your Model Studio API key: apiKey="sk-xxx". // However, to avoid security risks, we recommend not hard-coding the API key in production code. String apiKey = System.getenv("DASHSCOPE_API_KEY"); String appId = "YOUR_APP_ID"; // Replace with your actual application ID String baseUrl = "https://dashscope.aliyuncs.com/api/v2/apps/agent/" + appId + "/compatible-mode/v1/"; OpenAIClient client = OpenAIOkHttpClient.builder() .apiKey(apiKey) .baseUrl(baseUrl) .build(); // Build biz_params, including user_defined_params and user_defined_tokens. // Custom parameters: Parameters passed to a specified plugin. Map<String, Object> pluginParams = new HashMap<>(); pluginParams.put("article_index", 9); // Custom parameter, set according to the plugin's requirements. Map<String, Object> userDefinedParams = new HashMap<>(); userDefinedParams.put("YOUR_PLUGIN_ID", pluginParams); // Replace with the actual plugin ID. // Custom tokens: Provide authentication information for the specified plugin. Map<String, Object> pluginTokens = new HashMap<>(); pluginTokens.put("user_token", "YOUR_TOKEN"); // The authentication token required by the plugin. Map<String, Object> userDefinedTokens = new HashMap<>(); userDefinedTokens.put("YOUR_PLUGIN_ID", pluginTokens); // Replace with the actual plugin ID. Map<String, Object> bizParams = new HashMap<>(); bizParams.put("user_defined_params", userDefinedParams); bizParams.put("user_defined_tokens", userDefinedTokens); // Asynchronous call, passing plugin parameters via putAdditionalBodyProperty Response response = client.responses().create( ResponseCreateParams.builder() .input("Hello") .background(true) .putAdditionalBodyProperty("biz_params", com.openai.core.JsonValue.from(bizParams)) .build() ); // Print the complete response JSON object ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); System.out.println(mapper.writeValueAsString(response)); } }#!/bin/bash # ==================== Configuration ==================== # If the DASHSCOPE_API_KEY environment variable is not set, replace ${DASHSCOPE_API_KEY} # with your actual Model Studio API key. # To avoid security risks, we recommend not hard-coding the API key in production code. APP_ID="YOUR_APP_ID" # Replace with your actual application ID # ==================== API Call ==================== curl --location "https://dashscope.aliyuncs.com/api/v2/apps/agent/${APP_ID}/compatible-mode/v1/responses" \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${DASHSCOPE_API_KEY}" \ --data '{ "input": "Who are you?", "background": true, "biz_params": { "user_defined_params": { "YOUR_PLUGIN_ID": { "article_index": 9 } }, "user_defined_tokens": { "YOUR_PLUGIN_ID": { "user_token": "YOUR_TOKEN" } } } }' # ==================== Parameter Reference ==================== # The biz_params object passes custom parameters to plugins in the Agent. # # user_defined_params - Custom parameters # YOUR_PLUGIN_ID: Replace with the actual plugin ID. # article_index: Custom parameter name and value, set according to the plugin's requirements. # # user_defined_tokens - Custom tokens (for authentication) # YOUR_PLUGIN_ID: Replace with the actual plugin ID. # user_token: The authentication token required by the plugin.
Request fields
Parameter | Type | Required | Description |
|---|---|---|---|
| string/array | Yes | The core input for the request, which can be a single string or an array of messages representing a multi-turn conversation history. |
| boolean | Yes | Specifies whether to execute the task asynchronously.
|
extra_body | object | No | A field for additional parameters. |
extra_body.biz_params | object | No | Used to pass parameters defined in the application, such as custom variables, node inputs, or plugin arguments. |
user_defined_params | object | No | Custom plugin parameter information. An application supports up to 10 unique plugins. |
user_defined_tokens | object | No | User-level authentication information for a custom plugin. An application supports up to 10 unique plugins. |
user_defined_tokens.user_token | string | No | The user authentication information required by the plugin. |
Response example
{
"id": "bcb9728b-a7f8-480c-ace0-8d61ff776857",
"created_at": 1761875532,
"error": null,
"incomplete_details": null,
"instructions": null,
"metadata": null,
"model": "",
"object": "response",
"output": [],
"parallel_tool_calls": false,
"temperature": null,
"tool_choice": "auto",
"tools": [],
"top_p": null,
"background": null,
"conversation": null,
"max_output_tokens": null,
"max_tool_calls": null,
"previous_response_id": null,
"prompt": null,
"prompt_cache_key": null,
"reasoning": null,
"safety_identifier": null,
"service_tier": null,
"status": "queued",
"text": null,
"top_logprobs": null,
"truncation": null,
"usage": null,
"user": null
}
Response fields
Parameter | Type | Description |
|---|---|---|
| string | A unique identifier for the asynchronous task. Use it to retrieve, cancel, or delete the task. |
| string | The initial status of the task, which is typically |
| integer | The task's creation time, represented as a Unix timestamp in seconds. |
| string | The object type. This value is always |
Retrieve task
Retrieves the status and result of a specified asynchronous task.
Endpoint:GET https://dashscope.aliyuncs.com/api/v2/apps/agent/{APP_ID}/compatible-mode/v1/responses/{RESPONSE_ID}
Replace
{APP_ID}with your App ID and{RESPONSE_ID}with the Response ID from the task creation response.
Request example
import asyncio
import os
from openai import AsyncOpenAI
# If the environment variable is not set, you can provide your DashScope API Key directly: api_key="sk-xxx".
# For security, avoid hard-coding the key in production environments.
api_key=os.getenv("DASHSCOPE_API_KEY")
app_id='APP_ID' # 1. Replace with your App ID
base_url = f'https://dashscope.aliyuncs.com/api/v2/apps/agent/{app_id}/compatible-mode/v1/'
# Initialize the client
client = AsyncOpenAI(api_key=api_key, base_url=base_url)
async def main():
# Query task status
response = await client.responses.retrieve("6e4ba287-0e93-4d67-9955-ef1017ed3384") # 2. Replace with your Response ID
print(response.model_dump_json(indent=2))
if __name__ == "__main__":
asyncio.run(main())
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class RetrieveTask {
public static void main(String[] args) throws Exception {
// If the environment variable is not set, you can provide your DashScope API Key directly: apiKey="sk-xxx".
// For security, avoid hard-coding the key in production environments.
String apiKey = System.getenv("DASHSCOPE_API_KEY");
String appId = "APP_ID"; // 1. Replace with your App ID
String baseUrl = "https://dashscope.aliyuncs.com/api/v2/apps/agent/" + appId + "/compatible-mode/v1/";
OpenAIClient client = OpenAIOkHttpClient.builder()
.apiKey(apiKey)
.baseUrl(baseUrl)
.build();
// Query task status
String responseId = "6e4ba287-0e93-4d67-9955-ef1017ed3384"; // 2. Replace with your Response ID
Response response = client.responses().retrieve(responseId);
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
System.out.println(mapper.writeValueAsString(response));
}
}
# If the environment variable is not set, replace ${DASHSCOPE_API_KEY} with your DashScope API Key.
# For security, avoid hard-coding the API key in production.
# 1. Replace {APP_ID} with your App ID.
# 2. Replace {RESPONSE_ID} with the ID from the asynchronous task creation response.
# Remove these comments before execution.
curl "https://dashscope.aliyuncs.com/api/v2/apps/agent/{APP_ID}/compatible-mode/v1/responses/{RESPONSE_ID}" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${DASHSCOPE_API_KEY}"
Response example
{
"id": "bcb9728b-a7f8-480c-ace0-8d61ff776857",
"created_at": 1761875537,
"error": null,
"incomplete_details": null,
"instructions": null,
"metadata": null,
"model": "",
"object": "response",
"output": [
{
"id": "msg_d89e8cb9-f8fa-4092-bb86-928e21839f64",
"content": [
{
"annotations": [],
"text": "Hello, I am Qwen, a large-scale language model independently developed by the Qwen Lab at Alibaba Group. I can answer questions, create text such as stories, official documents, emails, and scripts, and also perform logical reasoning, programming, and even express opinions and play games. My goal is to be your trustworthy intelligent assistant. Is there anything I can help you with?",
"type": "output_text",
"logprobs": null
}
],
"role": "assistant",
"status": "completed",
"type": "message"
}
],
"parallel_tool_calls": false,
"temperature": null,
"tool_choice": "auto",
"tools": [],
"top_p": null,
"background": null,
"conversation": null,
"max_output_tokens": null,
"max_tool_calls": null,
"previous_response_id": null,
"prompt": null,
"prompt_cache_key": null,
"reasoning": null,
"safety_identifier": null,
"service_tier": null,
"status": "completed",
"text": null,
"top_logprobs": null,
"truncation": null,
"usage": null,
"user": null
}
Response fields
Parameter | Type | Description |
|---|---|---|
| string | The unique identifier for the asynchronous task. |
| string | The current status of the asynchronous task. For details, see Task Lifecycle. |
| array | The output of the task. When |
Cancel a task
Cancels an asynchronous task in the queued or running state.
Endpoint:POST https://dashscope.aliyuncs.com/api/v2/apps/agent/{APP_ID}/compatible-mode/v1/responses/{RESPONSE_ID}/cancel
Replace
{APP_ID}with your application ID and{RESPONSE_ID}with the task ID returned on task creation.
Request example
import asyncio
import os
from openai import AsyncOpenAI
# If the environment variable is not set, replace the following line with your DashScope API key: api_key="sk-xxx".
# However, we do not recommend hardcoding the API key in a production environment to reduce security risks.
api_key=os.getenv("DASHSCOPE_API_KEY")
app_id='APP_ID' # 1. Replace with your application ID
base_url = f'https://dashscope.aliyuncs.com/api/v2/apps/agent/{app_id}/compatible-mode/v1/'
# Initialize the client
client = AsyncOpenAI(api_key=api_key, base_url=base_url)
async def main():
# Cancel the task
response = await client.responses.cancel("6e4ba287-0e93-4d67-9955-ef1017ed3384") # 2. Replace with the task ID
print(response.model_dump_json(indent=2))
if __name__ == "__main__":
asyncio.run(main())
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class CancelTask {
public static void main(String[] args) throws Exception {
// If the environment variable is not set, replace the following line with your DashScope API key: apiKey="sk-xxx".
// However, we do not recommend hardcoding the API key in a production environment to reduce security risks.
String apiKey = System.getenv("DASHSCOPE_API_KEY");
String appId = "APP_ID"; // 1. Replace with your application ID
String baseUrl = "https://dashscope.aliyuncs.com/api/v2/apps/agent/" + appId + "/compatible-mode/v1/";
OpenAIClient client = OpenAIOkHttpClient.builder()
.apiKey(apiKey)
.baseUrl(baseUrl)
.build();
// Cancel the task
String responseId = "6e4ba287-0e93-4d67-9955-ef1017ed3384"; // 2. Replace with the task ID
Response response = client.responses().cancel(responseId);
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
System.out.println(mapper.writeValueAsString(response));
}
}
# If you are not using an environment variable, replace ${DASHSCOPE_API_KEY} with your DashScope API key.
# It is not recommended to expose the raw API key in a production environment to reduce security risks.
# 1. Replace {APP_ID} with your application ID.
# 2. Replace {RESPONSE_ID} with the task ID returned when creating the task.
# Remove these comments before execution.
curl -X POST "https://dashscope.aliyuncs.com/api/v2/apps/agent/{APP_ID}/compatible-mode/v1/responses/{RESPONSE_ID}/cancel" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${DASHSCOPE_API_KEY}"
Response example
{
"created_at": 1761877521,
"id": "568b1459-126d-4719-b58f-b41078bacb48",
"model": "",
"object": "response",
"output": [
],
"parallel_tool_calls": false,
"status": "cancelled",
"tool_choice": "auto",
"tools": [
]
}
Response fields
Field | Type | Description |
|---|---|---|
| string | Unique identifier of the task. |
| string | The status of the task after cancellation. For example:
|
| string | The object type, always |
Delete a response
Deletes a response that is in a final state (completed, failed, or cancelled). This operation is irreversible.
Endpoint:DELETE https://dashscope.aliyuncs.com/api/v2/apps/agent/{APP_ID}/compatible-mode/v1/responses/{RESPONSE_ID}
Replace
{APP_ID}with your application ID and{RESPONSE_ID}with the response ID returned when the asynchronous task was created.
Request example
import asyncio
import os
from openai import AsyncOpenAI
# If the environment variable is not configured, you can replace the following line with your Model Studio API key: api_key="sk-xxx".
# We do not recommend hard-coding the API key in your code in a production environment to reduce the risk of API key exposure.
api_key = os.getenv("DASHSCOPE_API_KEY")
app_id = 'APP_ID' # 1. Replace with your application ID
base_url = f'https://dashscope.aliyuncs.com/api/v2/apps/agent/{app_id}/compatible-mode/v1/'
client = AsyncOpenAI(api_key=api_key, base_url=base_url)
async def main():
# 2. Replace with the response ID to delete
response_id_to_delete = "b17c64f94-7034-403e-aef5-4f48647656d5"
try:
response_wrapper = await client.responses.with_raw_response.delete(response_id_to_delete)
http_response = response_wrapper.http_response
response_json = http_response.json()
# Check if the "deleted" field in the response is true.
if response_json.get("deleted") is True:
print("The response was successfully deleted.")
print(response_json)
else:
print("The deletion failed.")
print(response_json)
except Exception as e:
print(f"\nAn error occurred while calling the API: {e}")
if __name__ == "__main__":
asyncio.run(main())
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.*;
public class DeleteTask {
public static void main(String[] args) throws Exception {
// If the environment variable is not configured, you can replace the following line with your Model Studio API key: apiKey="sk-xxx".
// We do not recommend hard-coding the API key in your code in a production environment to reduce the risk of API key exposure.
String apiKey = System.getenv("DASHSCOPE_API_KEY");
String appId = "APP_ID"; // 1. Replace with your application ID
String baseUrl = "https://dashscope.aliyuncs.com/api/v2/apps/agent/" + appId + "/compatible-mode/v1/";
OpenAIClient client = OpenAIOkHttpClient.builder()
.apiKey(apiKey)
.baseUrl(baseUrl)
.build();
// 2. Replace with the response ID to delete
String responseId = "b17c64f94-7034-403e-aef5-4f48647656d5";
client.responses().delete(responseId);
System.out.println("The response was successfully deleted. ID: " + responseId);
}
}
# If the environment variable is not set, replace ${DASHSCOPE_API_KEY} with your Model Studio API key.
# We do not recommend hard-coding the API key in your code in a production environment to reduce the risk of API key exposure.
# 1. Replace {APP_ID} with your application ID.
# 2. Replace {RESPONSE_ID} with the response ID returned when you created the asynchronous task.
curl -X DELETE "https://dashscope.aliyuncs.com/api/v2/apps/agent/{APP_ID}/compatible-mode/v1/responses/{RESPONSE_ID}" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${DASHSCOPE_API_KEY}"
Response example
{
"deleted": true,
"id": "c8eddc0e-faf5-4228-a853-9c411194015f",
"object": "response"
}
Response fields
Field | Type | Description |
|---|---|---|
| string | The unique identifier of the deleted response. |
| boolean | Set to |
| string | The object type. This value is always |
Task lifecycle
An asynchronous task has the following states:
State | Description |
|---|---|
| The task is created and awaits scheduling in the queue. |
| The task is running. |
| The task completed successfully. The |
| The user cancelled the task before it completed. |
| The task failed to execute. The |
Error codes
If an application call fails, see Error codes to resolve the error.

