Workflow and legacy agent application API

Updated at:

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

ImportantThis document applies only to the China (Beijing) region.

Related guides

Prerequisites

Before you begin, make sure you have completed the following steps:

  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 on the API Key management page, and configure the API Key in environment variables.
  3. Install an SDK (optional):If you call with an SDK, install the DashScope SDK for your language.

Call Method

  • HTTP API calls

    Request URL: POST https://dashscope.aliyuncs.com/api/v1/apps/APP_ID/completion

    Where APP_ID must be replaced with your actual application ID

  • SDK calls

    Python/Java SDK: This document has the correct endpoint configured by default

    Custom endpoint: configurable via the base_url parameter

Online testing: Go to Application card -> Publish -> API testing to open the testing page, then fill in the parameters and click Run.

Request body

app_idstringRequired

Application identifier.

You can obtain the application ID on the application card of the My Applications page.

In the Java SDK, it is appId.For HTTP calls, put your actual application ID in the URL to replace APP_ID.

promptstringRequired

The user's input instruction, used to guide the application to generate a reply.

For HTTP calls, put prompt into the input object.

session_idstringOptional

Session identifier for conversation history.

When session_id is passed, the request automatically carries the conversation history stored in the cloud. In this case, prompt must be passed.

This ID automatically expires after 1 consecutive hour without any requests.

In the Java SDK, this is setSessionId. When calling via HTTP, put session_id into the input object.

messagesarrayOptional

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 and 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)

The system message, used to define the model's role, tone, task objectives, or constraints. It is generally placed first in the messages array.

Property

contentstring (required)

The system instruction, used to specify the model's role, behavior rules, response style, and task constraints.

rolestring (required)

The role of the system message, fixed as system.

User Messageobject (required)

The user message, used to pass questions, instructions, or context to the model.

Property

contentstring (required)

The message content.

Property

textstring (required)

The input text.

rolestring (required)

The role of the user message, fixed as user.

Assistant Messageobject (optional)

The model's reply. It is usually passed back to the model as context in multi-turn conversations.

Property

contentstring (required)

The text content of the model's reply.

rolestring (required)

The role of the assistant message, fixed as assistant.

workspacestringOptional

The workspace identifier. Related documentation: Obtain Workspace ID.

Pass workspace ID only when calling applications in a sub-workspace.

When calling via HTTP, specify X-DashScope-WorkSpace in the header.

streambooleanOptional

Default value: False

Whether to respond in streaming output mode.

It is recommended to set it to True, which improves the reading experience and reduces the risk of timeouts.

Parameter values:

  • False (default): The model returns all content at once after generation is complete.
  • True (recommended): Content is output while being generated, and a data chunk is returned each time part of the content is generated. You need to read these chunks one by one in real time to assemble the complete reply.

To implement streaming output with the Java SDK, call the streamCall interface; to implement streaming output over HTTP, specify X-DashScope-SSE as enable in the Header.

incremental_outputbooleanOptional

Default value: False

Whether to enable incremental output in streaming output mode.

It is recommended to set it to True to improve the reading experience.

Parameter values:

  • False (default): Each output returns the entire sequence generated so far, and the last output is the complete generated result.
I
I like
I like apple
I like apple.
  • True (recommended): Incremental output, that is, subsequent output does not include content that has already been output. You need to read these fragments one by one in real time to obtain the complete result.
I
like
apple
.

In the Java SDK, it is incrementalOutput. When calling over HTTP, put incremental_output into the parameters object.

flow_stream_modestringOptional

Default value: full_thoughts

The streaming output mode of workflow applications. Related documentation: Streaming output.

Parameter values:

  • message_format_plus (recommended): Enhanced message mode.

    Outputs the execution process and results of all nodes in the workflow_message field, covering all node types. It returns the same data structure as message_format, but supports streaming push for all node types.

    ImportantClient-side processing rules: for text nodes (OUTPUT / END text mode), message.content is an incremental delta and must be appended; for JSON nodes (LLM / Component / AgentGroup, etc.), message.content is a complete JSON snapshot and must be replaced as a whole. When node_is_completed=true, the node is marked as completed.

    Sub-canvas node streaming: nodes inside the sub-canvas of loop nodes and batch processing nodes are also pushed in a streaming manner, identified by the response field parent_node_id that indicates the parent node they belong to.

    ImportantNested sub-canvas is not supported yet: loop or batch processing nodes cannot be placed inside the sub-canvas of loop/batch processing nodes.

    In the Java SDK, it is FlowStreamMode.MESSAGE_FORMAT_PLUS.

  • message_format (recommended): Message mode.

    Outputs the results of specified nodes (Output nodes or End nodes) in the message field.

    ImportantEnable the streaming output switch for the target node in the application in the console to return results in a streaming manner; if 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): Full thoughts mode.

    NoteNot recommended for new business. We recommend using message_format or message_format_plus instead.

    Outputs the results of all nodes in the thoughts field.

    ImportantWhen using this mode, you must also set the has_thoughts parameter to True.

    In the Java SDK, it is FlowStreamMode.FULL_THOUGHTS.

The Python SDK must be 2.0.1 or later, and the Java SDK must be 2.22.23 or later. When calling over HTTP, put flow_stream_mode into the parameters object.

biz_paramsobjectOptional

When an application passes parameters through custom variables, nodes, or plug-ins, use this field for the transfer. Related documentation: Call agent applications - Pass custom parameters, Call workflow applications - Pass custom parameters.

In the Java SDK, this is bizParams. When calling via HTTP, put biz_params into the input object.

For workflow applications, the custom variables of the start node are passed directly. Example:

biz_params = {"city": "杭州"}

For agent applications, prompt variables or plug-in variable parameters are passed via the following fields:

Property

user_prompt_params object (optional)

Represents custom prompt variable parameter information.

Variable names within an application must be unique, with a limit of 10.

Usage steps:

  1. Configure custom variables and reference them in the prompt within the application, then publish the application.
  2. The API call passes variable information through this parameter.

Example:

biz_params ={
    "user_prompt_params": {
        "date": "2025年03月03日",
        "city": "杭州"
    }
}

user_defined_params object (optional)

Represents custom plug-in parameter information.

Plug-ins added within an application must be unique, with a limit of 10.

Property

tool_idstring (optional)

The plug-in ID, which can be obtained from the plug-in card.

${plugin_params}string (optional)

Multiple key-value pairs contained in the innermost level of the object. Each key-value pair represents a user-defined parameter name to be passed 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 that plug-in. Example:

"user_defined_params": {
        "<TOOL_ID>": {
            "article_index": 2},
        "<TOOL_ID>": {
            "article_index": 8}
        }

user_defined_tokens object (optional)

Represents user-level authentication information for custom plug-ins.

Plug-ins added within an application must be unique, with a limit of 10.

Property

tool_idstring (optional)

The plug-in ID, which can be obtained from the plug-in card. Passed via 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's 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.

memory_idstringOptional

The long-term memory ID. See CreateMemory to create one. Related document: long-term memory.

NoteOnly agent applications support this parameter.

  1. Enable the long-term memory switch in the application, and publish the application.
  2. When calling the application with a specified memory_id, the system automatically builds and saves long-term memories based on user preferences.
  3. On subsequent calls with the same memory_id, the system restores these long-term memories and merges them with the latest user message before providing them to the model for processing.

In the Java SDK, this is memoryId. When calling via HTTP, put memory_id into the input object.

has_thoughtsbooleanOptional

The default value is False

Whether to output the process of plug-in calls and knowledge retrieval, or the thinking process of a model with thinking mode enabled. You can view it in the thoughts field.

Parameter values:

  • True: Output.
  • False (default): Do not output.

In the Java SDK, this is hasThoughts. When calling via HTTP, put has_thoughts in the parameters object.

image_listarrayOptional

A list of images. Supports image URLs and Data URLs (Base64-encoded). You must select a vision and video understanding model in the application.

The base64 encoding format can be constructed as a Data URL: data:[MIME_type];base64,{base64_image}. For details and code examples, see the visual understanding section on the right side of this document.

Scenarios:

  • Image retrieval (agent applications): Retrieve structured knowledge bases that contain image links based on the uploaded image links.
  • Visual understanding: Use the visual understanding capability of the Qwen VL series models to analyze image content for question answering.

Related document: Upload files (documents, images, videos, or audio).

In the Java SDK, this is images. When calling via HTTP, put image_list in the input object.

file_listarrayOptional

A list that contains one or more file URLs.

NoteOnly agent applications support this parameter.

Related document: Upload files (documents, images, videos, or audio).

In the Java SDK, this is files. When calling via HTTP, put file_list in the input object.

The Python DashScope SDK version must be 2.0.1 or later, and the Java DashScope SDK version must be 2.21.13 or later.

rag_optionsobjectOptional

Used to configure retrieval-related parameters, including but not limited to retrieving from specified knowledge bases or documents. For more information, see Retrieve knowledge bases.

NoteOnly agent applications support this parameter.

In the Java SDK, this is ragOptions. When calling via HTTP, put rag_options in the parameters object.

Property

pipeline_ids array (Required)

A list that contains one or more knowledge base IDs. The maximum is 5.

Retrieve all documents in the specified knowledge bases.

How to obtain:

  • Obtain the knowledge base ID on the Knowledge Base page;
  • Or use the Data.Id returned by the CreateIndex API (only supports unstructured knowledge bases).

In the Java SDK, this is pipelineIds.

file_idsarray (Optional)

A list that contains one or more unstructured document IDs. The maximum is 5.

Retrieve unstructured documents in the specified knowledge bases.

When passing in document IDs, you must also pass the knowledge base IDs to which these documents belong in the pipeline_ids field.

How to obtain:

  • In Collections, click Details for the target file dataset. Get the document ID from the file list.
  • Or through the ID returned by the AddFile API for importing documents.

In the Java SDK, it is fileIds.

metadata_filterobject (Optional)

Used to filter the metadata of unstructured documents. By specifying one or more key-value pairs, unstructured documents with this metadata in the specified knowledge base are retrieved.

Prerequisites:

When passing in 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 through the ListChunks API.

This object consists of one or more key-value pairs:

  • Key: of type String, representing the name of the metadata.

  • Value:

    • Single-value matching: The value is a String, indicating that only documents whose field value is exactly equal to this string are retrieved.

      • Example: "author": "John.Doe"
    • Multiple-value "OR" matching: The value is an Array or List containing multiple String values. This indicates retrieving documents whose field value matches any value in the array (the logic is OR).

      • Example: "source": ["internal_wiki", "public_docs"]

Combination logic:
Different keys are combined with "AND" logic. For example, "author": "John.Doe", "source": ["internal_wiki", "public_docs"] means filtering out documents whose author is "John.Doe" and whose source is "internal_wiki" or "public_docs".

In the Java SDK, it is metadataFilter.

tags array (Optional)

A list containing one or more unstructured document tags.

Retrieves unstructured documents that have these tags.

How to view:

  • In Collections, click Details for the target file dataset and check the tags on the document.
  • Or obtain them through the DescribeFile API.

structured_filter object (Optional)

Used to perform metadata filtering on structured data. By specifying one or more key-value pairs, you can filter out document chunks that meet the conditions.

How to view:

  • On the Knowledge Base page, click View Details View Index on the knowledge base card to view it.
  • Or obtain it through the ListChunks API.

This object consists of one or more key-value pairs:

Each key (column name) must have a corresponding value; filtering by column name only is not supported.

  • Key: Must be of type String, representing the name of the metadata field (column name) to filter.

  • Value:

    • Single-condition matching: The value is a String or Number, indicating that only documents whose field value exactly matches are retrieved. Example: "category": "Company News".
    • Multiple-value "OR" matching: The value is an Array or List containing multiple String or Number values. This indicates retrieving documents whose field value matches any value in the array (the logic is OR). Example: "year": 2024, "department": ["Engineering", "Product"].

Combination logic:
Different keys are combined with "AND" logic. For example, "year": 2024, "department": ["Engineering", "Product"] means filtering out document chunks whose year is 2024 and whose department is "Engineering" or "Product".

