Workflow and legacy agent application API

Updated at:

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

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

Related guides

Prerequisites

Before you begin, make sure that you have completed the following operations:

  1. Create an application: Go to Application Management to create an Alibaba Cloud Model Studio application and obtain the application ID;
  2. Obtain an API Key: Obtain it in API Key Management, and configure the API Key in environment variables.
  3. Install the SDK (optional): If you use an SDK, install the DashScope SDK for the corresponding language.

Invocation methods

  • HTTP API calls

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

    Replace APP_ID with your actual application ID

  • SDK calls

    Python/Java SDK: The correct endpoint is configured by default in this document

    Custom endpoint: You can configure it through the base_url parameter

Online debugging: After you enter the debugging page through the application card -> Publish -> API debugging path, fill in the parameters and click Run.

Request body

app_idstring(Required)

Application identifier.

You can obtain the application ID on the application card of the Application Management page.

In the Java SDK, it is appId. When calling through HTTP, put the actual application ID into the URL to replace APP_ID.

promptstring(Required)

The input instruction from the user, which is used to guide the application to generate a reply.

When calling through HTTP, put prompt into the input object.

session_idstring (Optional)

The historical conversation identifier.

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

The ID automatically expires after 1 consecutive hour without any request.

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

messagesarray(Optional)

The context passed to the LLM, arranged in conversation order.

When you use the messages parameter to implement multi-turn conversation, you do not need to pass prompt or session_id.

If both session_id and messages are passed in, the LLM preferentially uses the content in messages and ignores session_id and prompt.

When calling through HTTP, put messages into the input object.

To use this parameter, the Python DashScope SDK must be at least 2.0.1, and the Java DashScope SDK must be at least 2.17.0.

Message types

System Messageobject (Optional)

The system message, used to set the role, tone, task objective, or constraints of the LLM. It is generally placed first in the messages array.

Properties

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 to system.

User Messageobject(Required)

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

Properties

contentstring(Required)

The message content.

Properties

textstring(Required)

The input text.

rolestring(Required)

The role of the user message, fixed to user.

Assistant Messageobject (Optional)

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

Properties

contentstring(Required)

The text content of the model reply.

rolestring(Required)

The role of the assistant message, fixed to assistant.

workspace string (Optional)

The business space identifier. Related document: Obtain the Workspace ID.

Pass the workspace ID only when calling an application in a sub-business space.

When calling through HTTP, specify X-DashScope-WorkSpace in the Header.

stream boolean(Optional) Default value: False

Whether to reply in streaming output mode.

We recommend setting it to True, which improves the reading experience and reduces the timeout risk.

Parameter values:

  • False (default): The model returns all generated content at once;
  • True (recommended): Output while generating. Each time a portion of content is generated, a data chunk is returned. You need to read these chunks one by one in real time to assemble the complete reply.

To implement streaming output in the Java SDK, call through the streamCall interface; to implement streaming output through HTTP, set X-DashScope-SSE to enable in the Header.

incremental_output boolean(Optional) Default value: False

Whether to enable incremental output in streaming output mode.

We recommend setting it to True, which improves the reading experience.

Parameter values:

  • False (default): Each time, the entire sequence that has been generated so far is output, 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 contain the content already 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 through HTTP, put incremental_output into the parameters object.

flow_stream_mode string(Optional) Default value: full_thoughts

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

Parameter values:

  • message_format_plus(Recommended): Message enhanced mode.

    In the workflow_message field, the execution process and results of all nodes are output, 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 needs to be appended; for JSON nodes (LLM / Component / AgentGroup, etc.), message.content is a complete JSON snapshot and needs to be replaced as a whole. When node_is_completed=true, the node is marked as finished executing.

    Sub-canvas node streaming: Nodes in the sub-canvas of loop nodes and batch processing nodes are also pushed in streaming mode, identified by the response field parent_node_id as the parent node they belong to.

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

    In the Java SDK, it is FlowStreamMode.MESSAGE_FORMAT_PLUS.

  • message_format(Recommended): Message mode.

    In the message field, the results of the specified nodes (process output node or end node) are output.

    ImportantIn the console application, turn on the streaming output switch of the target node to stream back results; when it is not turned on, the final result of the node is returned 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.

    The results of all nodes are output 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 at least 2.0.1, and the Java SDK must be at least 2.22.23. When calling through HTTP, put flow_stream_mode into the parameters object.

biz_paramsobject (Optional)

When the application passes parameters through custom variables, nodes, or plugins, use this field to pass them. Related documents: Call an agent application - Pass custom parameters, Invoke a workflow application - Pass custom parameters.

In the Java SDK, it is bizParams. When calling through 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": "Hangzhou"}

Agent applications pass prompt variables or plugin variable parameters through the following fields:

Properties

user_prompt_params object (Optional)

Indicates the custom prompt variable parameter information.

Variable names within an application cannot be duplicated, with an upper limit of 10.

Steps:

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

Example:

biz_params ={
    "user_prompt_params": {
        "date": "March 3, 2025",
        "city": "Hangzhou"
    }
}

user_defined_params object (Optional)

Indicates the custom plugin parameter information.

Plugins added to an application cannot be duplicated, with an upper limit of 10.

Properties

tool_idstring (Optional)

The plugin ID, which can be obtained on the plugin card.

${plugin_params}string(Optional)

Multiple key-value pairs contained at the innermost level of the object. Each key-value pair represents the user-defined parameter name to be passed and its specified value. For example:

"article_index": 2

Steps:

  1. Associate the specified plugin in the application, and publish the application.
  2. Pass the plugin information through this parameter in the API call.

You can provide multiple key-value pairs, where each key is the plugin's TOOL_ID and the value is the parameter object required by that plugin. Example:

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

user_defined_tokens object(Optional)

Indicates the user-level authentication information of the custom plugin.

Plugins added to an application cannot be duplicated, with an upper limit of 10.

Properties

tool_idstring (Optional)

The plugin ID, which can be obtained on the plugin card. It is passed through the <TOOL_ID> field.

user_token string (Optional)

Passes the user authentication information required by the plugin, such as the value of the actual DASHSCOPE_API_KEY.

