Skip to main content

Application DashScope API Reference

This document describes the input and output parameters for calling Alibaba Cloud Model Studio applications (agents and workflows) with the DashScope API, and provides call examples for typical scenarios.

This document applies only to the Singapore region.
Related guides See Application Calling.

Prerequisites

Before you begin, make sure you have completed the following:
  1. Create an application:Go to My Applications to create an Alibaba Cloud Model Studio application and obtain the application ID;
  2. Obtain an API Key:Obtain it from API Key management, and configure the API Key as an environment variable.
  3. Install the SDK (optional):If you call the API with an SDK, install the DashScope SDK for your programming language.

Call Method

  • HTTP API calls Request URL: POST https://dashscope-intl.aliyuncs.com/api/v1/apps/APP_ID/completion
    Replace APP_ID with your actual application ID
  • SDK calls Python/Java SDK: The correct endpoint is configured by default in this document Custom endpoint: You can configure it with the base_url parameter

Request body

app_idstring(required)The application identifier.You can obtain the application ID from the application card on the My Applications page.
It is appId in the Java SDK. When calling via HTTP, put the actual application ID into the URL and replace APP_ID.
promptstring(required)The user's input instruction, used to guide the application to generate a reply.
When calling via HTTP, put prompt in the input object.
session_idstring (optional)The identifier of the conversation history.When session_id is passed, the request automatically carries the conversation history stored in the cloud. In this case, you must pass prompt.The ID automatically expires after 1 consecutive hour without any requests.
It is setSessionId in the Java SDK. When calling via HTTP, put session_id in the input object.
messagesarray(optional)The context passed to the model, arranged in conversation order.When using the messages parameter for multi-turn conversations, you do not need to pass prompt or session_id.If both session_id and messages are passed, the model prioritizes the content in messages and ignores session_id and prompt.
When calling via HTTP, put messages into the input object.
To use this parameter, the Python DashScope SDK version must be at least 2.0.1, and the Java DashScope SDK version must be at least 2.17.0.

Message type

System Messageobject (optional)System message, used to define the model's role, tone, task objectives, or constraints. Typically placed first in the messages array.
contentstring(required)System instruction, used to specify the model's role, behavioral rules, response style, and task constraints.rolestring(required)The role of the system message, fixed to system.
User Messageobject(required)User message, used to pass questions, instructions, or context to the model.
contentstring(required)Message content.
textstring(required)The input text.
rolestring(required)The role of the user message, fixed to user.
Assistant Messageobject (optional)The model's reply. Typically passed back to the model as context in multi-turn conversations.
contentstring(required)The text content of the model's reply.rolestring(required)The role of the assistant message, fixed to assistant.
workspace string (optional)Business space identifier. Related documentation: Obtain Workspace ID.Pass workspace ID only when calling an application in a sub-business space.
When calling via HTTP, specify X-DashScope-WorkSpace in the header.
stream boolean (optional) Default value is FalseWhether to respond in streaming output mode.It is recommended to set it to True, which improves the reading experience and reduces the risk of timeout.Parameter Value:
  • False (default): The model returns all the generated content all at once after generation is complete.
  • True (recommended): Outputs while generating, returning a data chunk each time part of the content is generated. You need to read these chunks in real time one by one to assemble the complete response.
To implement streaming output with the Java SDK, call the streamCall interface; to implement streaming output via HTTP, specify X-DashScope-SSE as enable in the Header.
incremental_output boolean (optional) Default value: FalseWhether to enable incremental output in streaming output mode.It is recommended to set it to True, which improves the reading experience.Parameter Value:
  • False (default): Outputs the entire sequence generated so far each time, and the last output is the complete generated result.
I
I like
I like apple
I like apple.
  • True (recommended): Incremental output, meaning subsequent output does not include content that has already been output. You need to read these fragments in real time one by one to obtain the complete result.