In the Java SDK, it is structuredFilter.

session_file_idsarray(Optional)

A list containing one or more file IDs. The maximum is 10.

NoteOnly agent applications support this parameter.

When calling an agent application, pass the file IDs, and the system will extract the text content from the files as the content basis for LLM question answering.

Related document: Upload files (documents, images, videos, or audio).

ImportantThe session file ID must start with "file_session_" and the file status must be FILE_IS_READY. Otherwise, the call fails.

In the Java SDK, it is sessionFileIds.

The Python DashScope SDK must be at least 2.0.1, and the Java DashScope SDK must be at least 2.17.0.

model_idstringOptional

The model name.

NoteOnly agent applications support this parameter.

When calling the API, you can pass the model name used for this call through this parameter.

Priority: When the model_id passed through the API differs from the console configuration, the API parameter value takes precedence.

In the Java SDK, it is modelId. When calling through HTTP, put model_id into the parameters object.

The Java DashScope SDK must be at least 2.19.3.

enable_system_timebooleanOptional

Default value: True

Controls whether the model automatically obtains the current time (Beijing time).

NoteOnly agent applications support this parameter.

Parameter values:

  • True (default): The current time is enabled, and the model can directly respond to real-time requests (such as "today's date").
  • False: The current time is disabled. You need to manually pass in the time through custom variables. For example:
# 通过 user_prompt_params 传递自定义时间
biz_params ={
    "user_prompt_params": {
        "date": "2025年03月03日"
    }
}

Scenarios:

  • You need to customize the time source instead of relying on the current time.
  • Avoid changes in model output caused by changes in the current time.

In the Java SDK, it is enableSystemTime. When calling through HTTP, put enable_system_time into the parameters object.

The Java DashScope SDK must be at least 2.19.3.

enable_web_searchbooleanOptional

Default value: false

Whether the model uses internet search results as reference when generating a reply.

NoteOnly agent applications support this parameter.

Parameter values:

  • True: Internet search is enabled, and the model uses the search results as reference information when generating a reply.

    NoteThe model decides on its own whether and when to trigger an internet search.

  • False (default): Disables internet search.

Priority:

  • If this parameter is not set during the call, the status of the in-app web search

    switch takes precedence.

  • If enable_web_search is set during the call, the API parameter takes precedence.

Enabling the internet search feature may increase Token consumption.

In the Java SDK, it is enableWebSearch. When calling through HTTP, put enable_web_search into the parameters object.

The Java DashScope SDK must be at least 2.19.3.

dialog_roundintegerOptional

The number of context rounds carried.

NoteOnly agent applications support this parameter.

Sets the maximum number of historical conversation rounds input to the model. The more rounds, the stronger the conversation relevance.

Priority: When the dialog_round passed through the API differs from the console configuration, the API parameter value takes precedence.

In the Java SDK, it is dialogRound. When calling through HTTP, put dialog_round into the parameters object.

The Java DashScope SDK must be at least 2.19.3.

enable_thinkingbooleanOptional

Default value: false

This parameter is used to switch between thinking mode and non-thinking mode in deep thinking models. It applies only to agent applications.

ImportantWorkflow applications do not support dynamically controlling the thinking mode through this parameter; you need to set it in each LLM node separately.

Parameter values:

  • False (default): Non-thinking mode. The final answer is returned directly (in the text field).
  • True: Thinking mode is enabled. The model first outputs the thinking process and then returns the final answer.

Priority:

  • If this parameter is not set at the call, the thinking mode switch state of the model in the application takes precedence.
  • If enable_thinking is set at the call, the API parameter takes precedence.

ImportantTo obtain the content of the thinking process, you must also set has_thoughts to True. Then:

  1. Thinking process: for agent applications, obtain it through the thought field; for workflow applications, obtain it through the reasoningContent field.
  2. Final answer: obtain it through the text field.

There is a very small chance that the thinking process is not output even after enable_thinking is enabled.

In the Java SDK, this parameter is enableThinking. When you call the API over HTTP, put enable_thinking in the parameters object.

The Java DashScope SDK version must be 2.20.0 or later.

Single-turn conversation

Python

Request example
import os
import dashscope
from dashscope import DashScopeError

client = dashscope.Client(
    # 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
    api_key=os.getenv("DASHSCOPE_API_KEY"))
try:
    response = client.apps.completions.create(
        app_id='APP_ID',  # 替换为实际的应用 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'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')

Java

Request example
// 建议dashscope SDK的版本 >= 2.12.0
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;

public class Main {
    public static void appCall()
            throws ApiException, NoApiKeyException, InputRequiredException {
        ApplicationParam param = ApplicationParam.builder()
                // 若没有配置环境变量,可用百炼API Key将下行替换为:.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .appId("APP_ID")
                .prompt("你是谁?")
                .build();

        Application application = new Application();
        ApplicationResult result = application.call(param);

        System.out.printf("text: %s\n",
                result.getOutput().getText());
    }

    public static void main(String[] args) {
        try {
            appCall();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.err.println("message:"+e.getMessage());
            System.out.println("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}

HTTP

curl

Request example
curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "prompt": "你是谁?"
    },
    "parameters":  {},
    "debug": {}
}'

Replace APP_ID with the actual application ID.

PHP

Request example
<?php

# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // 替换为实际的应用 ID

$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";

// 构造请求数据
$data = [
    "input" => [
        'prompt' => '你是谁?'
    ]
];

// 将数据编码为 JSON
$dataString = json_encode($data);

// 检查 json_encode 是否成功
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON encoding failed with error: " . json_last_error_msg());
}

// 初始化 cURL 对话
$ch = curl_init($url);

// 设置 cURL 选项
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $api_key
]);

// 执行请求
$response = curl_exec($ch);

// 检查 cURL 执行是否成功
if ($response === false) {
    die("cURL Error: " . curl_error($ch));
}

// 获取 HTTP 状态码
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 关闭 cURL 对话
curl_close($ch);
// 解码响应数据
$response_data = json_decode($response, true);
// 处理响应
if ($status_code == 200) {
    if (isset($response_data['output']['text'])) {
        echo "{$response_data['output']['text']}\n";
    } else {
        echo "No text in response.\n";
    }}
else {
    if (isset($response_data['request_id'])) {
        echo "request_id={$response_data['request_id']}\n";}
    echo "code={$status_code}\n";
    if (isset($response_data['message'])) {
        echo "message={$response_data['message']}\n";}
    else {
        echo "message=Unknown error\n";}
}
?>

Node.js

You must install the following dependencies:
npm install axios
Request example
const axios = require('axios');

async function callDashScope() {
    // 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';// 替换为实际的应用 ID

    const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;

    const data = {
        input: {
            prompt: "你是谁?"
        },
        parameters: {},
        debug: {}
    };

    try {
        const response = await axios.post(url, data, {
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            }
        });

        if (response.status === 200) {
            console.log(`${response.data.output.text}`);
        } else {
            console.log(`request_id=${response.headers['request_id']}`);
            console.log(`code=${response.status}`);
            console.log(`message=${response.data.message}`);
        }
    } catch (error) {
        console.error(`Error calling DashScope: ${error.message}`);
        if (error.response) {
            console.error(`Response status: ${error.response.status}`);
            console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
        }
    }
}

callDashScope();

C#

Request example
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        //若没有配置环境变量,可用百炼API Key将下行替换为:apiKey="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
        string appId = "APP_ID"; // 替换为实际的应用ID

        string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");

            string jsonContent = @"{
                ""input"": {
                    ""prompt"": ""你是谁?""
                },
                ""parameters"": {},
                ""debug"": {}
            }";

            HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

            try
            {
                HttpResponseMessage response = await client.PostAsync(url, content);

                if (response.IsSuccessStatusCode)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine("Request successful:");
                    Console.WriteLine(responseBody);
                }
                else
                {
                    Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error calling DashScope: {ex.Message}");
            }
        }
    }
}

Go

Request example
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
)

func main() {
	// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // 替换为实际的应用 ID

	if apiKey == "" {
		fmt.Println("请确保设置了DASHSCOPE_API_KEY。")
		return
	}

	url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)

	// 创建请求体
	requestBody := map[string]interface{}{
		"input": map[string]string{
			"prompt": "你是谁?",
		},
		"parameters": map[string]interface{}{},
		"debug":      map[string]interface{}{},
	}

	jsonData, err := json.Marshal(requestBody)
	if err != nil {
		fmt.Printf("Failed to marshal JSON: %v\n", err)
		return
	}

	// 创建 HTTP POST 请求
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Printf("Failed to create request: %v\n", err)
		return
	}

	// 设置请求头
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	// 发送请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Printf("Failed to send request: %v\n", err)
		return
	}
	defer resp.Body.Close()

	// 读取响应
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Failed to read response: %v\n", err)
		return
	}

	// 处理响应
	if resp.StatusCode == http.StatusOK {
		fmt.Println("Request successful:")
		fmt.Println(string(body))
	} else {
		fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
		fmt.Println(string(body))
	}
}

dashscope CLI

Request example
export DASHSCOPE_API_KEY="your-api-key"
# 将 {WorkspaceId} 替换为业务空间ID,cn-beijing 替换为对应地域(新加坡: ap-southeast-1, 美东: us-east-1)
export DASHSCOPE_HTTP_BASE_URL="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1"
dashscope application create -a your-app-id -p "你好"

Replace your-app-id with the actual application ID. -a specifies the application ID, and -p specifies the prompt content.

ImportantThe SDK Expert interactive assistant can complete the same development and troubleshooting work in natural language. See

DashScope SDK Expert.

For the complete region list, see Base URL overview.

Multi-turn conversation

Enable multi-turn conversations through session_id or messages. Related documents: Call an agent application - multi-turn conversation, Call a workflow application - multi-turn conversation.

Python

Request example
import os
import dashscope
from dashscope import DashScopeError

def call_with_session():
    client = dashscope.Client(
        # 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
        api_key=os.getenv("DASHSCOPE_API_KEY"))
    try:
        response = client.apps.completions.create(
            app_id='APP_ID',  # 替换为实际的应用 ID
            prompt='你是谁?')

        responseNext = client.apps.completions.create(
                    app_id='APP_ID',  # 替换为实际的应用 ID
                    prompt='你有什么技能?',
                    session_id=response.session_id)  # 上一轮response的session_id

        print('%s\n session_id=%s\n' % (responseNext.text, responseNext.session_id))
        # print('%s\n' % (response.usage))
    except DashScopeError as e:
        print(f'request_id={e.request_id}')
        print(f'code={e.code}')
        print(f'message={e.message}')
        print(f'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')

if __name__ == '__main__':
    call_with_session()

Java

Request example
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import java.util.Arrays;
import java.util.List;
public class Main {
    public static void callWithSession()
            throws ApiException, NoApiKeyException, InputRequiredException {
        ApplicationParam param = ApplicationParam.builder()
                // 若没有配置环境变量,可用百炼API Key将下行替换为:.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // 替换为实际的应用 ID
                .appId("APP_ID")
                .prompt("你是谁?")
                .build();

        Application application = new Application();
        ApplicationResult result = application.call(param);

        param.setSessionId(result.getOutput().getSessionId());
        param.setPrompt("你有什么技能?");
        result = application.call(param);

        System.out.printf("%s\n session_id: %s\n",
                result.getOutput().getText(), result.getOutput().getSessionId());
    }

    public static void main(String[] args) {
        try {
            callWithSession();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.printf("Exception: %s", e.getMessage());
            System.out.println("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}

HTTP

curl

Request example (previous turn)
curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "prompt": "你是谁?"
    },
    "parameters":  {},
    "debug": {}
}'
Request example (next turn)
curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "prompt": "你有什么技能?",
        "session_id":"4f8ef7233dc641aba496cb201fa59f8c"
    },
    "parameters":  {},
    "debug": {}
}'

PHP

Request example (previous turn)
<?php
# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // 替换为实际的应用 ID

$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";

// 构造请求数据
$data = [
    "input" => [
        'prompt' => '你是谁?'
    ]
];