Steps:

  1. Associate the specified plugin in the application, and publish the application.
  2. Pass the plugin user-level authentication information through this parameter in the API call.

You can provide multiple key-value pairs, where each key is the plugin's TOOL_ID and the value is the user_token object.

memory_id string (Optional)

The long-term memory ID, created through CreateMemory. Related document: Long-term memory.

NoteOnly agent applications support this parameter.

  1. Turn on the long-term memory switch in the application, and publish the application.
  2. When calling the application with the specified memory_id, the system automatically builds and saves long-term memory based on user preference information.
  3. When you call later with the same memory_id, the system restores these long-term memories and merges them with the latest user message for the model to process.

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

has_thoughts boolean (Optional) Default value: False

Whether to output the process of plugin calls and knowledge retrieval, or the thinking process of a model with thinking mode enabled, which can be viewed in the thoughts field.

Parameter values:

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

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

image_list array(Optional)

The image list. It supports image URLs and Data URLs (Base64-encoded). An image and video understanding model must be selected in the application.

The base64 encoded format can be constructed as a Data URL: data:[MIME_type];base64,{base64_image}. For detailed instructions and code examples, see the Visual understanding section to the right of this document.

Scenarios:

  • Image retrieval (agent applications): Retrieves a structured knowledge base containing image links based on the uploaded image link.
  • Visual understanding: Analyzes image content through the visual understanding capability of Qwen-VL series models to implement question answering.

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

In the Java SDK, it is images. When calling through HTTP, put image_list into the input object.

file_list array(Optional)

A list containing one or more file URLs.

NoteOnly agent applications support this parameter.

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

In the Java SDK, it is files. When calling through HTTP, put file_list into the input object.

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

rag_options object (Optional)

Used to configure retrieval-related parameters, including but not limited to retrieving from the specified knowledge bases or documents. Related document: Retrieve knowledge base.

NoteOnly agent applications support this parameter.

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

Properties

pipeline_ids array(Required)

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

Retrieves all documents in the specified knowledge base.

How to obtain:

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

In the Java SDK, it is pipelineIds.

file_idsarray(Optional)

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

Retrieves the unstructured documents in the specified knowledge base.

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 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:

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_idstring(Optional)

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_timeboolean (Optional) 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:
# Pass a custom time through user_prompt_params
biz_params ={
    "user_prompt_params": {
        "date": "March 3, 2025"
    }
}

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_searchboolean (Optional) 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_roundinteger (Optional)

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_thinking boolean (Optional) 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.v2 import DashScopeError

client = dashscope.Client(
    # If no environment variable is configured, replace the following with your Model Studio API key: api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
    api_key=os.getenv("DASHSCOPE_API_KEY"))
try:
    response = client.apps.completions.create(
        app_id='APP_ID',  # Replace with the actual application ID
        prompt='Who are you?')
    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'See: https://help.aliyun.com/zh/model-studio/developer-reference/error-code')

Java

Request example
// Recommended dashscope SDK version: 2.12.0 or later
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()
                // If no environment variable is configured, replace the following with your Model Studio API key: .apiKey("sk-xxx"). Do not hardcode the API key in production to reduce the risk of leakage.
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .appId("APP_ID")
                .prompt("Who are you?")
                .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("See: 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": "Who are you?"
    },
    "parameters":  {},
    "debug": {}
}'

Replace APP_ID with the actual application ID.

PHP

Request example
<?php

# If no environment variable is configured, replace the following with your Model Studio API key: $api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Replace with the actual application ID

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

// Build the request data
$data = [
    "input" => [
        'prompt' => 'Who are you?'
    ]
];

// Encode the data as JSON
$dataString = json_encode($data);

// Check whether json_encode succeeded
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON encoding failed with error: " . json_last_error_msg());
}

// Initialize the cURL handle
$ch = curl_init($url);

// Set cURL options
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
]);

// Execute the request
$response = curl_exec($ch);

// Check whether the cURL request succeeded
if ($response === false) {
    die("cURL Error: " . curl_error($ch));
}

// Get the HTTP status code
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close the cURL handle
curl_close($ch);
// Decode the response data
$response_data = json_decode($response, true);
// Process the response
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() {
    // If no environment variable is configured, replace the following with your Model Studio API key: apiKey='sk-xxx'. Do not hardcode the API key in production to reduce the risk of leakage.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';// Replace with the actual application ID

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

    const data = {
        input: {
            prompt: "Who are you?"
        },
        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)
    {
        //If no environment variable is configured, replace the following with your Model Studio API key: apiKey="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
        string appId = "APP_ID"; // Replace with the actual application 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"": ""Who are you?""
                },
                ""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() {
	// If no environment variable is configured, replace the following with your Model Studio API key: apiKey := "sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // Replace with the actual application ID

	if apiKey == "" {
		fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
		return
	}

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

	// Create the request body
	requestBody := map[string]interface{}{
		"input": map[string]string{
			"prompt": "Who are you?",
		},
		"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
	}

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

	// Set the request headers
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	// Send the request
	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()

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

	// Process the response
	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"
# Replace {WorkspaceId} with the workspace ID and cn-beijing with the appropriate region (Singapore: ap-southeast-1, US East: 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 "Hello"

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.v2 import DashScopeError

def call_with_session():
    client = dashscope.Client(
        # If no environment variable is configured, replace the following with your Model Studio API key: api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
        api_key=os.getenv("DASHSCOPE_API_KEY"))
    try:
        response = client.apps.completions.create(
            app_id='APP_ID',  # Replace with the actual application ID
            prompt='Who are you?')

        responseNext = client.apps.completions.create(
                    app_id='APP_ID',  # Replace with the actual application ID
                    prompt='What skills do you have?',
                    session_id=response.session_id)  # session_id from the previous response

        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'See: 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()
                // If no environment variable is configured, replace the following with your Model Studio API key: .apiKey("sk-xxx"). Do not hardcode the API key in production to reduce the risk of leakage.
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // Replace with the actual application ID
                .appId("APP_ID")
                .prompt("Who are you?")
                .build();

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

        param.setSessionId(result.getOutput().getSessionId());
        param.setPrompt("What skills do you have?");
        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("See: 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": "Who are you?"
    },
    "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": "What skills do you have?",
        "session_id":"4f8ef7233dc641aba496cb201fa59f8c"
    },
    "parameters":  {},
    "debug": {}
}'