I
like
apple
.
In the Java SDK, it is incrementalOutput. When calling via HTTP, put incremental_output in the parameters object.
flow_stream_mode string (optional) Default value: full_thoughtsThe streaming output mode of workflow applications.Parameter Value:
  • message_format (recommended): Outputs the result of the specified node (the Output node or the End node) in the message field.
    In the console application, turn on the Streaming output switch of the target node to return results in a streaming manner; when it is not enabled, the final result of the node is returned all at once.
    In the Java SDK, it is FlowStreamMode.MESSAGE_FORMAT.
  • full_thoughts (default): Outputs the results of all nodes in the thoughts field.
    When using this mode, you must also set the has_thoughts parameter to True.
    In the Java SDK, it is FlowStreamMode.FULL_THOUGHTS.
  • agent_format: Outputs the result of the specified node (an LLM node or the End node) in the text field. In the console application, turn on the Response switch of the target node to return results in a streaming manner.
    Do not use this mode on parallel nodes, as it may result in mixed content. Make sure the nodes with the switch enabled have a clear execution order.
    In the Java SDK, it is FlowStreamMode.AGENT_FORMAT.
The Python SDK version must be 2.0.1 or later, and the Java SDK version must be 2.21.0 or later. When calling via HTTP, put flow_stream_mode in the parameters object.
biz_paramsobject (optional)When the application passes parameters via custom variables, nodes, or plug-ins, use this field.
In the Java SDK, it is bizParams. When calling via HTTP, put biz_params in the input object.
Custom variables of the start node of a workflow application are passed directly. Example:
biz_params = {"city": "杭州"}
Agent applications pass prompt variables or plug-in variable parameters via the following fields:

Property

user_defined_params object (optional)Represents custom plug-in parameter information.Each plug-in added to an application must be unique, with a maximum of 10 plug-ins.

Property

tool_idstring (Optional)The plug-in ID, which you can obtain from the plug-in card.${plugin_params}string (Optional)The multiple key-value pairs contained in the innermost part of the object. Each key-value pair represents a user-defined parameter name to pass and its specified value. For example:
"article_index": 2
Usage Steps:
  1. Associate the specified plug-in in the application and publish the application.
  2. The API call passes plug-in information through this parameter.
You can provide multiple key-value pairs, where each key is the plug-in's TOOL_ID and the value is the parameter object required by the plug-in. Example:
"user_defined_params": {
        "<TOOL_ID>": {
            "article_index": 2},
        "<TOOL_ID>": {
            "article_index": 8}
        }
user_defined_tokens object (Optional)Represents the user-level authentication information for custom plug-ins.Each plug-in added to an application must be unique, with a maximum of 10 plug-ins.

Property

tool_idstring (Optional)The plug-in ID, which you can obtain from the plug-in card. Pass it through the <TOOL_ID> field.user_token string (Optional)Passes the user authentication information required by the plug-in, such as the actual value of DASHSCOPE_API_KEY.
Usage Steps:
  1. Associate the specified plug-in in the application and publish the application.
  2. The API call passes the plug-in user-level authentication information through this parameter.
You can provide multiple key-value pairs, where each key is the plug-in's TOOL_ID and the value is a user_token object.
has_thoughts boolean (Optional) Default value: FalseWhether to output the process of plug-in calls and knowledge retrieval, which can be viewed in the thoughts field.Parameter Value:
  • True: output.
  • False (default): no output.
In the Java SDK, it is hasThoughts. When calling via HTTP, put has_thoughts in the parameters object.
rag_options object (Optional)Used to configure retrieval-related parameters, including but not limited to retrieving from specified knowledge bases or documents.
Only agent applications support this parameter.
In the Java SDK, it is ragOptions. When calling via HTTP, put rag_options in the parameters object.

Property

pipeline_ids array (Required)A list containing one or more knowledge base IDs. The maximum is 5.Retrieves all documents in the specified knowledge bases.How to obtain:
  • Obtain the knowledge base ID on the knowledge base page;
  • Or from the Data.Id returned by the CreateIndex API (only unstructured knowledge bases are supported).
In the Java SDK, this is pipelineIds.
file_idsarray (Optional)A list containing one or more unstructured document IDs. The upper limit is 5.Retrieve unstructured documents within the specified knowledge base.When passing document IDs, you must also pass the knowledge base IDs to which these documents belong in the pipeline_ids field.How to obtain:
In the Java SDK, this is fileIds.
metadata_filterobject (Optional)The metadata used to filter unstructured documents. By specifying one or more key-value pairs, you can retrieve unstructured documents with the specified metadata from the specified knowledge base.Prerequisites:When passing metadata, you must also pass the knowledge base IDs to which the metadata belongs in the pipeline_ids field.How to view:
  • Visit the Knowledge Base page and click View Details Meta Information on the knowledge base card to view it.
  • Or obtain it via the ListChunks API.