// 将数据编码为 JSON
$dataString = json_encode($data);

// 检查 json_encode 是否成功
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON encoding failed with error: " . json_last_error_msg());
}

// 初始化 cURL 对话
$ch = curl_init($url);

// 设置 cURL 选项
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $api_key
]);

// 执行请求
$response = curl_exec($ch);

// 检查 cURL 执行是否成功
if ($response === false) {
    die("cURL Error: " . curl_error($ch));
}

// 获取 HTTP 状态码
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 关闭 cURL 对话
curl_close($ch);
// 解码响应数据
$response_data = json_decode($response, true);
// 处理响应
if ($status_code == 200) {
    if (isset($response_data['output']['text'])) {
        echo "{$response_data['output']['text']}\n";
    } else {
        echo "No text in response.\n";
    };
    if (isset($response_data['output']['session_id'])) {
        echo "session_id={$response_data['output']['session_id']}\n";
    }
}else {
    if (isset($response_data['request_id'])) {
        echo "request_id={$response_data['request_id']}\n";}
    echo "code={$status_code}\n";
    if (isset($response_data['message'])) {
        echo "message={$response_data['message']}\n";}
    else {
        echo "message=Unknown error\n";}
}
?>
Request example (next turn)
<?php
# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // 替换为实际的应用 ID

$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";

// 构造请求数据
$data = [
    "input" => [
        'prompt' => '你有什么技能?',
        // 替换为实际上一轮对话返回的session_id
        'session_id' => '2e658bcb514f4d30ab7500b4766a8d43'
    ]
];

// 将数据编码为 JSON
$dataString = json_encode($data);

// 检查 json_encode 是否成功
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON encoding failed with error: " . json_last_error_msg());
}

// 初始化 cURL 对话
$ch = curl_init($url);

// 设置 cURL 选项
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $api_key
]);

// 执行请求
$response = curl_exec($ch);

// 检查 cURL 执行是否成功
if ($response === false) {
    die("cURL Error: " . curl_error($ch));
}

// 获取 HTTP 状态码
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 关闭 cURL 对话
curl_close($ch);
// 解码响应数据
$response_data = json_decode($response, true);
// 处理响应
if ($status_code == 200) {
    if (isset($response_data['output']['text'])) {
        echo "{$response_data['output']['text']}\n";
    } else {
        echo "No text in response.\n";
    };
    if (isset($response_data['output']['session_id'])) {
        echo "session_id={$response_data['output']['session_id']}\n";
    }
}else {
    if (isset($response_data['request_id'])) {
        echo "request_id={$response_data['request_id']}\n";}
    echo "code={$status_code}\n";
    if (isset($response_data['message'])) {
        echo "message={$response_data['message']}\n";}
    else {
        echo "message=Unknown error\n";}
}
?>

Node.js

You must install the following dependencies:
npm install axios
Request example (previous turn)
const axios = require('axios');

async function callDashScope() {
    // 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';// 替换为实际的应用 ID

    const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;

    const data = {
        input: {
            prompt: "你是谁?"
        },
        parameters: {},
        debug: {}
    };

    try {
        const response = await axios.post(url, data, {
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            }
        });

        if (response.status === 200) {
            console.log(`${response.data.output.text}`);
            console.log(`session_id=${response.data.output.session_id}`);
        } else {
            console.log(`request_id=${response.headers['request_id']}`);
            console.log(`code=${response.status}`);
            console.log(`message=${response.data.message}`);
        }
    } catch (error) {
        console.error(`Error calling DashScope: ${error.message}`);
        if (error.response) {
            console.error(`Response status: ${error.response.status}`);
            console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
        }
    }
}
callDashScope();
Request example (next turn)
const axios = require('axios');

async function callDashScope() {
    // 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';// 替换为实际的应用 ID

    const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
    // session_id替换为实际上一轮对话的session_id
    const data = {
        input: {
            prompt: "你有什么技能?",
            session_id: 'fe4ce8b093bf46159ea9927a7b22f0d3',
        },
        parameters: {},
        debug: {}
    };

    try {
        const response = await axios.post(url, data, {
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            }
        });

        if (response.status === 200) {
            console.log(`${response.data.output.text}`);
            console.log(`session_id=${response.data.output.session_id}`);
        } else {
            console.log(`request_id=${response.headers['request_id']}`);
            console.log(`code=${response.status}`);
            console.log(`message=${response.data.message}`);
        }
    } catch (error) {
        console.error(`Error calling DashScope: ${error.message}`);
        if (error.response) {
            console.error(`Response status: ${error.response.status}`);
            console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
        }
    }
}
callDashScope();

C#

Request example (previous turn)
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        //若没有配置环境变量,可用百炼API Key将下行替换为:apiKey="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
        string appId = "APP_ID"; // 替换为实际的应用ID

        string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");

            string jsonContent = @"{
                ""input"": {
                    ""prompt"": ""你是谁?""
                },
                ""parameters"": {},
                ""debug"": {}
            }";

            HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

            try
            {
                HttpResponseMessage response = await client.PostAsync(url, content);

                if (response.IsSuccessStatusCode)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine("Request successful:");
                    Console.WriteLine(responseBody);
                }
                else
                {
                    Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error calling DashScope: {ex.Message}");
            }
        }
    }
}
Request example (next turn)
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        //若没有配置环境变量,可用百炼API Key将下行替换为:apiKey="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
        string appId = "APP_ID"; // 替换为实际的应用ID

        string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");

            string jsonContent = @"{
                ""input"": {
                    ""prompt"": ""你有什么技能?"",
                    ""session_id"": ""7b830e4cc8fe44faad0e648f9b71435f""
                },
                ""parameters"": {},
                ""debug"": {}
            }";

            HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

            try
            {
                HttpResponseMessage response = await client.PostAsync(url, content);

                if (response.IsSuccessStatusCode)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine("Request successful:");
                    Console.WriteLine(responseBody);
                }
                else
                {
                    Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error calling DashScope: {ex.Message}");
            }
        }
    }
}

Go

Request example (previous turn)
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
)

func main() {
	// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // 替换为实际的应用 ID

	if apiKey == "" {
		fmt.Println("请确保设置了DASHSCOPE_API_KEY。")
		return
	}

	url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)

	// 创建请求体
	requestBody := map[string]interface{}{
		"input": map[string]string{
			"prompt": "你是谁?",
		},
		"parameters": map[string]interface{}{},
		"debug":      map[string]interface{}{},
	}

	jsonData, err := json.Marshal(requestBody)
	if err != nil {
		fmt.Printf("Failed to marshal JSON: %v\n", err)
		return
	}

	// 创建 HTTP POST 请求
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Printf("Failed to create request: %v\n", err)
		return
	}

	// 设置请求头
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	// 发送请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Printf("Failed to send request: %v\n", err)
		return
	}
	defer resp.Body.Close()

	// 读取响应
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Failed to read response: %v\n", err)
		return
	}

	// 处理响应
	if resp.StatusCode == http.StatusOK {
		fmt.Println("Request successful:")
		fmt.Println(string(body))
	} else {
		fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
		fmt.Println(string(body))
	}
}
Request example (next turn)
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
)

func main() {
	// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // 替换为实际的应用 ID

	if apiKey == "" {
		fmt.Println("请确保设置了DASHSCOPE_API_KEY。")
		return
	}

	url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)

	// 创建请求体
	requestBody := map[string]interface{}{
		"input": map[string]string{
			"prompt":     "你有什么技能?",
			"session_id": "f7eea37f0c734c20998a021b688d6de2", // 替换为实际上一轮对话的session_id
		},
		"parameters": map[string]interface{}{},
		"debug":      map[string]interface{}{},
	}

	jsonData, err := json.Marshal(requestBody)
	if err != nil {
		fmt.Printf("Failed to marshal JSON: %v\n", err)
		return
	}

	// 创建 HTTP POST 请求
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Printf("Failed to create request: %v\n", err)
		return
	}

	// 设置请求头
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	// 发送请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Printf("Failed to send request: %v\n", err)
		return
	}
	defer resp.Body.Close()

	// 读取响应
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Failed to read response: %v\n", err)
		return
	}

	// 处理响应
	if resp.StatusCode == http.StatusOK {
		fmt.Println("Request successful:")
		fmt.Println(string(body))
	} else {
		fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
		fmt.Println(string(body))
	}
}

Replace APP_ID with the actual application ID. In the next turn, replace the value of the session_id input parameter with the session_id value returned in the previous turn.

Pass parameters

Pass custom parameters through biz_params. Related documents: Call an agent application - Pass custom parameters, Invoke a workflow application - Pass custom parameters.

Python

Request example
import os
import dashscope
# 需要 dashscope 2.0.1 及以上版本
from dashscope import DashScopeError

client = dashscope.Client(
        # 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
        api_key=os.getenv("DASHSCOPE_API_KEY"))
biz_params = {
    # 智能体应用的自定义插件输入参数传递,自定义的插件ID替换<TOOL_ID>
    "user_defined_params": {
        "<TOOL_ID>": {
            "article_index": 2}}}
try:
    response = client.apps.completions.create(
        app_id='APP_ID',
        prompt='寝室公约内容',
        biz_params=biz_params)
    print('%s\n' % (response.text))  # 处理只输出文本text
    # print('%s\n' % (response.usage))
except DashScopeError as e:
    print(f'request_id={e.request_id}')
    print(f'code={e.code}')
    print(f'message={e.message}')
    print(f'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')

Java

Request example
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;

public class Main {
    public static void appCall() throws NoApiKeyException, InputRequiredException {
        String bizParams =
                // 智能体应用的自定义插件输入参数传递,自定义的插件ID替换<TOOL_ID>
                "{\"user_defined_params\":{\"<TOOL_ID>\":{\"article_index\":2}}}";
        ApplicationParam param = ApplicationParam.builder()
                // 若没有配置环境变量,可用百炼API Key将下行替换为:.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .appId("APP_ID")
                .prompt("寝室公约内容")
                .bizParams(JsonUtils.parse(bizParams))
                .build();

        Application application = new Application();
        ApplicationResult result = application.call(param);
        System.out.printf("%s\n",
                result.getOutput().getText());
    }

    public static void main(String[] args) {
        try {
            appCall();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.printf("Exception: %s", e.getMessage());
            System.out.println("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}

HTTP

curl

Request example
curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "prompt": "寝室公约内容",
        "biz_params":
        {
            "user_defined_params":
            {
                "<TOOL_ID>":
                    {
                    "article_index": 2
                    }
            }
        }
    },
    "parameters":  {},
    "debug":{}
}'

Replace APP_ID with the actual application ID. Replace <TOOL_ID> with the plugin ID.

PHP

Request example
<?php

# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // 替换为实际的应用 ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";
//<TOOL_ID>替换为实际的插件ID
// 构造请求数据
$data = [
    "input" => [
        'prompt' => '寝室公约内容',
        'biz_params' => [
        'user_defined_params' => [
            '<TOOL_ID>' => [
                'article_index' => 2
                ]
            ]
        ]
    ],
];
// 将数据编码为 JSON
$dataString = json_encode($data);

// 检查 json_encode 是否成功
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON encoding failed with error: " . json_last_error_msg());
}

// 初始化 cURL 对话
$ch = curl_init($url);

// 设置 cURL 选项
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $api_key
]);

// 执行请求
$response = curl_exec($ch);

// 检查 cURL 执行是否成功
if ($response === false) {
    die("cURL Error: " . curl_error($ch));
}

// 获取 HTTP 状态码
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 关闭 cURL 对话
curl_close($ch);
// 解码响应数据
$response_data = json_decode($response, true);
// 处理响应
if ($status_code == 200) {
    if (isset($response_data['output']['text'])) {
        echo "{$response_data['output']['text']}\n";
    } else {
        echo "No text in response.\n";
    }
}else {
    if (isset($response_data['request_id'])) {
        echo "request_id={$response_data['request_id']}\n";}
    echo "code={$status_code}\n";
    if (isset($response_data['message'])) {
        echo "message={$response_data['message']}\n";}
    else {
        echo "message=Unknown error\n";}
}
?>