PHP

Request example (previous turn)
<?php
# If no environment variable is configured, replace the following with your Model Studio API key: $api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Replace with the actual application ID

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

// Build the request data
$data = [
    "input" => [
        'prompt' => 'Who are you?'
    ]
];

// Encode the data as JSON
$dataString = json_encode($data);

// Check whether json_encode succeeded
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON encoding failed with error: " . json_last_error_msg());
}

// Initialize the cURL handle
$ch = curl_init($url);

// Set cURL options
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
]);

// Execute the request
$response = curl_exec($ch);

// Check whether the cURL request succeeded
if ($response === false) {
    die("cURL Error: " . curl_error($ch));
}

// Get the HTTP status code
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close the cURL handle
curl_close($ch);
// Decode the response data
$response_data = json_decode($response, true);
// Process the response
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
# If no environment variable is configured, replace the following with your Model Studio API key: $api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Replace with the actual application ID

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

// Build the request data
$data = [
    "input" => [
        'prompt' => 'What skills do you have?',
        // Replace with the session_id returned by the previous turn
        'session_id' => '2e658bcb514f4d30ab7500b4766a8d43'
    ]
];

// Encode the data as JSON
$dataString = json_encode($data);

// Check whether json_encode succeeded
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON encoding failed with error: " . json_last_error_msg());
}

// Initialize the cURL handle
$ch = curl_init($url);

// Set cURL options
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
]);

// Execute the request
$response = curl_exec($ch);

// Check whether the cURL request succeeded
if ($response === false) {
    die("cURL Error: " . curl_error($ch));
}

// Get the HTTP status code
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close the cURL handle
curl_close($ch);
// Decode the response data
$response_data = json_decode($response, true);
// Process the response
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

Install the required dependencies:
npm install axios
Request example (previous turn)
const axios = require('axios');