This object consists of one or more key-value pairs:
  • Key: String type, representing the name of the metadata.
  • Value:
    • Single-value match: the value is a String, indicating that only documents whose field value exactly equals this string are retrieved.
      • Example: "author": "John.Doe"
    • Multiple-value "OR" match: the value is an Array or List containing multiple String values. This indicates retrieving documents whose field value matches any value in the array (logic is OR).
      • Example: "source": ["internal_wiki", "public_docs"]
Combined logic:
The logic between different keys is "AND". For example, "author": "John.Doe", "source": ["internal_wiki", "public_docs"] means filtering documents whose author is "John.Doe" and whose source is "internal_wiki" or "public_docs".

In the Java SDK, this is metadataFilter.
tags array (Optional)A list containing one or more unstructured document tags.Retrieve unstructured documents with the specified tags.How to view:
  • Single-turn
  • Multi-turn
  • Pass parameters
  • Streaming output
  • Knowledge base retrieval
  • Python
  • Java
  • HTTP
Request example
import os
import dashscope
from dashscope import DashScopeError

# The following is the configuration for the Singapore region. Replace {WorkspaceId} with your workspace ID. The region value varies by region.
client = dashscope.Client(
    # If not using an environment variable, set your API key directly (e.g., api_key="sk-xxx"). However, it is not recommended to hardcode your API key in code in production environments, to reduce the risk of API key leakage.
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)
try:
    response = client.apps.completions.create(
        app_id='APP_ID',  # Replace with the actual application ID
        prompt='你是谁?')
    print(response.text)
except DashScopeError as e:
    print(f'request_id={e.request_id}')
    print(f'code={e.code}')
    print(f'message={e.message}')
    print(f'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')

Response object

status_code stringThe returned status code.200 indicates a successful request; otherwise, the request failed.If the request fails, use code to obtain the error code and message to obtain the error details.
The Java SDK does not return this parameter. A call failure throws an exception whose message contains the contents of status_code and message.
request_id stringThe unique identifier of this call.
The Java SDK returns this parameter as requestId.
code stringThe error code; empty when the call succeeds.
Only the Python SDK returns this parameter.
message stringThe error details; ignored if the request succeeds.
Only the Python SDK returns this parameter.
output objectThe call result information.

output property

text stringThe reply content generated by the model.finish_reason stringCompletion reason.stop indicates a natural stop (a preset stop token is encountered); null indicates a forced interruption (such as reaching the maximum length limit or manual stopping).session_idstringThe unique identifier of the current conversation.Pass it in subsequent requests to carry the conversation history.thoughtsarrayWhen calling, set the has_thoughts parameter to True, and you can view the process of plug-in calls and knowledge retrieval, or the thinking process of the deep thinking model in thoughts.
thought stringThe thinking process of the model.When a deep thinking model is selected in the agent application on the console and the application is successfully published, if the has_thoughts parameter is set to True in an API call, the thinking process of the model will be returned in this field.reasoningContentstringThe thinking process of the model.When a deep thinking model is selected in the workflow application on the console and the application is successfully published, if the has_thoughts parameter is set to True in an API call, the thinking process of the model will be returned in this field.action_type stringThe execution step type returned by the model. For example, API indicates executing an API plug-in, agentRag indicates executing knowledge retrieval, and reasoning indicates executing the thinking process of the deep thinking model.action_name stringThe name of the executed action, such as knowledge retrieval, API plug-in, or thinking process.action stringThe executed step.action_input_stream stringThe streaming result of the input parameters.action_input stringThe input parameters of the plug-in.observation stringThe process of retrieval or the plug-in.
doc_references arrayThe information of documents cited by the model from the retrieved documents.Only when the Show Source switch is turned on and the application is published in the agent application on the Model Studio console can doc_references contain valid information.
index_id stringThe index of the retrieved documents cited by the model, such as [1].title stringThe title of the text chunk cited by the model.doc_id stringThe ID of the document cited by the model.doc_name stringThe name of the document cited by the model.text stringThe specific text content cited by the model.biz_id stringThe business association identifier cited by the model.images arrayThe list of image URLs cited by the model.
usage objectThe data information used in this request.