Node.js

You must install the following dependencies:
npm install axios
Request example
const axios = require('axios');

async function callDashScope() {
    // 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';// 替换为实际的应用 ID
    const pluginCode = 'TOOL_ID';// 替换为实际的插件ID
    const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;

    const data = {
        input: {
            prompt: "寝室公约内容",
            biz_params: {
                user_defined_params: {
                    [pluginCode]: {
                        // article_index为自定义插件的变量,替换为实际的插件变量
                        'article_index': 3
                    }
                }
            }
        },
        parameters: {},
        debug: {}
    };

    try {
        console.log("Sending request to DashScope API...");

        const response = await axios.post(url, data, {
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            }
        });

        if (response.status === 200) {
            if (response.data.output && response.data.output.text) {
                console.log(`${response.data.output.text}`);
            }
        } else {
            console.log("Request failed:");
            if (response.data.request_id) {
                console.log(`request_id=${response.data.request_id}`);
            }
            console.log(`code=${response.status}`);
            if (response.data.message) {
                console.log(`message=${response.data.message}`);
            } else {
                console.log('message=Unknown error');
            }
        }
    } catch (error) {
        console.error(`Error calling DashScope: ${error.message}`);
        if (error.response) {
            console.error(`Response status: ${error.response.status}`);
            console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
        }
    }
}
callDashScope();

C#

Request example
using System.Text;

class Program
{
    static async Task Main(string[] args)
    {
        // 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
        string appId = "APP_ID";// 替换为实际的应用ID

        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("请确保设置了 DASHSCOPE_API_KEY。");
            return;
        }

        string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
            string pluginCode = "TOOL_ID"; // TOOL_ID替换为实际的插件 ID
            string jsonContent = $@"{{
                ""input"": {{
                    ""prompt"": ""寝室公约内容"",
                    ""biz_params"": {{
                        ""user_defined_params"": {{
                            ""{pluginCode}"": {{
                                ""article_index"": 2
                            }}
                        }}
                    }}
                }},
                ""parameters"": {{}},
                ""debug"": {{}}
            }}";

            HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

            try
            {
                HttpResponseMessage response = await client.PostAsync(url, content);

                if (response.IsSuccessStatusCode)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine("Request successful:");
                    Console.WriteLine(responseBody);
                }
                else
                {
                    Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error calling DashScope: {ex.Message}");
            }
        }
    }
}

Go

Request example
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
)

func main() {
	// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID"           // 替换为实际的应用 ID
	pluginCode := "TOOL_ID" // 替换为实际的插件 ID

	if apiKey == "" {
		fmt.Println("请确保设置了DASHSCOPE_API_KEY。")
		return
	}

	url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)

	// 创建请求体
	requestBody := map[string]interface{}{
		"input": map[string]interface{}{
			"prompt": "寝室公约内容",
			"biz_params": map[string]interface{}{
				"user_defined_params": map[string]interface{}{
					pluginCode: map[string]interface{}{
						"article_index": 2,
					},
				},
			},
		},
		"parameters": map[string]interface{}{},
		"debug":      map[string]interface{}{},
	}

	jsonData, err := json.Marshal(requestBody)
	if err != nil {
		fmt.Printf("Failed to marshal JSON: %v\n", err)
		return
	}

	// 创建 HTTP POST 请求
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Printf("Failed to create request: %v\n", err)
		return
	}

	// 设置请求头
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	// 发送请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Printf("Failed to send request: %v\n", err)
		return
	}
	defer resp.Body.Close()

	// 读取响应
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Failed to read response: %v\n", err)
		return
	}

	// 处理响应
	if resp.StatusCode == http.StatusOK {
		fmt.Println("Request successful:")
		fmt.Println(string(body))
	} else {
		fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
		fmt.Println(string(body))
	}
}

Impact of releasing a new version on API calls

After you release a new version of an application, the APP_ID always points to the latest released version. Requests in progress at release time are not interrupted and complete normally based on the pre-release configuration; after the release is complete, new requests initiated through the same APP_ID use the new version's configuration (including the prompt, model, tools, and so on).

The API does not support specifying a historical version to call through parameters. The request body contains only the input and parameters fields, and does not provide a version number or historical version parameter.

If the session_id of a multi-turn conversation continues to be used after a new version is released, context understanding deviations or tool call exceptions may occur, because the historical context of that session was generated based on the pre-release configuration. We recommend ending active multi-turn conversations before releasing major changes, or starting a new session with a new session_id after the release.

To restore the pre-release configuration, perform a version rollback on the application details page in the Alibaba Cloud Model Studio console:

  1. Click Version management.
  2. Select the historical version to restore.
  3. Click Overwrite current draft.
  4. Click Release to make the rollback take effect.

To reduce the impact on live calls, we recommend releasing major changes during off-peak business hours; if you need to provide multiple versions of capabilities externally at the same time, you can manage versions by creating multiple applications (using different APP_IDs).

Streaming output

Streaming output is implemented through stream. Related documents: Call an agent application - streaming output, Call a workflow application - streaming output.

Python

Request example
import os
import dashscope
from dashscope import DashScopeError

client = dashscope.Client(
            # 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
            api_key=os.getenv("DASHSCOPE_API_KEY"))
try:
    stream = client.apps.completions.create(
                app_id='APP_ID',
                prompt='你是谁?',
                stream=True,  # 流式输出
                incremental_output=True)  # 增量输出

    for partial in stream:
        print(f'{partial.text}\n')  # 处理只输出文本text
except DashScopeError as e:
    print(f'request_id={e.request_id}')
    print(f'code={e.code}')
    print(f'message={e.message}')
    print(f'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')

Java

Request example
// 建议dashscope SDK的版本 >= 2.15.0
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import io.reactivex.Flowable;// 流式输出
// 智能体应用调用实现流式输出结果

public class Main {
    public static void streamCall() throws NoApiKeyException, InputRequiredException {
        ApplicationParam param = ApplicationParam.builder()
                // 若没有配置环境变量,可用百炼API Key将下行替换为:.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // 替换为实际的应用 ID
                .appId("APP_ID")
                .prompt("你是谁?")
                // 增量输出
                .incrementalOutput(true)
                .build();
        Application application = new Application();
        // .streamCall():流式输出内容
        Flowable<ApplicationResult> result = application.streamCall(param);
        result.blockingForEach(data -> {
            System.out.printf("%s\n",
                    data.getOutput().getText());
        });
    }
    public static void main(String[] args) {
        try {
            streamCall();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.printf("Exception: %s", e.getMessage());
            System.out.println("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}

HTTP

curl

Request example
curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--header 'X-DashScope-SSE: enable' \
--data '{
    "input": {
        "prompt": "你是谁?"

    },
    "parameters":  {
        "incremental_output":true
    },
    "debug": {}
}'

Replace APP_ID with the actual application ID.

PHP

Request example
<?php

// 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // 替换为实际的应用 ID

$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";

// 构造请求数据
$data = [
    "input" => [
        'prompt' => '你是谁?'],
    "parameters" => [
        'incremental_output' => true]];// 增量输出
// 将数据编码为 JSON
$dataString = json_encode($data);

// 检查 json_encode 是否成功
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON encoding failed with error: " . json_last_error_msg());
}

// 初始化 cURL 对话
$ch = curl_init($url);

// 设置 cURL 选项
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); // 不返回传输的数据
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($ch, $string) {
    echo $string; // 处理流式数据
    return strlen($string);
});
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $api_key,
    'X-DashScope-SSE: enable' // 流式输出
]);

// 执行请求
$response = curl_exec($ch);

// 检查 cURL 执行是否成功
if ($response === false) {
    die("cURL Error: " . curl_error($ch));
}

// 获取 HTTP 状态码
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 关闭 cURL 对话
curl_close($ch);

if ($status_code != 200) {
    echo "HTTP Status Code: $status_code\n";
    echo "Request Failed.\n";
}
?>

Node.js

You must install the following dependencies:
npm install axios
Request example

1. Output the complete response

const axios = require('axios');

async function callDashScope() {
    //若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';// 替换为实际的应用 ID

    const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;

    const data = {
        input: {
            prompt: "你是谁?"
        },
        parameters: {
            'incremental_output' : true // 增量输出
        },
        debug: {}
    };

    try {
        console.log("Sending request to DashScope API...");

        const response = await axios.post(url, data, {
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json',
                'X-DashScope-SSE': 'enable' // 流式输出
            },
            responseType: 'stream' // 用于处理流式响应
        });

        if (response.status === 200) {
            // 处理流式响应
            response.data.on('data', (chunk) => {
                console.log(`Received chunk: ${chunk.toString()}`);
            });
        } else {
            console.log("Request failed:");
            if (response.data.request_id) {
                console.log(`request_id=${response.data.request_id}`);
            }
            console.log(`code=${response.status}`);
            if (response.data.message) {
                console.log(`message=${response.data.message}`);
            } else {
                console.log('message=Unknown error');
            }
        }
    } catch (error) {
        console.error(`Error calling DashScope: ${error.message}`);
        if (error.response) {
            console.error(`Response status: ${error.response.status}`);
            console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
        }
    }
}

callDashScope();

You can expand the collapsible panel to view the specific content:

2. Output only the content of the text field

const axios = require('axios');
const { Transform } = require('stream');

async function callDashScope() {
    //若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID'; // 替换为实际的应用 ID

    const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;

    const data = {
        input: { prompt: "你是谁?" },
        parameters: { incremental_output: true }, // 增量输出
        debug: {}
    };

    try {
        console.log("Sending request to DashScope API...");

        const response = await axios.post(url, data, {
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json',
                'X-DashScope-SSE': 'enable' // 流式输出
            },
            responseType: 'stream' // 用于处理流式响应
        });

        if (response.status === 200) {
            // // 处理流式响应 SSE协议解析转换流
            const sseTransformer = new Transform({
                transform(chunk, encoding, callback) {
                    this.buffer += chunk.toString();

                    // 按SSE事件分割(两个换行符)
                    const events = this.buffer.split(/\n\n/);
                    this.buffer = events.pop() || ''; // 保留未完成部分

                    events.forEach(eventData => {
                        const lines = eventData.split('\n');
                        let textContent = '';

                        // 解析事件内容
                        lines.forEach(line => {
                            if (line.startsWith('data:')) {
                                try {
                                    const jsonData = JSON.parse(line.slice(5).trim());
                                    if (jsonData.output?.text) {
                                        textContent = jsonData.output.text;
                                    }
                                } catch(e) {
                                    console.error('JSON解析错误:', e.message);
                                }
                            }
                        });

                        if (textContent) {
                            // 添加换行符并推送
                            this.push(textContent + '\n');
                        }
                    });

                    callback();
                },
                flush(callback) {
                    if (this.buffer) {
                        this.push(this.buffer + '\n');
                    }
                    callback();
                }
            });
            sseTransformer.buffer = '';

            // 管道处理
            response.data
                .pipe(sseTransformer)
                .on('data', (textWithNewline) => {
                    process.stdout.write(textWithNewline); // 自动换行输出
                })
                .on('end', () => console.log(""))
                .on('error', err => console.error("管道错误:", err));

        } else {
            console.log("请求失败,状态码:", response.status);
            response.data.on('data', chunk => console.log(chunk.toString()));
        }
    } catch (error) {
        console.error(`API调用失败: ${error.message}`);
        if (error.response) {
            console.error(`状态码: ${error.response.status}`);
            error.response.data.on('data', chunk => console.log(chunk.toString()));
        }
    }
}

callDashScope();

C#

Request example
using System.Net;
using System.Text;

class Program
{
    static async Task Main(string[] args)
    {
        //若没有配置环境变量,可用百炼API Key将下行替换为:apiKey="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
        string appId = "APP_ID"; // 替换为实际的应用ID
        string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
            client.DefaultRequestHeaders.Add("X-DashScope-SSE", "enable");

            string jsonContent = @"{
                ""input"": {
                    ""prompt"": ""你是谁""
                },
                ""parameters"": {""incremental_output"": true},
                ""debug"": {}
            }";

            HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

            Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
            try
            {
                var request = new HttpRequestMessage(HttpMethod.Post, url);
                request.Content = content;

                HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);

                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine("Request successful:");
                    Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
                    using (var stream = await response.Content.ReadAsStreamAsync())
                    using (var reader = new StreamReader(stream))
                    {
                        string? line; // 声明为可空字符串
                        while ((line = await reader.ReadLineAsync()) != null)
                        {
                            if (line.StartsWith("data:"))
                            {
                                string data = line.Substring(5).Trim();
                                Console.WriteLine(data);
                                Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
                            }
                        }
                    }
                }
                else
                {
                    Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error calling DashScope: {ex.Message}");
            }
        }
    }
}

Go

Request example
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"strings"
	"time"
)

func main() {
	// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // 替换为实际的应用 ID

	if apiKey == "" {
		fmt.Println("请确保设置了DASHSCOPE_API_KEY。")
		return
	}

	url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)

	// 创建请求体,其中incremental_output为是否开启流式响应
	requestBody := map[string]interface{}{
		"input": map[string]string{
			"prompt": "你是谁?",
		},
		"parameters": map[string]interface{}{
			"incremental_output": true,
		},
		"debug": map[string]interface{}{},
	}

	jsonData, err := json.Marshal(requestBody)
	if err != nil {
		fmt.Printf("Failed to marshal JSON: %v\n", err)
		return
	}

	// 创建 HTTP POST 请求
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Printf("Failed to create request: %v\n", err)
		return
	}

	// 设置请求头,其中X-DashScope-SSE设置为enable,表示开启流式响应
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("X-DashScope-SSE", "enable")

	// 发送请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Printf("Failed to send request: %v\n", err)
		return
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
		body, _ := io.ReadAll(resp.Body)
		fmt.Println(string(body))
		return
	}

	// 处理流式响应
	reader := io.Reader(resp.Body)
	buf := make([]byte, 1024)
	for {
		n, err := reader.Read(buf)
		if n > 0 {
			data := string(buf[:n])
			lines := strings.Split(data, "\n")
			for _, line := range lines {
				line = strings.TrimSpace(line)
				if len(line) >= 5 && line[:5] == "data:" {
					timestamp := time.Now().Format("2006-01-02 15:04:05.000")
					fmt.Printf("%s: %s\n", timestamp, line[5:])
				} else if len(line) > 0 {
					fmt.Println(line)
				}
			}
		}
		if err != nil {
			if err == io.EOF {
				break
			}
			fmt.Printf("Error reading response: %v\n", err)
			break
		}
	}
}

Retrieve knowledge base

When you call an agent application, you can use rag_options to implement knowledge base retrieval. Related document: Retrieve a knowledge base.

Python

Request example
import os
import dashscope
# 需要 dashscope 2.0.1 及以上版本
from dashscope import DashScopeError

client = dashscope.Client(
    # 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
    api_key=os.getenv("DASHSCOPE_API_KEY"))
try:
    response = client.apps.completions.create(
        app_id='APP_ID',  # 应用ID替换APP_ID
        prompt='请帮我推荐一款3000元以下的手机',
        rag_options={
            "pipeline_ids": ["PIPELINE_ID1","PIPELINE_ID2"],  # 替换为实际的知识库ID,逗号隔开多个
        }
    )
    print('%s\n' % (response.text))  # 处理只输出文本text
    # print('%s\n' % (response.usage))
except DashScopeError as e:
    print(f'request_id={e.request_id}')
    print(f'code={e.code}')
    print(f'message={e.message}')
    print(f'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')

Java

Request example
// 建议dashscope SDK 的版本 >= 2.16.8;
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import java.util.Arrays;

public class Main {
    public static void streamCall() throws NoApiKeyException, InputRequiredException {
        ApplicationParam param = ApplicationParam.builder()
                // 若没有配置环境变量,可用百炼API Key将下行替换为:.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .appId("APP_ID") // 替换为实际的应用ID
                .prompt("请帮我推荐一款3000元左右的手机")
                .ragOptions(RagOptions.builder()
                        // 替换为实际指定的知识库ID,逗号隔开多个
                        .pipelineIds(Arrays.asList("PIPELINES_ID1", "PIPELINES_ID2"))
                        .build())
                .build();

        Application application = new Application();
        ApplicationResult result = application.call(param);
        System.out.printf("%s\n",
                result.getOutput().getText());// 处理只输出文本text
    }

    public static void main(String[] args) {
        try {
            streamCall();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.printf("Exception: %s", e.getMessage());
            System.out.println("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}

HTTP

curl

Request example
curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "prompt": "请帮我推荐一款3000元以下的手机"
    },
    "parameters":  {
                    "rag_options" : {
                    "pipeline_ids":["PIPELINE_ID1"]}
    },
    "debug": {}
}'

Replace APP_ID with the actual application ID, and replace PIPELINE_ID1 with the specified knowledge base ID.

PHP

Request example
<?php
# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // 替换为实际的应用 ID

$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";

// 构造请求数据
$data = [
    "input" => [
        'prompt' => '请帮我推荐一款3000元以下的手机'
    ],
    "parameters" => [
        'rag_options' => [
            'pipeline_ids' => ['PIPELINE_ID1','PIPELINE_ID2']//替换为指定的知识库ID,逗号隔开多个
        ]
    ]
];
// 将数据编码为 JSON
$dataString = json_encode($data);

// 检查 json_encode 是否成功
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON encoding failed with error: " . json_last_error_msg());
}

// 初始化 cURL 对话
$ch = curl_init($url);

// 设置 cURL 选项
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $api_key
]);

// 执行请求
$response = curl_exec($ch);

// 检查 cURL 执行是否成功
if ($response === false) {
    die("cURL Error: " . curl_error($ch));
}

// 获取 HTTP 状态码
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 关闭 cURL 对话
curl_close($ch);
// 解码响应数据
$response_data = json_decode($response, true);
// 处理响应
if ($status_code == 200) {
    if (isset($response_data['output']['text'])) {
        echo "{$response_data['output']['text']}\n";
    } else {
        echo "No text in response.\n";
    }
}else {
    if (isset($response_data['request_id'])) {
        echo "request_id={$response_data['request_id']}\n";}
    echo "code={$status_code}\n";
    if (isset($response_data['message'])) {
        echo "message={$response_data['message']}\n";}
    else {
        echo "message=Unknown error\n";}
}
?>

Node.js

You must install the following dependencies:
npm install axios
Request example
const axios = require('axios');
async function callDashScope() {
    // 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';//替换为实际的应用 ID

    const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;

    const data = {
        input: {
            prompt: "请帮我推荐一款3000元以下的手机"
        },
        parameters: {
            rag_options:{
                pipeline_ids:['PIPELINE_ID1','PIPELINE_ID2']  // 替换为指定的知识库ID,多个请用逗号隔开
            }
        },
        debug: {}
    };

    try {
        const response = await axios.post(url, data, {
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            }
        });

        if (response.status === 200) {
            console.log(`${response.data.output.text}`);
        } else {
            console.log(`request_id=${response.headers['request_id']}`);
            console.log(`code=${response.status}`);
            console.log(`message=${response.data.message}`);
        }
    } catch (error) {
        console.error(`Error calling DashScope: ${error.message}`);
        if (error.response) {
            console.error(`Response status: ${error.response.status}`);
            console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
        }
    }
}

callDashScope();

C#

Request example
using System.Text;

class Program
{
    static async Task Main(string[] args)
    {
        // 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
        string appId = "APP_ID";// 替换为实际的应用ID
        // PIPELINE_ID1替换为指定的知识库ID
        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("请确保设置了 DASHSCOPE_API_KEY。");
            return;
        }

        string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
            string jsonContent = $@"{{
                ""input"": {{
                    ""prompt"": ""请帮我推荐一款3000元以下的手机""
                }},
                ""parameters"": {{
                    ""rag_options"" : {{
                        ""pipeline_ids"":[""PIPELINE_ID1""]
                    }}
                }},
                ""debug"": {{}}
            }}";

            HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

            try
            {
                HttpResponseMessage response = await client.PostAsync(url, content);

                if (response.IsSuccessStatusCode)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
                else
                {
                    Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error calling DashScope: {ex.Message}");
            }
        }
    }
}

Go

Request example
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
)

func main() {
	// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // 替换为实际的应用 ID

	if apiKey == "" {
		fmt.Println("请确保设置了DASHSCOPE_API_KEY。")
		return
	}

	url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)

	// 创建请求体
	requestBody := map[string]interface{}{
		"input": map[string]string{
			"prompt": "请帮我推荐一款3000元以下的手机",
		},
		"parameters": map[string]interface{}{
			"rag_options": map[string]interface{}{
				"pipeline_ids": []string{"PIPELINE_ID1"}, // 替换为指定的知识库ID
			},
		},
		"debug": map[string]interface{}{},
	}

	jsonData, err := json.Marshal(requestBody)
	if err != nil {
		fmt.Printf("Failed to marshal JSON: %v\n", err)
		return
	}

	// 创建 HTTP POST 请求
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Printf("Failed to create request: %v\n", err)
		return
	}

	// 设置请求头
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	// 发送请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Printf("Failed to send request: %v\n", err)
		return
	}
	defer resp.Body.Close()

	// 读取响应
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Failed to read response: %v\n", err)
		return
	}

	// 处理响应
	if resp.StatusCode == http.StatusOK {
		fmt.Println("Request successful:")
		fmt.Println(string(body))
	} else {
		fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
		fmt.Println(string(body))
	}
}

To view retrieval process information: add has_thoughts to your code and set it to True when you make the call. The retrieval process information will then be returned in the thoughts field of the response.

Long-term memory

When you call an agent application, specify memory_id to enable long-term memory. Related document: Long-term memory.

Python

Request example (generate memory content)
# 需要 dashscope 2.0.1 及以上版本
import os
import dashscope
from dashscope import DashScopeError

client = dashscope.Client(
           # 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
            api_key=os.getenv("DASHSCOPE_API_KEY"))
try:
    response = client.apps.completions.create(
                app_id='APP_ID',  # 请输入实际的应用 ID
                prompt='用户饮食偏好:面食',
                memory_id='MEMORY_ID')  # 请输入实际的记忆体 ID

    print('%s\n' % (response.text))  # 处理只输出text
    # print('%s\n' % (response.usage))
