Asynchronous invocation API

Updated at:

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

ImportantThis topic is applicable only to the China (Beijing) region.

NoteAsynchronous tasks do not support streaming output (stream=true).

Prerequisites

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:

  1. Create a task: Call the create method and set background=True to get the task ID.
  2. Poll for status: Periodically call the retrieve method to query the task status.
  3. Process the result: When the task status is completed, failed, or cancelled, exit the loop and process the final result.

Code example

import asyncio
import os
from openai import AsyncOpenAI
import time

# 1. Initialize the client
# If the environment variable is not set, you can replace the following line with your Model Studio API key: api_key="sk-xxx".
# To prevent API key exposure, avoid hardcoding the 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/'
client = AsyncOpenAI(api_key=api_key, base_url=base_url)

async def main():
    start_time = time.time()

    # 2. Start an asynchronous task
    print("Step 1: Creating an asynchronous task...")

    create_response = await client.responses.create(
        input="Please plan a three-day trip to Beijing for me, including the Forbidden City and the Great Wall.",
        background=True
    )
    task_id = create_response.id
    print(f"  - Task created successfully! Task ID: {task_id}")
    print(f"  - Initial status: {create_response.status}")

    # 3. Poll for the task status until the task is complete
    print("\nStep 2: Polling for task status (every 2 seconds)...")
    while True:
        retrieve_response = await client.responses.retrieve(task_id)
        status = retrieve_response.status

        print(f"  - Current status: {status}")

        # Check if the task has reached a terminal state
        if status in ['completed', 'failed', 'cancelled']:
            print("\nStep 3: The task is complete or has been terminated.")
            final_response = retrieve_response
            break

        # Wait for 2 seconds before the next poll
        await asyncio.sleep(2)

    # 4. Process and print the final result
    if final_response.status == 'completed':
        print("  - Status: Success")
        # Extract and print the text result
        if final_response.output and final_response.output[0].content:
            result_text = final_response.output[0].content[0].text
            print("\n--- Task Output ---")
            print(result_text)
            print("-----------------")
        else:
            print("The task is complete, but no valid output was returned.")

    else: # 'failed' or 'cancelled'
        print(f"  - Status: {final_response.status.upper()}")
        print("\n--- Final Response Details ---")
        # Print the complete JSON for debugging
        print(final_response.model_dump_json(indent=2))
        print("-----------------------")

    end_time = time.time()
    print(f"\nTotal time elapsed: {end_time - start_time:.2f} seconds")

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 QuickStart {
    public static void main(String[] args) throws Exception {
        // If the environment variable is not set, you can replace the following line with your Model Studio API key: apiKey="sk-xxx".
        // To prevent API key exposure, avoid hardcoding the 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();

        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);

        long startTime = System.currentTimeMillis();

        // 1. Create an asynchronous task
        System.out.println("Step 1: Creating an asynchronous task...");
        Response createResponse = client.responses().create(
                ResponseCreateParams.builder()
                        .input("Please plan a three-day trip to Beijing for me, including the Forbidden City and the Great Wall.")
                        .background(true)
                        .build()
        );
        String taskId = createResponse.id();
        System.out.println("  - Task created successfully! Task ID: " + taskId);
        System.out.println("  - Initial status: " + createResponse.status().orElse(null));

        // 2. Poll for the task status until the task is complete
        System.out.println("\nStep 2: Polling for task status (every 2 seconds)...");
        Response finalResponse = null;
        while (true) {
            Response retrieveResponse = client.responses().retrieve(taskId);
            ResponseStatus status = retrieveResponse.status().orElse(null);
            System.out.println("  - Current status: " + status);

            // Check if the task has reached a terminal state
            if (ResponseStatus.COMPLETED.equals(status)
                    || ResponseStatus.FAILED.equals(status)
                    || ResponseStatus.CANCELLED.equals(status)) {
                System.out.println("\nStep 3: The task is complete or has been terminated.");
                finalResponse = retrieveResponse;
                break;
            }
            // Wait for 2 seconds before the next poll
            Thread.sleep(2000);
        }

        // 3. Process and print the final result
        ResponseStatus finalStatus = finalResponse.status().orElse(null);
        if (ResponseStatus.COMPLETED.equals(finalStatus)) {
            System.out.println("  - Status: Success");
            if (!finalResponse.output().isEmpty()) {
                System.out.println("\n--- Task Output ---");
                System.out.println(mapper.writeValueAsString(finalResponse.output()));
                System.out.println("-----------------");
            }
        } else {
            System.out.println("  - Status: " + finalStatus);
            System.out.println("\n--- Final Response Details ---");
            System.out.println(mapper.writeValueAsString(finalResponse));
            System.out.println("-----------------------");
        }

        long endTime = System.currentTimeMillis();
        System.out.println("\nTotal time elapsed: " + (endTime - startTime) / 1000.0 + " seconds");
    }
}

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 Applicationconfiguration

Plugin parameter passing: In your application, select a plugin and then click Publish.image

Workflow Applicationconfiguration
Custom parameter passing

This example shows how to query for city cuisine.

  1. In the application, create custom parameters in the Start node.
  2. Reference the custom parameters in the Prompts of the LLM Node.
  3. After testing, Publish the application.
image
Plugin parameter passing

This example uses a tool to query dorm rules.

  1. To pass plugin parameters, add a Plug-in Node and select the desired plugin.
  2. In the application, create custom parameters in the Start node and pass them to the input parameters of the plugin node.
  3. Reference the custom parameters and plugin output parameters in the Prompts of the LLM Node.
  4. After testing, Publish the application.
image

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. Use user_defined_params to pass plugin parameters and user_defined_tokens to 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

input

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.

background

boolean

Yes

Specifies whether to execute the task asynchronously.

  • false (default): Uses synchronous mode. The API keeps the connection open until the task is complete.

  • true: Enables asynchronous mode. The API immediately returns a task ID, which can be used to check the task status and retrieve the result.

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

id

string

A unique identifier for the asynchronous task. Use it to retrieve, cancel, or delete the task.

status

string

The initial status of the task, which is typically queued.

created_at

integer

The task's creation time, represented as a Unix timestamp in seconds.

object

string

The object type. This value is always response.

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

id

string

The unique identifier for the asynchronous task.

status

string

The current status of the asynchronous task. For details, see Task Lifecycle.

output

array

The output of the task. When status is completed , this field contains the final result.

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

id

string

Unique identifier of the task.

status

string

The status of the task after cancellation. For example:

cancelled: The task was successfully canceled.

failed: The cancellation failed because the task was already in a final state, such as completed or failed.

object

string

The object type, always response.

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

id

string

The unique identifier of the deleted response.

deleted

boolean

Set to true if the response was deleted successfully.

object

string

The object type. This value is always response.

Task lifecycle

An asynchronous task has the following states:

State

Description

queued

The task is created and awaits scheduling in the queue.

running

The task is running.

completed

The task completed successfully. The output field of the response contains the result.

cancelled

The user cancelled the task before it completed.

failed

The task failed to execute. The output field of the response contains the error message.

Error codes

If an application call fails, see Error codes to resolve the error.