usage property

modelsarrayThe model information for this call.
model_id stringThe model ID called by this application.input_tokens integerThe length of the user input text after being converted into tokens.output_tokens integerThe length of the model-generated reply after being converted into tokens.
Single-turn response example
{
    "output": {
        "finish_reason": "stop",
        "session_id": "6105c965c31b40958a43dc93c28c7a59",
        "text": "我是千问,由阿里云开发的AI助手。我被设计用来回答各种问题、提供信息和与用户进行对话。有什么我可以帮助你的吗?"
    },
    "usage": {
        "models": [
            {
                "output_tokens": 36,
                "model_id": "qwen-plus",
                "input_tokens": 74
            }
        ]
    },
    "request_id": "f97ee37d-0f9c-9b93-b6bf-bd263a232bf9"
}
Response example with a specified knowledge baseWhen calling the application knowledge base feature, if you want the output to include information about the retrieved documents cited by the model, go to the agent application in the Model Studio console, click Retrieve Configuration, turn on the Show Source switch, and publish the application.
{
    "text": "根据您的预算,我推荐您考虑百炼 Zephyr Z9。这款手机轻巧便携,拥有6.4英寸1080 x 2340像素的屏幕,搭配128GB存储与6GB RAM,非常适合日常使用<ref>[1]</ref>。此外,它还配备了4000mAh电池以及30倍数字变焦镜头,能够捕捉远处细节,价格区间在2499-2799元之间,完全符合您的预算需求<ref>[1]</ref>。",
    "finish_reason": "stop",
    "session_id": "6c1d47fa5eca46b2ad0668c04ccfbf13",
    "thoughts": null,
    "doc_references": [
        {
            "index_id": "1",
            "title": "百炼手机产品介绍",
            "doc_id": "file_7c0e9abee4f142f386e488c9baa9cf38_10317360",
            "doc_name": "百炼系列手机产品介绍",
            "doc_url": null,
            "text": "【文档名】:百炼系列手机产品介绍\n【标题】:百炼手机产品介绍\n【正文】:参考售价:5999- 6499。百炼 Ace Ultra ——游戏玩家之选:配备 6.67英寸 1080 x 2400像素屏幕,内置 10GB RAM与 256GB存储,确保游戏运行丝滑无阻。百炼 Ace Ultra ——游戏玩家之选:配备 6.67英寸 1080 x 2400像素屏幕,内置 10GB RAM与 256GB存储,确保游戏运行丝滑无阻。5500mAh电池搭配液冷散热系统,长时间游戏也能保持冷静。高动态双扬声器,沉浸式音效升级游戏体验。参考售价:3999- 4299。百炼 Zephyr Z9 ——轻薄便携的艺术:轻巧的 6.4英寸 1080 x 2340像素设计,搭配 128GB存储与 6GB RAM,日常使用游刃有余。4000mAh电池确保一天无忧,30倍数字变焦镜头捕捉远处细节,轻薄而不失强大。参考售价:2499- 2799。百炼 Flex Fold+ ——折叠屏新纪元:集创新与奢华于一身,主屏 7.6英寸 1800 x 2400像素与外屏 4.7英寸 1080 x 2400像素,多角度自由悬停设计,满足不同场景需求。512GB存储、12GB RAM,加之 4700mAh电池与 UTG超薄柔性玻璃,开启折叠屏时代新篇章。此外,这款手机还支持双卡双待、卫星通话,帮助您在世界各地都能畅联通话。参考零售价:9999- 10999。\n",
            "biz_id": null,
            "images": [

            ],
            "page_number": [
                0]
        }]
}
Error response exampleWhen an access request fails, the output indicates the cause of the error via code and message.The following shows an error response example returned when a correct API-KEY is not provided.
request_id=1d14958f-0498-91a3-9e15-be477971967b,
code=401,
message=Invalid API-key provided.

QPM limits

The default QPM (requests per minute) per application is 15000.

Error codes

If the call fails and returns an error message, see Error codes for troubleshooting.