except DashScopeError as e:
    print(f'request_id={e.request_id}')
    print(f'code={e.code}')
    print(f'message={e.message}')
    print(f'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
Request example (call again)
# 需要 dashscope 2.0.1 及以上版本
import os
import dashscope
from dashscope import DashScopeError

client = dashscope.Client(
           # 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
            api_key=os.getenv("DASHSCOPE_API_KEY"))
try:
    response = client.apps.completions.create(
                app_id='APP_ID',  # 请输入实际的应用 ID
                prompt='美食推荐',
                memory_id='MEMORY_ID')  # 请输入实际的记忆体 ID

    print('%s\n' % (response.text))  # 处理只输出text
    # print('%s\n' % (response.usage))
except DashScopeError as e:
    print(f'request_id={e.request_id}')
    print(f'code={e.code}')
    print(f'message={e.message}')
    print(f'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')

Java

Request example (generate memory content)
// DashScope SDK版本不低于2.17.0
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;

public class Main {
    public static void callWithMemory() throws NoApiKeyException, InputRequiredException {
        ApplicationParam param = ApplicationParam.builder()
                // 若没有配置环境变量,可用百炼API Key将下行替换为:.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .appId("APP_ID") // 替换为实际的应用 ID
                .prompt("用户饮食偏好:面食")
                .memoryId("MEMORY_ID") // 替换为实际的记忆体 ID
                .build();

        Application application = new Application();
        ApplicationResult result = application.call(param);

        System.out.printf("%s\n",
                result.getOutput().getText()); // 处理只输出文本text
    }
    public static void main(String[] args) {
        try {
            callWithMemory();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.printf("Exception: %s", e.getMessage());
            System.out.println("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}
Request example (call again)
// DashScope SDK版本不低于2.17.0
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;

public class Main {
    public static void callWithMemory() throws NoApiKeyException, InputRequiredException {
        ApplicationParam param = ApplicationParam.builder()
                // 若没有配置环境变量,可用百炼API Key将下行替换为:.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .appId("APP_ID") // 替换为实际的应用 ID
                .prompt("美食推荐")
                .memoryId("MEMORY_ID") // 替换为实际的记忆体 ID
                .build();

        Application application = new Application();
        ApplicationResult result = application.call(param);

        System.out.printf("text: %s\n",
                result.getOutput().getText()); // 处理只输出文本text
    }
    public static void main(String[] args) {
        try {
            callWithMemory();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.printf("Exception: %s", e.getMessage());
            System.out.println("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}

HTTP

curl

Request example (generate memory content)
curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "prompt": "用户饮食偏好:面食",
        "memory_id": "MEMORY_ID"
    },
    "parameters":  {},
    "debug": {}
}'
Request example (call again)
curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "prompt": "美食推荐",
        "memory_id": "MEMORY_ID"
    },
    "parameters":  {},
    "debug": {}
}'

Replace APP_ID with the actual application ID.

PHP

Request example (generate memory content)
<?php
# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // 替换为实际的应用 ID
$memory_id = 'MEMORY_ID'; // 替换为实际的记忆体 ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/{$application_id}/completion";

// 构造请求数据
$data = [
    "input" => [
        'prompt' => '用户饮食偏好:面食',
        'memory_id' => $memory_id
    ]
];
// 将数据编码为 JSON
$dataString = json_encode($data);

// 检查 json_encode 是否成功
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON encoding failed with error: " . json_last_error_msg());
}

// 初始化 cURL 对话
$ch = curl_init($url);

// 设置 cURL 选项
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $api_key
]);

// 执行请求
$response = curl_exec($ch);

// 检查 cURL 执行是否成功
if ($response === false) {
    die("cURL Error: " . curl_error($ch));
}

// 获取 HTTP 状态码
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 关闭 cURL 对话
curl_close($ch);
// 解码响应数据
$response_data = json_decode($response, true);
// 处理响应
if ($status_code == 200) {
    if (isset($response_data['output']['text'])) {
        echo "{$response_data['output']['text']}\n";
    } else {
        echo "No text in response.\n";
    }
}else {
    if (isset($response_data['request_id'])) {
        echo "request_id={$response_data['request_id']}\n";}
    echo "code={$status_code}\n";
    if (isset($response_data['message'])) {
        echo "message={$response_data['message']}\n";}
    else {
        echo "message=Unknown error\n";}
}
?>
Request example (call again)
<?php
# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // 替换为实际的应用 ID
$memory_id = 'MEMORY_ID'; // 替换为实际的记忆体 ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/{$application_id}/completion";

// 构造请求数据
$data = [
    "input" => [
        'prompt' => '美食推荐',
        'memory_id' => $memory_id
    ]
];
// 将数据编码为 JSON
$dataString = json_encode($data);

// 检查 json_encode 是否成功
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON encoding failed with error: " . json_last_error_msg());
}

// 初始化 cURL 对话
$ch = curl_init($url);

// 设置 cURL 选项
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $api_key
]);

// 执行请求
$response = curl_exec($ch);

// 检查 cURL 执行是否成功
if ($response === false) {
    die("cURL Error: " . curl_error($ch));
}

// 获取 HTTP 状态码
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 关闭 cURL 对话
curl_close($ch);
// 解码响应数据
$response_data = json_decode($response, true);
// 处理响应
if ($status_code == 200) {
    if (isset($response_data['output']['text'])) {
        echo "{$response_data['output']['text']}\n";
    } else {
        echo "No text in response.\n";
    }
}else {
    if (isset($response_data['request_id'])) {
        echo "request_id={$response_data['request_id']}\n";}
    echo "code={$status_code}\n";
    if (isset($response_data['message'])) {
        echo "message={$response_data['message']}\n";}
    else {
        echo "message=Unknown error\n";}
}
?>

Node.js

You must install the following dependencies:
npm install axios
Request example (generate memory content)
const axios = require('axios');

async function callDashScope() {
    //若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';// 替换为实际的应用 ID
    const memoryId = 'MEMORY_ID';// 替换为实际的memory_id

    const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;

    const data = {
        input: {
            prompt: "用户饮食偏好:面食",
            memory_id: memoryId
        },
        parameters: {},
        debug: {}
    };

    try {
        console.log("Sending request to DashScope API...");

        const response = await axios.post(url, data, {
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            }
        });

        if (response.status === 200) {
            if (response.data.output && response.data.output.text) {
                console.log(`${response.data.output.text}`);
            }
        } else {
            console.log("Request failed:");
            if (response.data.request_id) {
                console.log(`request_id=${response.data.request_id}`);
            }
            console.log(`code=${response.status}`);
            if (response.data.message) {
                console.log(`message=${response.data.message}`);
            } else {
                console.log('message=Unknown error');
            }
        }
    } catch (error) {
        console.error(`Error calling DashScope: ${error.message}`);
        if (error.response) {
            console.error(`Response status: ${error.response.status}`);
            console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
        }
    }
}

callDashScope();
Request example (call again)
const axios = require('axios');

async function callDashScope() {
    //若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';// 替换为实际的应用 ID
    const memoryId = 'MEMORY_ID';// 替换为实际的memory_id

    const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;

    const data = {
        input: {
            prompt: "美食推荐",
            memory_id: memoryId
        },
        parameters: {},
        debug: {}
    };

    try {
        console.log("Sending request to DashScope API...");

        const response = await axios.post(url, data, {
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            }
        });

        if (response.status === 200) {
            if (response.data.output && response.data.output.text) {
                console.log(`${response.data.output.text}`);
            }
        } else {
            console.log("Request failed:");
            if (response.data.request_id) {
                console.log(`request_id=${response.data.request_id}`);
            }
            console.log(`code=${response.status}`);
            if (response.data.message) {
                console.log(`message=${response.data.message}`);
            } else {
                console.log('message=Unknown error');
            }
        }
    } catch (error) {
        console.error(`Error calling DashScope: ${error.message}`);
        if (error.response) {
            console.error(`Response status: ${error.response.status}`);
            console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
        }
    }
}

callDashScope();

C#

Request example (generate memory content)
using System.Text;

class Program
{
    static async Task Main(string[] args)
    {
        // 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
        string appId = "APP_ID";// 替换为实际的应用ID
        string memoryId = "MEMORY_ID";//替换为实际的memory_id
        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("请确保设置了 DASHSCOPE_API_KEY。");
            return;
        }

        string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
            string jsonContent = $@"{{
                ""input"": {{
                    ""prompt"": ""用户饮食偏好:面食"",
                    ""memory_id"":""{memoryId}""
                }},
                ""parameters"": {{}},
                ""debug"": {{}}
            }}";

            HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

            try
            {
                HttpResponseMessage response = await client.PostAsync(url, content);

                if (response.IsSuccessStatusCode)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
                else
                {
                    Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error calling DashScope: {ex.Message}");
            }
        }
    }
}
Request example (call again)
using System.Text;

class Program
{
    static async Task Main(string[] args)
    {
        // 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
        string appId = "APP_ID";// 替换为实际的应用ID
        string memoryId = "MEMORY_ID";//替换为实际的memory_id
        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("请确保设置了 DASHSCOPE_API_KEY。");
            return;
        }

        string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
            string jsonContent = $@"{{
                ""input"": {{
                    ""prompt"": ""美食推荐"",
                    ""memory_id"":""{memoryId}""
                }},
                ""parameters"": {{}},
                ""debug"": {{}}
            }}";

            HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

            try
            {
                HttpResponseMessage response = await client.PostAsync(url, content);

                if (response.IsSuccessStatusCode)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
                else
                {
                    Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error calling DashScope: {ex.Message}");
            }
        }
    }
}

Go

Request example (generate memory content)
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
)

func main() {
	// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // 替换为实际的应用 ID

	if apiKey == "" {
		fmt.Println("请确保设置了DASHSCOPE_API_KEY。")
		return
	}

	url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)

	// 创建请求体
	requestBody := map[string]interface{}{
		"input": map[string]string{
			"prompt":    "用户饮食偏好:面食",
			"memory_id": "MEMORY_ID", // 替换为实际的记忆体 ID
		},
		"parameters": map[string]interface{}{},
		"debug":      map[string]interface{}{},
	}

	jsonData, err := json.Marshal(requestBody)
	if err != nil {
		fmt.Printf("Failed to marshal JSON: %v\n", err)
		return
	}

	// 创建 HTTP POST 请求
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Printf("Failed to create request: %v\n", err)
		return
	}

	// 设置请求头
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	// 发送请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Printf("Failed to send request: %v\n", err)
		return
	}
	defer resp.Body.Close()

	// 读取响应
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Failed to read response: %v\n", err)
		return
	}

	// 处理响应
	if resp.StatusCode == http.StatusOK {
		fmt.Println("Request successful:")
		fmt.Println(string(body))
	} else {
		fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
		fmt.Println(string(body))
	}
}
Request example (call again)
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
)

func main() {
	// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // 替换为实际的应用 ID

	if apiKey == "" {
		fmt.Println("请确保设置了DASHSCOPE_API_KEY。")
		return
	}

	url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)

	// 创建请求体
	requestBody := map[string]interface{}{
		"input": map[string]string{
			"prompt":    "美食推荐",
			"memory_id": "MEMORY_ID", // 替换为实际的记忆体 ID
		},
		"parameters": map[string]interface{}{},
		"debug":      map[string]interface{}{},
	}

	jsonData, err := json.Marshal(requestBody)
	if err != nil {
		fmt.Printf("Failed to marshal JSON: %v\n", err)
		return
	}

	// 创建 HTTP POST 请求
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Printf("Failed to create request: %v\n", err)
		return
	}

	// 设置请求头
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	// 发送请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Printf("Failed to send request: %v\n", err)
		return
	}
	defer resp.Body.Close()

	// 读取响应
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Failed to read response: %v\n", err)
		return
	}

	// 处理响应
	if resp.StatusCode == http.StatusOK {
		fmt.Println("Request successful:")
		fmt.Println(string(body))
	} else {
		fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
		fmt.Println(string(body))
	}
}

Upload files

When calling an agent application, specify session_file_ids /file_list to enable the file upload feature. For more information, see File Q&A.

Python

Request example
import os
import dashscope
# 需要 dashscope 2.0.1 及以上版本
from dashscope import DashScopeError

client = dashscope.Client(
    # 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
    api_key=os.getenv("DASHSCOPE_API_KEY"))
try:
    response = client.apps.completions.create(
        app_id='APP_ID',  # 应用ID替换APP_ID
        prompt='请根据以下文件帮我推荐一款3000元以下的手机',
        rag_options={
            "session_file_ids": ["Session_File_ID1"],  # Session_File_ID1 替换为实际的临时文件ID,逗号隔开多个
        }
    )
    print('%s\n' % (response.text))  # 处理只输出文本text
    # print('%s\n' % (response.usage))
except DashScopeError as e:
    print(f'request_id={e.request_id}')
    print(f'code={e.code}')
    print(f'message={e.message}')
    print(f'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')

Java

Request example
// 建议dashscope SDK 的版本 >= 2.17.0;
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;

import java.util.Arrays;

public class Main {
    public static void appCall() throws NoApiKeyException, InputRequiredException {
        ApplicationParam param = ApplicationParam.builder()
                // 若没有配置环境变量,可用百炼API Key将下行替换为:.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .appId("APP_ID") // 替换为实际的应用ID
                .prompt("请根据以下文件帮我推荐一款3000元左右的手机")
                .ragOptions(RagOptions.builder()
                        .sessionFileIds(Arrays.asList("Session_File_ID1", "Session_File_ID2"))  // 替换为实际指定的临时文件 ID,逗号隔开多个
                        .build())
                .build();

        Application application = new Application();
        ApplicationResult result = application.call(param);
        System.out.printf("%s\n",
                result.getOutput().getText());// 处理只输出文本text
    }