async function callDashScope() {
    // If no environment variable is configured, replace the following with your Model Studio API key: apiKey='sk-xxx'. Do not hardcode the API key in production to reduce the risk of leakage.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';// Replace with the actual application ID

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

    const data = {
        input: {
            prompt: "Who are you?"
        },
        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() {
    // If no environment variable is configured, replace the following with your Model Studio API key: apiKey='sk-xxx'. Do not hardcode the API key in production to reduce the risk of leakage.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';// Replace with the actual application ID

    const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
    // Replace session_id with the actual session_id from the previous turn
    const data = {
        input: {
            prompt: "What skills do you have?",
            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)
    {
        //If no environment variable is configured, replace the following with your Model Studio API key: apiKey="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
        string appId = "APP_ID"; // Replace with the actual application 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"": ""Who are you?""
                },
                ""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)
    {
        //If no environment variable is configured, replace the following with your Model Studio API key: apiKey="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
        string appId = "APP_ID"; // Replace with the actual application 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"": ""What skills do you have?"",
                    ""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() {
	// If no environment variable is configured, replace the following with your Model Studio API key: apiKey := "sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // Replace with the actual application ID

	if apiKey == "" {
		fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
		return
	}

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

	// Create the request body
	requestBody := map[string]interface{}{
		"input": map[string]string{
			"prompt": "Who are you?",
		},
		"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
	}

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

	// Set the request headers
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	// Send the request
	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()

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

	// Process the response
	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() {
	// If no environment variable is configured, replace the following with your Model Studio API key: apiKey := "sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // Replace with the actual application ID

	if apiKey == "" {
		fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
		return
	}

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

	// Create the request body
	requestBody := map[string]interface{}{
		"input": map[string]string{
			"prompt":     "What skills do you have?",
			"session_id": "f7eea37f0c734c20998a021b688d6de2", // Replace with the actual session_id from the previous turn
		},
		"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
	}

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

	// Set the request headers
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	// Send the request
	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()

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

	// Process the response
	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
# Requires dashscope 2.0.1 or later
from dashscope.v2 import DashScopeError

client = dashscope.Client(
        # If no environment variable is configured, replace the following with your Model Studio API key: api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
        api_key=os.getenv("DASHSCOPE_API_KEY"))
biz_params = {
    # Pass custom plugin input parameters for the agent application; replace the custom plugin ID with <TOOL_ID>
    "user_defined_params": {
        "<TOOL_ID>": {
            "article_index": 2}}}
try:
    response = client.apps.completions.create(
        app_id='APP_ID',
        prompt='Dormitory agreement content',
        biz_params=biz_params)
    print('%s\n' % (response.text))  # Handle text-only output
    # 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'See: 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 =
                // Pass custom plugin input parameters for the agent application; replace the custom plugin ID with <TOOL_ID>
                "{\"user_defined_params\":{\"<TOOL_ID>\":{\"article_index\":2}}}";
        ApplicationParam param = ApplicationParam.builder()
                // If no environment variable is configured, replace the following with your Model Studio API key: .apiKey("sk-xxx"). Do not hardcode the API key in production to reduce the risk of leakage.
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .appId("APP_ID")
                .prompt("Dormitory agreement content")
                .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("See: 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": "Dormitory agreement content",
        "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

# If no environment variable is configured, replace the following with your Model Studio API key: $api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Replace with the actual application ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";
// Replace <TOOL_ID> with the actual plugin ID
// Build the request data
$data = [
    "input" => [
        'prompt' => 'Dormitory agreement content',
        'biz_params' => [
        'user_defined_params' => [
            '<TOOL_ID>' => [
                'article_index' => 2
                ]
            ]
        ]
    ],
];
// Encode the data as JSON
$dataString = json_encode($data);

// Check whether json_encode succeeded
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON encoding failed with error: " . json_last_error_msg());
}

// Initialize the cURL handle
$ch = curl_init($url);

// Set cURL options
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
]);

// Execute the request
$response = curl_exec($ch);

// Check whether the cURL request succeeded
if ($response === false) {
    die("cURL Error: " . curl_error($ch));
}

// Get the HTTP status code
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close the cURL handle
curl_close($ch);
// Decode the response data
$response_data = json_decode($response, true);
// Process the response
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

Install the required dependencies:
npm install axios
Request example
const axios = require('axios');

async function callDashScope() {
    // If no environment variable is configured, replace the following with your Model Studio API key: apiKey='sk-xxx'. Do not hardcode the API key in production to reduce the risk of leakage.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';// Replace with the actual application ID
    const pluginCode = 'TOOL_ID';// Replace with the actual plugin ID
    const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;

    const data = {
        input: {
            prompt: "Dormitory agreement content",
            biz_params: {
                user_defined_params: {
                    [pluginCode]: {
                        // article_index is a custom plugin variable; replace it with the actual plugin variable
                        '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)
    {
        // If no environment variable is configured, replace the following with your Model Studio API key: apiKey="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
        string appId = "APP_ID";// Replace with the actual application ID

        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("Make sure DASHSCOPE_API_KEY is set.");
            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"; // Replace TOOL_ID with the actual plugin ID
            string jsonContent = $@"{{
                ""input"": {{
                    ""prompt"": ""Dormitory agreement content"",
                    ""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() {
	// If no environment variable is configured, replace the following with your Model Studio API key: apiKey := "sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID"           // Replace with the actual application ID
	pluginCode := "TOOL_ID" // Replace with the actual plugin ID

	if apiKey == "" {
		fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
		return
	}

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

	// Create the request body
	requestBody := map[string]interface{}{
		"input": map[string]interface{}{
			"prompt": "Dormitory agreement content",
			"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
	}

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

	// Set the request headers
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	// Send the request
	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()

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

	// Process the response
	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.v2 import DashScopeError

client = dashscope.Client(
            # If no environment variable is configured, replace the following with your Model Studio API key: api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
            api_key=os.getenv("DASHSCOPE_API_KEY"))
try:
    stream = client.apps.completions.create(
                app_id='APP_ID',
                prompt='Who are you?',
                stream=True,  # streaming output
                incremental_output=True)  # Incremental output

    for partial in stream:
        print(f'{partial.text}\n')  # Handle text-only output
except DashScopeError as e:
    print(f'request_id={e.request_id}')
    print(f'code={e.code}')
    print(f'message={e.message}')
    print(f'See: https://help.aliyun.com/zh/model-studio/developer-reference/error-code')

Java

Request example
// Recommended dashscope SDK version: 2.15.0 or later
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;// streaming output
// Implement streaming output for an agent application call

public class Main {
    public static void streamCall() throws NoApiKeyException, InputRequiredException {
        ApplicationParam param = ApplicationParam.builder()
                // If no environment variable is configured, replace the following with your Model Studio API key: .apiKey("sk-xxx"). Do not hardcode the API key in production to reduce the risk of leakage.
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // Replace with the actual application ID
                .appId("APP_ID")
                .prompt("Who are you?")
                // Incremental output
                .incrementalOutput(true)
                .build();
        Application application = new Application();
        // .streamCall(): streaming output content
        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("See: 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": "Who are you?"

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

Replace APP_ID with the actual application ID.

PHP

Request example
<?php

// If no environment variable is configured, replace the following with your Model Studio API key: $api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Replace with the actual application ID

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

// Build the request data
$data = [
    "input" => [
        'prompt' => 'Who are you?'],
    "parameters" => [
        'incremental_output' => true]];// Incremental output
// Encode the data as JSON
$dataString = json_encode($data);

// Check whether json_encode succeeded
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON encoding failed with error: " . json_last_error_msg());
}

// Initialize the cURL handle
$ch = curl_init($url);

// Set cURL options
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); // Do not return the transferred data
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($ch, $string) {
    echo $string; // Process streaming data
    return strlen($string);
});
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $api_key,
    'X-DashScope-SSE: enable' // streaming output
]);

// Execute the request
$response = curl_exec($ch);

// Check whether the cURL request succeeded
if ($response === false) {
    die("cURL Error: " . curl_error($ch));
}

// Get the HTTP status code
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close the cURL handle
curl_close($ch);

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

Node.js

You need to install the following dependencies:
npm install axios
Request example

1. Output the complete response

const axios = require('axios');

async function callDashScope() {
    //If no environment variable is configured, replace the following with your Model Studio API key: apiKey='sk-xxx'. Do not hardcode the API key in production to reduce the risk of leakage.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';// Replace with the actual application ID

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

    const data = {
        input: {
            prompt: "Who are you?"
        },
        parameters: {
            'incremental_output' : true // Incremental output
        },
        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' // streaming output
            },
            responseType: 'stream' // for handling streaming responses
        });

        if (response.status === 200) {
            // Process the streaming response
            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() {
    //If no environment variable is configured, replace the following with your Model Studio API key: apiKey='sk-xxx'. Do not hardcode the API key in production to reduce the risk of leakage.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID'; // Replace with the actual application ID

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

    const data = {
        input: { prompt: "Who are you?" },
        parameters: { incremental_output: true }, // Incremental output
        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' // streaming output
            },
            responseType: 'stream' // for handling streaming responses
        });

        if (response.status === 200) {
            // // Process the streaming response; parse and convert the SSE stream
            const sseTransformer = new Transform({
                transform(chunk, encoding, callback) {
                    this.buffer += chunk.toString();

                    // Split by SSE events (two newlines)
                    const events = this.buffer.split(/\n\n/);
                    this.buffer = events.pop() || ''; // Keep the incomplete part

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

                        // Parse the event content
                        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 parse error:', e.message);
                                }
                            }
                        });

                        if (textContent) {
                            // Add a newline and push
                            this.push(textContent + '\n');
                        }
                    });

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

            // Pipe processing
            response.data
                .pipe(sseTransformer)
                .on('data', (textWithNewline) => {
                    process.stdout.write(textWithNewline); // Output with automatic line breaks
                })
                .on('end', () => console.log(""))
                .on('error', err => console.error("Pipe error:", err));

        } else {
            console.log("Request failed, status code:", response.status);
            response.data.on('data', chunk => console.log(chunk.toString()));
        }
    } catch (error) {
        console.error(`API call failed: ${error.message}`);
        if (error.response) {
            console.error(`Status code: ${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)
    {
        //If no environment variable is configured, replace the following with your Model Studio API key: apiKey="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
        string appId = "APP_ID"; // Replace with the actual application 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"": ""Who are you?""
                },
                ""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; // Declare as a nullable string
                        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() {
	// If no environment variable is configured, replace the following with your Model Studio API key: apiKey := "sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // Replace with the actual application ID

	if apiKey == "" {
		fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
		return
	}

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

	// Create the request body; incremental_output controls whether streaming is enabled
	requestBody := map[string]interface{}{
		"input": map[string]string{
			"prompt": "Who are you?",
		},
		"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
	}

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

	// Set the request headers; set X-DashScope-SSE to enable to turn on streaming
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("X-DashScope-SSE", "enable")

	// Send the request
	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
	}

	// Process the streaming response
	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
# Requires dashscope 2.0.1 or later
from dashscope.v2 import DashScopeError

client = dashscope.Client(
    # If no environment variable is configured, replace the following with your Model Studio API key: api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
    api_key=os.getenv("DASHSCOPE_API_KEY"))
try:
    response = client.apps.completions.create(
        app_id='APP_ID',  # Replace APP_ID with the actual application ID
        prompt='Recommend a phone under 3,000 yuan',
        rag_options={
            "pipeline_ids": ["PIPELINE_ID1","PIPELINE_ID2"],  # Replace with the actual knowledge base IDs, separated by commas
        }
    )
    print('%s\n' % (response.text))  # Handle text-only output
    # 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'See: https://help.aliyun.com/zh/model-studio/developer-reference/error-code')

Java

Request example
// Recommended dashscope SDK version: 2.16.8 or later;
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()
                // If no environment variable is configured, replace the following with your Model Studio API key: .apiKey("sk-xxx"). Do not hardcode the API key in production to reduce the risk of leakage.
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .appId("APP_ID") // Replace with the actual application ID
                .prompt("Recommend a phone around 3,000 yuan")
                .ragOptions(RagOptions.builder()
                        // Replace with the specified knowledge base IDs, separated by commas
                        .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());// Handle text-only output
    }

    public static void main(String[] args) {
        try {
            streamCall();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.printf("Exception: %s", e.getMessage());
            System.out.println("See: 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": "Recommend a phone under 3,000 yuan"
    },
    "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
# If no environment variable is configured, replace the following with your Model Studio API key: $api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Replace with the actual application ID

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

// Build the request data
$data = [
    "input" => [
        'prompt' => 'Recommend a phone under 3,000 yuan'
    ],
    "parameters" => [
        'rag_options' => [
            'pipeline_ids' => ['PIPELINE_ID1','PIPELINE_ID2']//Replace with the specified knowledge base IDs, separated by commas
        ]
    ]
];
// Encode the data as JSON
$dataString = json_encode($data);

// Check whether json_encode succeeded
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON encoding failed with error: " . json_last_error_msg());
}

// Initialize the cURL handle
$ch = curl_init($url);

// Set cURL options
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
]);

// Execute the request
$response = curl_exec($ch);

// Check whether the cURL request succeeded
if ($response === false) {
    die("cURL Error: " . curl_error($ch));
}

// Get the HTTP status code
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close the cURL handle
curl_close($ch);
// Decode the response data
$response_data = json_decode($response, true);
// Process the response
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

Install the required dependencies:
npm install axios
Request example
const axios = require('axios');
async function callDashScope() {
    // If no environment variable is configured, replace the following with your Model Studio API key: apiKey='sk-xxx'. Do not hardcode the API key in production to reduce the risk of leakage.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';//Replace with the actual application ID

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

    const data = {
        input: {
            prompt: "Recommend a phone under 3,000 yuan"
        },
        parameters: {
            rag_options:{
                pipeline_ids:['PIPELINE_ID1','PIPELINE_ID2']  // Replace with the specified knowledge base IDs, separated by commas
            }
        },
        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)
    {
        // If no environment variable is configured, replace the following with your Model Studio API key: apiKey="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
        string appId = "APP_ID";// Replace with the actual application ID
        // Replace PIPELINE_ID1 with the specified knowledge base ID
        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("Make sure DASHSCOPE_API_KEY is set.");
            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"": ""Recommend a phone under 3,000 yuan""
                }},
                ""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() {
	// If no environment variable is configured, replace the following with your Model Studio API key: apiKey := "sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // Replace with the actual application ID

	if apiKey == "" {
		fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
		return
	}

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

	// Create the request body
	requestBody := map[string]interface{}{
		"input": map[string]string{
			"prompt": "Recommend a phone under 3,000 yuan",
		},
		"parameters": map[string]interface{}{
			"rag_options": map[string]interface{}{
				"pipeline_ids": []string{"PIPELINE_ID1"}, // Replace with the specified knowledge base ID
			},
		},
		"debug": map[string]interface{}{},
	}

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

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

	// Set the request headers
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	// Send the request
	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()

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

	// Process the response
	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)
# Requires dashscope 2.0.1 or later
import os
import dashscope
from dashscope.v2 import DashScopeError

client = dashscope.Client(
           # If no environment variable is configured, replace the following with your Model Studio API key: api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
            api_key=os.getenv("DASHSCOPE_API_KEY"))
try:
    response = client.apps.completions.create(
                app_id='APP_ID',  # Enter the actual application ID
                prompt='User dietary preference: noodles',
                memory_id='MEMORY_ID')  # Enter the actual memory ID

    print('%s\n' % (response.text))  # Handle text-only output
    # 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'See: https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
Request example (call again)
# Requires dashscope 2.0.1 or later
import os
import dashscope
from dashscope.v2 import DashScopeError

client = dashscope.Client(
           # If no environment variable is configured, replace the following with your Model Studio API key: api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
            api_key=os.getenv("DASHSCOPE_API_KEY"))
try:
    response = client.apps.completions.create(
                app_id='APP_ID',  # Enter the actual application ID
                prompt='Food recommendations',
                memory_id='MEMORY_ID')  # Enter the actual memory ID

    print('%s\n' % (response.text))  # Handle text-only output
    # 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'See: https://help.aliyun.com/zh/model-studio/developer-reference/error-code')

Java

Request example (generate memory content)
// DashScope SDK version must be 2.17.0 or later
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()
                // If no environment variable is configured, replace the following with your Model Studio API key: .apiKey("sk-xxx"). Do not hardcode the API key in production to reduce the risk of leakage.
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .appId("APP_ID") // Replace with the actual application ID
                .prompt("User dietary preference: noodles")
                .memoryId("MEMORY_ID") // Replace with the actual memory ID
                .build();

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

        System.out.printf("%s\n",
                result.getOutput().getText()); // Handle text-only output
    }
    public static void main(String[] args) {
        try {
            callWithMemory();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.printf("Exception: %s", e.getMessage());
            System.out.println("See: https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}
Request example (call again)
// DashScope SDK version must be 2.17.0 or later
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()
                // If no environment variable is configured, replace the following with your Model Studio API key: .apiKey("sk-xxx"). Do not hardcode the API key in production to reduce the risk of leakage.
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .appId("APP_ID") // Replace with the actual application ID
                .prompt("Food recommendations")
                .memoryId("MEMORY_ID") // Replace with the actual memory ID
                .build();

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

        System.out.printf("text: %s\n",
                result.getOutput().getText()); // Handle text-only output
    }
    public static void main(String[] args) {
        try {
            callWithMemory();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.printf("Exception: %s", e.getMessage());
            System.out.println("See: 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": "User dietary preference: noodles",
        "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": "Food recommendations",
        "memory_id": "MEMORY_ID"
    },
    "parameters":  {},
    "debug": {}
}'

Replace APP_ID with the actual application ID.

PHP

Request example (generating memory content)
<?php
# If no environment variable is configured, replace the following with your Model Studio API key: $api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Replace with the actual application ID
$memory_id = 'MEMORY_ID'; // Replace with the actual memory ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/{$application_id}/completion";

// Build the request data
$data = [
    "input" => [
        'prompt' => 'User dietary preference: noodles',
        'memory_id' => $memory_id
    ]
];
// Encode the data as JSON
$dataString = json_encode($data);

// Check whether json_encode succeeded
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON encoding failed with error: " . json_last_error_msg());
}

// Initialize the cURL handle
$ch = curl_init($url);

// Set cURL options
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
]);

// Execute the request
$response = curl_exec($ch);

// Check whether the cURL request succeeded
if ($response === false) {
    die("cURL Error: " . curl_error($ch));
}

// Get the HTTP status code
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close the cURL handle
curl_close($ch);
// Decode the response data
$response_data = json_decode($response, true);
// Process the response
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 (calling again)
<?php
# If no environment variable is configured, replace the following with your Model Studio API key: $api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Replace with the actual application ID
$memory_id = 'MEMORY_ID'; // Replace with the actual memory ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/{$application_id}/completion";

// Build the request data
$data = [
    "input" => [
        'prompt' => 'Food recommendations',
        'memory_id' => $memory_id
    ]
];
// Encode the data as JSON
$dataString = json_encode($data);

// Check whether json_encode succeeded
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON encoding failed with error: " . json_last_error_msg());
}

// Initialize the cURL handle
$ch = curl_init($url);

// Set cURL options
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
]);

// Execute the request
$response = curl_exec($ch);

// Check whether the cURL request succeeded
if ($response === false) {
    die("cURL Error: " . curl_error($ch));
}

// Get the HTTP status code
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close the cURL handle
curl_close($ch);
// Decode the response data
$response_data = json_decode($response, true);
// Process the response
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

Install the required dependencies:
npm install axios
Request example (generating memory content)
const axios = require('axios');

async function callDashScope() {
    //If no environment variable is configured, replace the following with your Model Studio API key: apiKey='sk-xxx'. Do not hardcode the API key in production to reduce the risk of leakage.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';// Replace with the actual application ID
    const memoryId = 'MEMORY_ID';// Replace with the actual memory ID

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

    const data = {
        input: {
            prompt: "User dietary preference: noodles",
            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 (calling again)
const axios = require('axios');

async function callDashScope() {
    //If no environment variable is configured, replace the following with your Model Studio API key: apiKey='sk-xxx'. Do not hardcode the API key in production to reduce the risk of leakage.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';// Replace with the actual application ID
    const memoryId = 'MEMORY_ID';// Replace with the actual memory ID

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

    const data = {
        input: {
            prompt: "Food recommendations",
            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 (generating memory content)
using System.Text;

class Program
{
    static async Task Main(string[] args)
    {
        // If no environment variable is configured, replace the following with your Model Studio API key: apiKey="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
        string appId = "APP_ID";// Replace with the actual application ID
        string memoryId = "MEMORY_ID";//Replace with the actual memory ID
        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("Make sure DASHSCOPE_API_KEY is set.");
            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"": ""User dietary preference: noodles"",
                    ""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 (calling again)
using System.Text;

class Program
{
    static async Task Main(string[] args)
    {
        // If no environment variable is configured, replace the following with your Model Studio API key: apiKey="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
        string appId = "APP_ID";// Replace with the actual application ID
        string memoryId = "MEMORY_ID";//Replace with the actual memory ID
        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("Make sure DASHSCOPE_API_KEY is set.");
            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"": ""Food recommendations"",
                    ""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 (generating memory content)
package main

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

func main() {
	// If no environment variable is configured, replace the following with your Model Studio API key: apiKey := "sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // Replace with the actual application ID

	if apiKey == "" {
		fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
		return
	}

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

	// Create the request body
	requestBody := map[string]interface{}{
		"input": map[string]string{
			"prompt":    "User dietary preference: noodles",
			"memory_id": "MEMORY_ID", // Replace with the actual memory 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
	}

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

	// Set the request headers
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	// Send the request
	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()

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

	// Process the response
	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 (calling again)
package main

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

func main() {
	// If no environment variable is configured, replace the following with your Model Studio API key: apiKey := "sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // Replace with the actual application ID

	if apiKey == "" {
		fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
		return
	}

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

	// Create the request body
	requestBody := map[string]interface{}{
		"input": map[string]string{
			"prompt":    "Food recommendations",
			"memory_id": "MEMORY_ID", // Replace with the actual memory 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
	}

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

	// Set the request headers
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	// Send the request
	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()

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

	// Process the response
	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
# Requires dashscope 2.0.1 or later
from dashscope.v2 import DashScopeError

client = dashscope.Client(
    # If no environment variable is configured, replace the following with your Model Studio API key: api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
    api_key=os.getenv("DASHSCOPE_API_KEY"))
try:
    response = client.apps.completions.create(
        app_id='APP_ID',  # Replace APP_ID with the actual application ID
        prompt='Based on the following file, recommend a phone under 3,000 yuan',
        rag_options={
            "session_file_ids": ["Session_File_ID1"],  # Replace Session_File_ID1 with the actual temporary file ID, separated by commas
        }
    )
    print('%s\n' % (response.text))  # Handle text-only output
    # 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'See: https://help.aliyun.com/zh/model-studio/developer-reference/error-code')

Java

Request example
// Recommended dashscope SDK version: 2.17.0 or later;
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()
                // If no environment variable is configured, replace the following with your Model Studio API key: .apiKey("sk-xxx"). Do not hardcode the API key in production to reduce the risk of leakage.
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .appId("APP_ID") // Replace with the actual application ID
                .prompt("Based on the following file, recommend a phone around 3,000 yuan")
                .ragOptions(RagOptions.builder()
                        .sessionFileIds(Arrays.asList("Session_File_ID1", "Session_File_ID2"))  // Replace with the specified temporary file IDs, separated by commas
                        .build())
                .build();

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

    public static void main(String[] args) {
        try {
            appCall();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.printf("Exception: %s", e.getMessage());
            System.out.println("See: 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": "Based on the following file, recommend a phone under 3,000 yuan"
    },
    "parameters":  {
                    "rag_options" : {
                    "session_file_ids":["Session_File_ID1"]}
    },
    "debug": {}
}'

PHP

Request example
<?php
# If no environment variable is configured, replace the following with your Model Studio API key: $api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Replace with the actual application ID

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

// Build the request data
$data = [
    "input" => [
        'prompt' => 'Based on the following file, recommend a phone under 3,000 yuan'
    ],
    "parameters" => [
        'rag_options' => [
            'session_file_ids' => ['Session_File_ID1']//Replace with the specified temporary file IDs, separated by commas
        ]
    ]
];
// Encode the data as JSON
$dataString = json_encode($data);

// Check whether json_encode succeeded
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON encoding failed with error: " . json_last_error_msg());
}

// Initialize the cURL handle
$ch = curl_init($url);

// Set cURL options
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
]);

// Execute the request
$response = curl_exec($ch);

// Check whether the cURL request succeeded
if ($response === false) {
    die("cURL Error: " . curl_error($ch));
}

// Get the HTTP status code
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close the cURL handle
curl_close($ch);
// Decode the response data
$response_data = json_decode($response, true);
// Process the response
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

Install the required dependencies:
npm install axios
Request example
const axios = require('axios');
async function callDashScope() {
    // If no environment variable is configured, replace the following with your Model Studio API key: apiKey='sk-xxx'. Do not hardcode the API key in production to reduce the risk of leakage.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';//Replace with the actual application ID

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

    const data = {
        input: {
            prompt: "Based on the following file, recommend a phone under 3,000 yuan"
        },
        parameters: {
            rag_options:{
                session_file_ids:['Session_File_ID1']  // Replace with the specified temporary file IDs, separated by commas
            }
        },
        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)
    {
        // If no environment variable is configured, replace the following with your Model Studio API key: apiKey="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
        string appId = "APP_ID";// Replace with the actual application ID
        // Replace Session_File_ID1 with the specified temporary file ID
        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("Make sure DASHSCOPE_API_KEY is set.");
            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"": ""Based on the following file, recommend a phone under 3,000 yuan""
                }},
                ""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() {
	// If no environment variable is configured, replace the following with your Model Studio API key: apiKey := "sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // Replace with the actual application ID

	if apiKey == "" {
		fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
		return
	}

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

	// Create the request body
	requestBody := map[string]interface{}{
		"input": map[string]string{
			"prompt": "Based on the following file, recommend a phone under 3,000 yuan",
		},
		"parameters": map[string]interface{}{
			"rag_options": map[string]interface{}{
				"session_file_ids": []string{"Session_File_ID1"}, // Replace with the actual temporary file
			},
		},
		"debug": map[string]interface{}{},
	}

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

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

	// Set the request headers
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	// Send the request
	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()

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

	// Process the response
	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
# Requires dashscope 2.0.1 or later
from dashscope.v2 import DashScopeError

client = dashscope.Client(
    # If no environment variable is configured, replace the following with your Model Studio API key: api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
    api_key=os.getenv("DASHSCOPE_API_KEY"))
try:
    response = client.apps.completions.create(
        app_id='APP_ID',  # Replace APP_ID with the actual application ID
        prompt='What is this',
        image_list=['https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg'],
    )
    print('%s\n' % (response.text))  # Handle text-only output
    # 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'See: https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
Base64 encoding example
import os
import base64
import dashscope
from dashscope.v2 import DashScopeError

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

# Encode the local image as a Base64 string
def encode_image(image_path):
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode("utf-8")

# Encode the local image
base64_image = encode_image("/path/to/your/image.jpeg")  # Replace with the actual image path

# Build the Data URL (the MIME type must match the image format)
data_url = f"data:image/jpeg;base64,{base64_image}"

# Call the application API
try:
    response = client.apps.completions.create(
        app_id='APP_ID',  # Replace APP_ID with the actual application ID
        prompt='What is in this image?',
        image_list=[data_url],  # Use the 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'See: https://help.aliyun.com/zh/model-studio/developer-reference/error-code')

Java

URL request example
// Recommended dashscope SDK version: 2.19.0 or later;
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()
                // If no environment variable is configured, replace the following with your Model Studio API key: .apiKey("sk-xxx"). Do not hardcode the API key in production to reduce the risk of leakage.
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .appId("APP_ID") // Replace with the actual application ID
                .prompt("What is this?")
                .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());// Handle text-only output
    }

    public static void main(String[] args) {
        try {
            appCall();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.printf("Exception: %s", e.getMessage());
            System.out.println("See: https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}
Base64 encoding example
// Recommended dashscope SDK version: 2.19.0 or later
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 {
    // Encode the local image as a Base64 string
    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 {
        // Encode the local image
        String base64Image = encodeImage("/path/to/your/image.jpeg"); // Replace with the actual image path

        // Build the Data URL (the MIME type must match the image format)
        String dataUrl = "data:image/jpeg;base64," + base64Image;

        ApplicationParam param = ApplicationParam.builder()
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .appId("APP_ID") // Replace with the actual application ID
                .prompt("What is in this image?")
                .images(Arrays.asList(dataUrl)) // Use the 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("See: 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": "What is this",
        "image_list":["https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"]
    },
    "debug": {}
}'
Base64 encoding example
# Encode the local image as a Base64 string
base64_image=$(base64 -i /path/to/your/image.jpeg)  # macOS/Linux

# Build the Data URL (the MIME type must match the image format)
data_url="data:image/jpeg;base64,${base64_image}"

# Call the application 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\": \"What is in this image?\",
        \"image_list\": [\"${data_url}\"]
    },
    \"debug\": {}
}"

PHP

URL request example
<?php
# If no environment variable is configured, replace the following with your Model Studio API key: $api_key="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Replace with the actual application ID

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

// Build the request data
$data = [
    "input" => [
        "prompt" => "What is this",
        "image_list" => ["https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"],
    ],
    "debug" => [],
];
// Encode the data as JSON
$dataString = json_encode($data);

// Check whether json_encode succeeded
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON encoding failed with error: " . json_last_error_msg());
}

// Initialize the cURL handle
$ch = curl_init($url);

// Set cURL options
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
]);

// Execute the request
$response = curl_exec($ch);

// Check whether the cURL request succeeded
if ($response === false) {
    die("cURL Error: " . curl_error($ch));
}

// Get the HTTP status code
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close the cURL handle
curl_close($ch);
// Decode the response data
$response_data = json_decode($response, true);
// Process the response
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" => "What is in this image?", "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

Install the required dependencies:
npm install axios
URL request example
import axios from 'axios';
async function callDashScope() {
    // If no environment variable is configured, replace the following with your Model Studio API key: apiKey='sk-xxx'. Do not hardcode the API key in production to reduce the risk of leakage.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';//Replace with the actual application ID

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

    const data = {
        input: {
            prompt: "What is this",
            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: "What is in this image?", 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)
    {
        // If no environment variable is configured, replace the following with your Model Studio API key: apiKey="sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
        string appId = "APP_ID";// Replace with the actual application ID

        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("Make sure DASHSCOPE_API_KEY is set.");
            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"": ""What is this"",
                    ""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"": ""What is in this image?"", ""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() {
	// If no environment variable is configured, replace the following with your Model Studio API key: apiKey := "sk-xxx". Do not hardcode the API key in production to reduce the risk of leakage.
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // Replace with the actual application ID

	if apiKey == "" {
		fmt.Println("Make sure DASHSCOPE_API_KEY is set.")
		return
	}

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

	// Create the request body
	requestBody := map[string]interface{}{
		"input": map[string]interface{}{
			"prompt":     "What is this",
			"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
	}

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

	// Set the request headers
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	// Send the request
	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()

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

	// Process the response
	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": "What is in this image?", "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_code string

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_id string

The unique identifier of this call.

The Java SDK returns this parameter as requestId.

code string

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

message string

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

output object

The call result information.

output Properties

text string

The reply content generated by the model.

finish_reason string

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

thought string

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_type string

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_name string

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

action string

The executed step.

action_input_stream string

The streaming result of the input parameters.

action_input string

The input parameters of the plugin.

observation string

The retrieval or plugin process.

doc_references array

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_id string

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

title string

The title of the text chunk cited by the model.

doc_id string

The document ID cited by the model.

doc_name string

The document name cited by the model.

doc_url string

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.

text string

The specific text content cited by the model.

biz_id string

The business association identifier cited by the model.

images array

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.

usage object

The data usage information of this request.

usage Properties

modelsarray

The model information of this call.

models Properties

model_id string

The model ID invoked by this application call.

input_tokens integer

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

output_tokens integer

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": "I am Qwen, an AI assistant developed by Alibaba Cloud. I am designed to answer questions, provide information, and converse with users. How can I help you?"
    },
    "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": "Based on your budget, I recommend the Model Studio Zephyr Z9. This phone is light and portable, with a 6.4-inch 1080 x 2340 pixel screen, 128GB storage, and 6GB RAM, making it ideal for daily use <ref>[1]</ref>. It also has a 4000mAh battery and a 30x digital zoom lens that captures distant details. The price range is 2,499-2,799 yuan, which fully meets your budget <ref>[1]</ref>.",
    "finish_reason": "stop",
    "session_id": "6c1d47fa5eca46b2ad0668c04ccfbf13",
    "thoughts": null,
    "doc_references": [
        {
            "index_id": "1",
            "title": "Model Studio phone product introduction",
            "doc_id": "file_7c0e9abee4f142f386e488c9baa9cf38_10317360",
            "doc_name": "Model Studio phone product introduction",
            "doc_url": null,
            "text": "[Document name]: Model Studio phone product introduction\n[Title]: Model Studio phone product introduction\n[Body]: Reference price: 5,999-6,499. Model Studio Ace Ultra - for gamers: features a 6.67-inch 1080 x 2400 pixel screen, 10GB RAM, and 256GB storage for smooth gaming. A 5500mAh battery with liquid cooling keeps it cool during long sessions. High-dynamic dual speakers enhance the gaming experience. Reference price: 3,999-4,299. Model Studio Zephyr Z9 - light and portable: a 6.4-inch 1080 x 2340 pixel design with 128GB storage and 6GB RAM handles daily use with ease. A 4000mAh battery lasts all day, and a 30x digital zoom lens captures distant details. Reference price: 2,499-2,799. Model Studio Flex Fold+ - a new era of foldable screens: a 7.6-inch 1800 x 2400 main screen and a 4.7-inch 1080 x 2400 outer screen, with multi-angle free-stop design for different scenarios. 512GB storage, 12GB RAM, a 4700mAh battery, and UTG ultra-thin flexible glass open a new chapter for foldables. It also supports dual SIM and satellite calling for connectivity worldwide. Reference retail price: 9,999-10,999.\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.