    public static void main(String[] args) {
        try {
            appCall();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.printf("Exception: %s", e.getMessage());
            System.out.println("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}

HTTP

curl

Request example
curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "prompt": "请根据以下文件帮我推荐一款3000元以下的手机"
    },
    "parameters":  {
                    "rag_options" : {
                    "session_file_ids":["Session_File_ID1"]}
    },
    "debug": {}
}'

PHP

Request example
<?php
# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // 替换为实际的应用 ID

$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";

// 构造请求数据
$data = [
    "input" => [
        'prompt' => '请根据以下文件帮我推荐一款3000元以下的手机'
    ],
    "parameters" => [
        'rag_options' => [
            'session_file_ids' => ['Session_File_ID1']//替换为指定的临时文件ID,逗号隔开多个
        ]
    ]
];
// 将数据编码为 JSON
$dataString = json_encode($data);

// 检查 json_encode 是否成功
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON encoding failed with error: " . json_last_error_msg());
}

// 初始化 cURL 对话
$ch = curl_init($url);

// 设置 cURL 选项
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $api_key
]);

// 执行请求
$response = curl_exec($ch);

// 检查 cURL 执行是否成功
if ($response === false) {
    die("cURL Error: " . curl_error($ch));
}

// 获取 HTTP 状态码
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 关闭 cURL 对话
curl_close($ch);
// 解码响应数据
$response_data = json_decode($response, true);
// 处理响应
if ($status_code == 200) {
    if (isset($response_data['output']['text'])) {
        echo "{$response_data['output']['text']}\n";
    } else {
        echo "No text in response.\n";
    }
}else {
    if (isset($response_data['request_id'])) {
        echo "request_id={$response_data['request_id']}\n";}
    echo "code={$status_code}\n";
    if (isset($response_data['message'])) {
        echo "message={$response_data['message']}\n";}
    else {
        echo "message=Unknown error\n";}
}
?>

Node.js

You must install the following dependencies:
npm install axios
Request example
const axios = require('axios');
async function callDashScope() {
    // 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';//替换为实际的应用 ID

    const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;

    const data = {
        input: {
            prompt: "请根据以下文件帮我推荐一款3000元以下的手机"
        },
        parameters: {
            rag_options:{
                session_file_ids:['Session_File_ID1']  // 替换为指定的临时文件 ID,多个请用逗号隔开
            }
        },
        debug: {}
    };

    try {
        const response = await axios.post(url, data, {
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            }
        });

        if (response.status === 200) {
            console.log(`${response.data.output.text}`);
        } else {
            console.log(`request_id=${response.headers['request_id']}`);
            console.log(`code=${response.status}`);
            console.log(`message=${response.data.message}`);
        }
    } catch (error) {
        console.error(`Error calling DashScope: ${error.message}`);
        if (error.response) {
            console.error(`Response status: ${error.response.status}`);
            console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
        }
    }
}

callDashScope();

C#

Request example
using System.Text;

class Program
{
    static async Task Main(string[] args)
    {
        // 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
        string appId = "APP_ID";// 替换为实际的应用ID
        // Session_File_ID1替换为指定的临时文件ID
        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("请确保设置了 DASHSCOPE_API_KEY。");
            return;
        }

        string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
            string jsonContent = $@"{{
                ""input"": {{
                    ""prompt"": ""请根据以下文件帮我推荐一款3000元以下的手机""
                }},
                ""parameters"": {{
                    ""rag_options"" : {{
                        ""session_file_ids"":[""Session_File_ID1""]
                    }}
                }},
                ""debug"": {{}}
            }}";

            HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

            try
            {
                HttpResponseMessage response = await client.PostAsync(url, content);

                if (response.IsSuccessStatusCode)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
                else
                {
                    Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error calling DashScope: {ex.Message}");
            }
        }
    }
}

Go

Request example
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
)

func main() {
	// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // 替换为实际的应用 ID

	if apiKey == "" {
		fmt.Println("请确保设置了DASHSCOPE_API_KEY。")
		return
	}

	url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)

	// 创建请求体
	requestBody := map[string]interface{}{
		"input": map[string]string{
			"prompt": "请根据以下文件帮我推荐一款3000元以下的手机",
		},
		"parameters": map[string]interface{}{
			"rag_options": map[string]interface{}{
				"session_file_ids": []string{"Session_File_ID1"}, // 替换为实际的临时文件
			},
		},
		"debug": map[string]interface{}{},
	}

	jsonData, err := json.Marshal(requestBody)
	if err != nil {
		fmt.Printf("Failed to marshal JSON: %v\n", err)
		return
	}

	// 创建 HTTP POST 请求
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Printf("Failed to create request: %v\n", err)
		return
	}

	// 设置请求头
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	// 发送请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Printf("Failed to send request: %v\n", err)
		return
	}
	defer resp.Body.Close()

	// 读取响应
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Failed to read response: %v\n", err)
		return
	}

	// 处理响应
	if resp.StatusCode == http.StatusOK {
		fmt.Println("Request successful:")
		fmt.Println(string(body))
	} else {
		fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
		fmt.Println(string(body))
	}
}

Visual understanding

Enable the visual understanding feature by passing an image URL or Data URL (Base64-encoded) through the image_list parameter.

Application configuration: The application must use an image and video understanding model. Related document: File Q&A.

NoteBase64 encoding of local images is supported. After the image is encoded into a Base64 string, build a Data URL in the data:[MIME_type];base64,{base64_image} format and pass it in. MIME_type must match the image format. Common formats: PNG uses image/png, JPEG uses image/jpeg, and WebP uses image/webp.

Python

URL request example
import os
import dashscope
# 需要 dashscope 2.0.1 及以上版本
from dashscope import DashScopeError

client = dashscope.Client(
    # 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
    api_key=os.getenv("DASHSCOPE_API_KEY"))
try:
    response = client.apps.completions.create(
        app_id='APP_ID',  # 应用ID替换APP_ID
        prompt='这是什么',
        image_list=['https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg'],
    )
    print('%s\n' % (response.text))  # 处理只输出文本text
    # print('%s\n' % (response.usage))
except DashScopeError as e:
    print(f'request_id={e.request_id}')
    print(f'code={e.code}')
    print(f'message={e.message}')
    print(f'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
Base64 encoding example
import os
import base64
import dashscope
from dashscope import DashScopeError

client = dashscope.Client(api_key=os.getenv("DASHSCOPE_API_KEY"))

# 将本地图像编码为 Base64 字符串
def encode_image(image_path):
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode("utf-8")

# 编码本地图像
base64_image = encode_image("/path/to/your/image.jpeg")  # 替换为实际图像路径

# 构建 Data URL(注意:MIME type 需与图像格式匹配)
data_url = f"data:image/jpeg;base64,{base64_image}"

# 调用应用 API
try:
    response = client.apps.completions.create(
        app_id='APP_ID',  # 应用ID替换APP_ID
        prompt='这张图片里有什么?',
        image_list=[data_url],  # 使用 Data URL
    )
    print('%s\n' % (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'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')

Java

URL request example
// 建议dashscope SDK 的版本 >= 2.19.0;
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import java.util.Arrays;

public class Main {
    public static void appCall() throws NoApiKeyException, InputRequiredException {
        ApplicationParam param = ApplicationParam.builder()
                // 若没有配置环境变量,可用百炼API Key将下行替换为:.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .appId("APP_ID") // 替换为实际的应用ID
                .prompt("这是什么?")
                .images(Arrays.asList("https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"))
                .build();

        Application application = new Application();
        ApplicationResult result = application.call(param);
        System.out.printf("%s\n",
                result.getOutput().getText());// 处理只输出文本text
    }

    public static void main(String[] args) {
        try {
            appCall();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.printf("Exception: %s", e.getMessage());
            System.out.println("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}
Base64 encoding example
// 建议dashscope SDK 的版本 >= 2.19.0
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;

public class Main {
    // 将本地图像编码为 Base64 字符串
    public static String encodeImage(String imagePath) throws IOException {
        byte[] imageBytes = Files.readAllBytes(Paths.get(imagePath));
        return Base64.getEncoder().encodeToString(imageBytes);
    }

    public static void appCall() throws NoApiKeyException, InputRequiredException, IOException {
        // 编码本地图像
        String base64Image = encodeImage("/path/to/your/image.jpeg"); // 替换为实际图像路径

        // 构建 Data URL(注意:MIME type 需与图像格式匹配)
        String dataUrl = "data:image/jpeg;base64," + base64Image;

        ApplicationParam param = ApplicationParam.builder()
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .appId("APP_ID") // 替换为实际的应用ID
                .prompt("这张图片里有什么?")
                .images(Arrays.asList(dataUrl)) // 使用 Data URL
                .build();

        Application application = new Application();
        ApplicationResult result = application.call(param);
        System.out.printf("%s\n", result.getOutput().getText());
    }

    public static void main(String[] args) {
        try {
            appCall();
        } catch (ApiException | NoApiKeyException | InputRequiredException | IOException e) {
            System.out.printf("Exception: %s", e.getMessage());
            System.out.println("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}

HTTP

curl

URL request example
curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "prompt": "这是什么",
        "image_list":["https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"]
    },
    "debug": {}
}'
Base64 encoding example
# 将本地图像编码为 Base64 字符串
base64_image=$(base64 -i /path/to/your/image.jpeg)  # macOS/Linux

# 构建 Data URL(注意:MIME type 需与图像格式匹配)
data_url="data:image/jpeg;base64,${base64_image}"

# 调用应用 API
curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data "{
    \"input\": {
        \"prompt\": \"这张图片里有什么?\",
        \"image_list\": [\"${data_url}\"]
    },
    \"debug\": {}
}"

PHP

URL request example
<?php
# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // 替换为实际的应用 ID

$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";

// 构造请求数据
$data = [
    "input" => [
        "prompt" => "这是什么",
        "image_list" => ["https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"],
    ],
    "debug" => [],
];
// 将数据编码为 JSON
$dataString = json_encode($data);

// 检查 json_encode 是否成功
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON encoding failed with error: " . json_last_error_msg());
}

// 初始化 cURL 对话
$ch = curl_init($url);

// 设置 cURL 选项
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $api_key
]);

// 执行请求
$response = curl_exec($ch);

// 检查 cURL 执行是否成功
if ($response === false) {
    die("cURL Error: " . curl_error($ch));
}

// 获取 HTTP 状态码
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 关闭 cURL 对话
curl_close($ch);
// 解码响应数据
$response_data = json_decode($response, true);
// 处理响应
if ($status_code == 200) {
    if (isset($response_data['output']['text'])) {
        echo "{$response_data['output']['text']}\n";
    } else {
        echo "No text in response.\n";
    }
}else {
    if (isset($response_data['request_id'])) {
        echo "request_id={$response_data['request_id']}\n";}
    echo "code={$status_code}\n";
    if (isset($response_data['message'])) {
        echo "message={$response_data['message']}\n";}
    else {
        echo "message=Unknown error\n";}
}
?>
Base64 encoding example
<?php
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID';

function encodeImage($imagePath) {
    if (!file_exists($imagePath)) die("Error: Image file not found");
    return base64_encode(file_get_contents($imagePath));
}

$base64Image = encodeImage("/path/to/your/image.jpeg");
$dataUrl = "data:image/jpeg;base64," . $base64Image;

$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";
$data = ["input" => ["prompt" => "这张图片里有什么?", "image_list" => [$dataUrl]], "debug" => []];

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'Authorization: Bearer ' . $api_key]);

$response = curl_exec($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($status_code == 200) {
    $response_data = json_decode($response, true);
    echo $response_data['output']['text'];
}
?>

Node.js

You must install the following dependencies:
npm install axios
URL request example
import axios from 'axios';
async function callDashScope() {
    // 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';//替换为实际的应用 ID

    const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;

    const data = {
        input: {
            prompt: "这是什么",
            image_list: ["https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"],
        },
        debug: {}
    };

    try {
        const response = await axios.post(url, data, {
            headers: {
                'Authorization': `Bearer ${apiKey}`,
                'Content-Type': 'application/json'
            }
        });

        if (response.status === 200) {
            console.log(`${response.data.output.text}`);
        } else {
            console.log(`request_id=${response.headers['request_id']}`);
            console.log(`code=${response.status}`);
            console.log(`message=${response.data.message}`);
        }
    } catch (error) {
        console.error(`Error calling DashScope: ${error.message}`);
        if (error.response) {
            console.error(`Response status: ${error.response.status}`);
            console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
        }
    }
}

callDashScope();
Base64 encoding example
import axios from 'axios';
import fs from 'fs';

async function callWithBase64() {
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';

    const imageBuffer = fs.readFileSync('/path/to/your/image.jpeg');
    const base64Image = imageBuffer.toString('base64');
    const dataUrl = `data:image/jpeg;base64,${base64Image}`;

    const response = await axios.post(
        `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`,
        { input: { prompt: "这张图片里有什么?", image_list: [dataUrl] } },
        { headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' } }
    );

    console.log(response.data.output.text);
}

callWithBase64();

C#

URL request example
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        // 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
        string appId = "APP_ID";// 替换为实际的应用ID

        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("请确保设置了 DASHSCOPE_API_KEY。");
            return;
        }

        string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
            string jsonContent = $@"{{
                ""input"": {{
                    ""prompt"": ""这是什么"",
                    ""image_list"": [""https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg""]
                }},
                ""parameters"": {{
                }},
                ""debug"": {{}}
            }}";

            HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

            try
            {
                HttpResponseMessage response = await client.PostAsync(url, content);

                if (response.IsSuccessStatusCode)
                {
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
                else
                {
                    Console.WriteLine($"Request failed with status code: {response.StatusCode}");
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error calling DashScope: {ex.Message}");
            }
        }
    }
}
Base64 encoding example
using System;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        var apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
        var appId = "APP_ID";

        byte[] imageBytes = File.ReadAllBytes("/path/to/your/image.jpeg");
        var base64Image = Convert.ToBase64String(imageBytes);
        var dataUrl = $"data:image/jpeg;base64,{base64Image}";

        using var client = new HttpClient();
        client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");

        var json = $@"{{""input"": {{""prompt"": ""这张图片里有什么?"", ""image_list"": [""{dataUrl}""]}}, ""debug"": {{}}}}";
        var content = new StringContent(json, Encoding.UTF8, "application/json");
        var response = await client.PostAsync($"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion", content);

        Console.WriteLine(await response.Content.ReadAsStringAsync());
    }
}

Go

URL request example
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
)

func main() {
	// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // 替换为实际的应用 ID

	if apiKey == "" {
		fmt.Println("请确保设置了DASHSCOPE_API_KEY。")
		return
	}

	url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)

	// 创建请求体
	requestBody := map[string]interface{}{
		"input": map[string]interface{}{
			"prompt":     "这是什么",
			"image_list": []string{"https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"},
		},
		"parameters": map[string]interface{}{},
		"debug":      map[string]interface{}{},
	}

	jsonData, err := json.Marshal(requestBody)
	if err != nil {
		fmt.Printf("Failed to marshal JSON: %v\n", err)
		return
	}

	// 创建 HTTP POST 请求
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Printf("Failed to create request: %v\n", err)
		return
	}

	// 设置请求头
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	// 发送请求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Printf("Failed to send request: %v\n", err)
		return
	}
	defer resp.Body.Close()

	// 读取响应
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Failed to read response: %v\n", err)
		return
	}

	// 处理响应
	if resp.StatusCode == http.StatusOK {
		fmt.Println("Request successful:")
		fmt.Println(string(body))
	} else {
		fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
		fmt.Println(string(body))
	}
}
Base64 encoding example
package main

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
)

func main() {
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID"

	imageData, _ := os.ReadFile("/path/to/your/image.jpeg")
	base64Image := base64.StdEncoding.EncodeToString(imageData)
	dataUrl := fmt.Sprintf("data:image/jpeg;base64,%s", base64Image)

	requestBody := map[string]interface{}{
		"input": map[string]interface{}{"prompt": "这张图片里有什么?", "image_list": []string{dataUrl}},
	}

	jsonData, _ := json.Marshal(requestBody)
	req, _ := http.NewRequest("POST", fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId), bytes.NewBuffer(jsonData))
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, _ := client.Do(req)
	defer resp.Body.Close()

	body, _ := io.ReadAll(resp.Body)
	fmt.Println(string(body))
}

Response object

status_codestring

The HTTP status code returned (only appears in the response for HTTP calls).

200 indicates a successful request; otherwise, the request failed.

When a call fails, both the Python SDK and Java SDK throw an exception; you can obtain the status code, error code, and detailed error information from the exception attributes e.status_code/e.code/e.message.

request_idstring

The unique identifier of this call.

The Java SDK returns this parameter as requestId.

codestring

The error code; empty when the call succeeds (only returned in the HTTP response body).

When an SDK call fails, the error code is returned through the code attribute of the DashScopeError exception (ApiException in Java).

messagestring

Detailed error information; ignored when the request succeeds (only returned in the HTTP response body).

When an SDK call fails, the error message is returned through the message attribute of the DashScopeError exception (ApiException in Java).

outputobject

The call result information.

output Properties

textstring
The reply content generated by the model.

finish_reasonstring
The reason for completion.

stop indicates a natural end (a preset marker was encountered); null indicates forced termination (such as reaching the maximum length limit or a manual stop).

session_idstring
The unique identifier of the current conversation.

Pass it in subsequent requests to carry the conversation history.

thoughtsarray
Set the has_thoughts parameter to True when calling to view the plugin call and knowledge retrieval process, or the thinking process of deep-thinking models, in thoughts.

thoughts Properties

thoughtstring
The model's thinking process.

After you select a deep-thinking model in the agent application in the console and successfully publish the application, if you set the has_thoughts parameter to True in the API call, the model's thinking process will be returned in this field.

reasoningContentstring
The model's thinking process.

After you select a deep-thinking model in the workflow application in the console and successfully publish the application, if you set the has_thoughts parameter to True in the API call, the model's thinking process will be returned in this field.

action_typestring
The type of execution step returned by the LLM. For example, API indicates executing an API plugin, agentRag indicates performing knowledge retrieval, and reasoning indicates the thinking process of a deep-thinking model.

action_namestring
The name of the executed action, such as knowledge retrieval, API plugin, or thinking process.

actionstring
The executed step.

action_input_streamstring
The streaming result of the input parameters.

action_inputstring
The input parameters of the plugin.

observationstring
The retrieval or plugin process.

doc_referencesarray
Information about the documents cited by the model from the retrieved recall documents.

Only after you turn on the Show answer sources switch and publish the application in the agent application in the Model Studio console can doc_references contain valid information.

doc_references Properties

index_idstring
The index of the recalled document cited by the model, such as [1].

titlestring
The title of the text chunk cited by the model.

doc_idstring
The document ID cited by the model.

doc_namestring
The document name cited by the model.

doc_urlstring
The document link cited by the model; null if the document is stored in the secure storage space of the Alibaba Cloud Model Studio platform.

textstring
The specific text content cited by the model.

biz_idstring
The business association identifier cited by the model.

imagesarray
The list of image URLs cited by the model.

page_numberarray
The page number of the text chunk cited by the model.

This parameter is only supported for knowledge bases created after October 25, 2024.

To use this parameter, the Python Dashscope SDK must be version 2.0.1 or later, and the Java Dashscope SDK must be version 2.16.10 or later.

workflow_messageobject
The object containing workflow node statuses and messages.

NoteOutput field specific to workflow applications:

  • This field is only returned when calling a workflow application; agent applications do not return it.
  • In streaming output mode, when flow_stream_mode is set to message_format or message_format_plus, this field returns the execution status and messages of each workflow node in real time.
  • In non-streaming output mode, this field returns the status and messages of the final node (the End node or Process output node).

Differences from agent application output:

  • Agent applications: the final reply is mainly returned via the output.text field, and the thoughts field (requires has_thoughts=true) returns the plugin call and knowledge retrieval process.
  • Workflow applications: in addition to output.text, the workflow_message field returns detailed execution information of workflow nodes, including node name, type, status, and the output content of each node.

workflow_message Properties

node_statusstring
The execution status of the current node, for example, executing.

node_typestring
The type of the current node, for example, End (end node).

node_msg_seq_idinteger
The sequence number of messages within a node.

node_namestring
The name of the current node, for example, End.

messageobject
The object containing the specific message content.

message Properties

contentstring
The specific text content of the message.

rolestring
The role of the message sender, for example, Assistant.

node_is_completedboolean
Indicates whether the current node has finished execution. true means completed; false means not completed.

node_idstring
The unique identifier ID of the current node.

parent_node_idstring
The ID of the parent node (loop node / batch node) that the current node belongs to.

  • Main canvas nodes: return null.
  • Sub-canvas nodes: return the node_id of the loop node or batch node they belong to.

Only in message_format_plus mode do sub-canvas nodes return non-null values.

Sub-canvas node content structure (message_format_plus)

When flow_stream_mode=message_format_plus and the node is in a sub-canvas (parent_node_id is non-null), message.content is the complete NodeResult JSON of that iteration/branch.

Sub-canvas node content fields

nodeIdstring
The node ID within the sub-canvas.

nodeNamestring
The node name.

nodeTypestring
The node type, such as LLM, Plugin, or Output.

nodeStatusstring
The node execution status: success / fail / skip (skipped, not executed) / executing.

inputstring
The node input content.

outputstring
The node output content.

indexinteger
The sub-canvas iteration/branch index, incrementing from 0.

parentNodeIdstring
The parent node (loop node / batch node) ID.

nodeExecTimestring
The node execution time, such as 100ms.

errorCodestring
Returned when node execution fails.

errorInfostring
Returned when node execution fails.

NoteThe processing rules for text nodes (Output / End text mode) and JSON nodes such as LLM are the same as on the main canvas: text nodes are deltas that must be concatenated, and JSON nodes are snapshots that must be replaced as a whole; node_is_completed=true marks the end of a node.

usageobject

The data usage information of this request.

usage Properties

modelsarray
The model information of this call.

models Properties

model_idstring
The model ID invoked by this application call.

input_tokensinteger
The length of the user input text after being converted into tokens.

output_tokensinteger
The length of the model-generated reply after being converted into tokens.

Single-turn conversation response example

The following is the raw response returned by the HTTP interface (the Python SDK returns a flattened response object, which can be read directly via response.text/response.finish_reason/response.session_id).

{
    "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 base

When calling the application knowledge base feature, to output the document information cited by the model from the recalled documents, click Retrieval settings in the agent application in the Model Studio console, turn on the Show answer sources switch, and publish the application.

The following is the response object shape of the Python SDK 2.0.

{
    "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]
        }]
}
Exception response example

When a request fails, the Python SDK throws an exception whose code and message attributes indicate the cause of the error.

The following shows an example of an exception response when a valid API-KEY is not provided.

request_id=1d14958f-0498-91a3-9e15-be477971967b,
code=401,
message=Invalid API-key provided.

QPM limits

Application calls are rate-limited on two independent dimensions, the application and the account. If either limit is reached, a rate limit error is returned:

  • Per-application concurrency: the number of requests per second counted by application ID (app_id), with a default upper limit of 100 QPS. Submission requests for asynchronous workflow tasks share this quota with synchronous calls.
  • Total account traffic: the number of requests per minute counted at the level of the same Alibaba Cloud primary account, with a default upper limit of 15000 QPM.

Requests that exceed the threshold are rejected with HTTP 429 and the error code Throttling.RateQuota, and usually recover automatically within one minute. If you expect a significant increase in business concurrency or call volume, contact your Alibaba Cloud business manager in advance to evaluate and request a quota increase.

Error codes

If the call fails (the Python SDK throws a DashScopeError exception, and HTTP calls return an error message), refer to Error codes for troubleshooting.