New agent application API

更新时间:
复制 MD 格式

This topic covers the input and output parameters for using the DashScope API to call the new agent application in Alibaba Cloud Model Studio.

Related guide: Agent 2.0.

Important

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

Prerequisites

Before you begin, ensure you complete the following:

  1. Create an application: Go to application management, create a new agent application in Model Studio, and record the application ID.

  2. Get an API Key: Obtain an API Key from key management and configure the API Key as an environment variable.

  3. Install the SDK (optional): Install the DashScope SDK for your programming language.

Invocation method

  • HTTP API invocation

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

    Replace APP_ID with your actual application ID.
  • SDK invocation

    The Python and Java SDKs use the correct endpoint by default.

    To set a custom endpoint, use the base_url parameter.

Online debugging: Go to application card -> publish -> API debugging, enter the parameters, and click run.

Request body

Single-turn

Python

Request example

import os
from http import HTTPStatus
from dashscope import Application
response = Application.call(
    # If not using an environment variable, set your API key directly (e.g., api_key="sk-xxx").
    # For security, we recommend using environment variables instead of hardcoding keys.
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    app_id='APP_ID',  # Replace with your application ID.
    prompt='Who are you?')

if response.status_code != HTTPStatus.OK:
    print(f'request_id={response.request_id}')
    print(f'code={response.status_code}')
    print(f'message={response.message}')
    print(f'Refer to the documentation: https://help.aliyun.com/en/model-studio/developer-reference/error-code')
else:
    print(response.output.text)

Java

Request example

// We recommend using Dashscope SDK version >= 2.12.0.
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;

public class Main {
    public static void appCall()
            throws ApiException, NoApiKeyException, InputRequiredException {
        ApplicationParam param = ApplicationParam.builder()
                // If not using an environment variable, set your API key directly (e.g., .apiKey("sk-xxx")).
                // For security, we recommend using environment variables instead of hardcoding keys.
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .appId("APP_ID") // Replace with your application 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("Refer to the documentation: https://help.aliyun.com/en/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 your application ID.

PHP

Request example

<?php

# If not using an environment variable, set your API key directly (e.g., $api_key="sk-xxx").
# For security, we recommend using environment variables instead of hardcoding keys.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Replace with your application ID.

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

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

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

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

// Initialize a cURL session
$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 if the cURL execution was successful
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 session
curl_close($ch);
// Decode the response data
$response_data = json_decode($response, true);
// Handle 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 dependency:

npm install axios

Request example

const axios = require('axios');

async function callDashScope() {
    // If not using an environment variable, set your API key directly (e.g., apiKey='sk-xxx').
    // For security, we recommend using environment variables instead of hardcoding keys.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';// Replace with your 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 not using an environment variable, set your API key directly (e.g., apiKey="sk-xxx"). 
        // For security, we recommend using environment variables instead of hardcoding keys.
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
        string appId = "APP_ID"; // Replace with your 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 not using an environment variable, set your API key directly (e.g., apiKey := "sk-xxx").
	// For security, we recommend using environment variables instead of hardcoding keys.
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // Replace with your application ID.

	if apiKey == "" {
		fmt.Println("Ensure the DASHSCOPE_API_KEY environment variable 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 an 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 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
	}

	// Handle 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))
	}
}

Multi-turn

For multi-turn conversations, use a session_id to maintain the conversation context:

1. First request: Do not include a session_id. The API returns a new session_id in the response.

2. Subsequent requests: Include the session_id from the previous response to continue the conversation.

3. Validity period: The session_id expires after 1 hour of inactivity.

Python

Request example

import os
from http import HTTPStatus
from dashscope import Application
def call_with_session():
    response = Application.call(
        # If not using an environment variable, set your API key directly (e.g., api_key="sk-xxx").
        # For security, we recommend using environment variables instead of hardcoding keys.
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        app_id='APP_ID',  # Replace with your application ID.
        prompt='Who are you?')

    if response.status_code != HTTPStatus.OK:
        print(f'request_id={response.request_id}')
        print(f'code={response.status_code}')
        print(f'message={response.message}')
        print(f'Refer to the documentation: https://help.aliyun.com/en/model-studio/developer-reference/error-code')
        return response

    responseNext = Application.call(
                # If not using an environment variable, set your API key directly (e.g., api_key="sk-xxx").
                # For security, we recommend using environment variables instead of hardcoding keys.
                api_key=os.getenv("DASHSCOPE_API_KEY"),
                app_id='APP_ID',  # Replace with your application ID.
                prompt='What are your skills?',
                session_id=response.output.session_id)  # The session_id from the previous response.

    if responseNext.status_code != HTTPStatus.OK:
        print(f'request_id={responseNext.request_id}')
        print(f'code={responseNext.status_code}')
        print(f'message={responseNext.message}')
        print(f'Refer to the documentation: https://help.aliyun.com/en/model-studio/developer-reference/error-code')
    else:
        print('%s\n session_id=%s\n' % (responseNext.output.text, responseNext.output.session_id))
        # print('%s\n' % (response.usage))

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 not using an environment variable, set your API key directly (e.g., .apiKey("sk-xxx")).
                // For security, we recommend using environment variables instead of hardcoding keys.
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // Replace with your 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 are your skills?");
        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("Refer to the documentation: https://help.aliyun.com/en/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}

HTTP

curl

Request example (first 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 are your skills?",
        "session_id":"4f8ef7233dc641aba496cb201fa59f8c"
    },
    "parameters":  {},
    "debug": {}
}' 

PHP

Request example (first turn)

<?php
# If not using an environment variable, set your API key directly (e.g., $api_key="sk-xxx").
# For security, we recommend using environment variables instead of hardcoding keys.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Replace with your application ID.

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

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

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

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

// Initialize a cURL session
$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 if the cURL execution was successful
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 session
curl_close($ch);
// Decode the response data
$response_data = json_decode($response, true);
// Handle 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 not using an environment variable, set your API key directly (e.g., $api_key="sk-xxx").
# For security, we recommend using environment variables instead of hardcoding keys.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Replace with your application ID.

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

// Construct the request data
$data = [
    "input" => [
        'prompt' => 'What are your skills?',
        // Replace with the session_id from the previous turn.
        'session_id' => '2e658bcb514f4d30ab7500b4766a8d43'
    ]
];

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

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

// Initialize a cURL session
$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 if the cURL execution was successful
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 session
curl_close($ch);
// Decode the response data
$response_data = json_decode($response, true);
// Handle 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 dependency:

npm install axios

Request example (first turn)

const axios = require('axios');

async function callDashScope() {
    // If not using an environment variable, set your API key directly (e.g., apiKey='sk-xxx').
    // For security, we recommend using environment variables instead of hardcoding keys.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';// Replace with your 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 not using an environment variable, set your API key directly (e.g., apiKey='sk-xxx').
    // For security, we recommend using environment variables instead of hardcoding keys.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';// Replace with your application ID.

    const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
    // Replace with the session_id from the previous turn.
    const data = {
        input: {
            prompt: "What are your skills?",
            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 (first turn)

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

class Program
{
    static async Task Main(string[] args)
    {
        // If not using an environment variable, set your API key directly (e.g., apiKey="sk-xxx"). 
        // For security, we recommend using environment variables instead of hardcoding keys.
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
        string appId = "APP_ID"; // Replace with your 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 not using an environment variable, set your API key directly (e.g., apiKey="sk-xxx"). 
        // For security, we recommend using environment variables instead of hardcoding keys.
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
        string appId = "APP_ID"; // Replace with your 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 are your skills?"",
                    ""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 (first turn)

package main

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

func main() {
	// If not using an environment variable, set your API key directly (e.g., apiKey := "sk-xxx").
	// For security, we recommend using environment variables instead of hardcoding keys.
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // Replace with your application ID.

	if apiKey == "" {
		fmt.Println("Ensure the DASHSCOPE_API_KEY environment variable 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 an 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 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
	}

	// Handle 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 not using an environment variable, set your API key directly (e.g., apiKey := "sk-xxx").
	// For security, we recommend using environment variables instead of hardcoding keys.
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // Replace with your application ID.

	if apiKey == "" {
		fmt.Println("Ensure the DASHSCOPE_API_KEY environment variable 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 are your skills?",
			"session_id": "f7eea37f0c734c20998a021b688d6de2", // Replace with the 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 an 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 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
	}

	// Handle 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 your application ID. For subsequent turns, use the session_id returned in the previous response.

Streaming output

Use stream to enable streaming output.

Python

Request example

import os
from http import HTTPStatus
from dashscope import Application
responses = Application.call(
            # If not using an environment variable, set your API key directly (e.g., api_key="sk-xxx").
            # For security, we recommend using environment variables instead of hardcoding keys.
            api_key=os.getenv("DASHSCOPE_API_KEY"), 
            app_id='APP_ID', # Replace with your application ID.
            prompt='Who are you?',
            stream=True,  # Enable streaming output.
            incremental_output=True)  # Enable incremental output.

for response in responses:
    if response.status_code != HTTPStatus.OK:
        print(f'request_id={response.request_id}')
        print(f'code={response.status_code}')
        print(f'message={response.message}')
        print(f'Refer to the documentation: https://help.aliyun.com/en/model-studio/developer-reference/error-code')
    else:
        print(f'{response.output.text}\n')  # Process the text-only output.

Java

Request example

// We recommend using Dashscope SDK version >= 2.15.0.
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import io.reactivex.Flowable;// For streaming output.
// Implement streaming output for agent application calls.

public class Main {
    public static void streamCall() throws NoApiKeyException, InputRequiredException {
        ApplicationParam param = ApplicationParam.builder()
                // If not using an environment variable, set your API key directly (e.g., .apiKey("sk-xxx")).
                // For security, we recommend using environment variables instead of hardcoding keys.
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // Replace with your application ID.
                .appId("APP_ID")
                .prompt("Who are you?")
                // Enable incremental output.
                .incrementalOutput(true)
                .build();
        Application application = new Application();
        // Use .streamCall() for streaming output.
        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("Refer to the documentation: https://help.aliyun.com/en/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 your application ID.

PHP

Request example

<?php

// If not using an environment variable, set your API key directly (e.g., $api_key="sk-xxx").
// For security, we recommend using environment variables instead of hardcoding keys.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Replace with your application ID.

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

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

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

// Initialize a cURL session
$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 the streaming data.
    return strlen($string);
});
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $api_key,
    'X-DashScope-SSE: enable' // Enable streaming output.
]);

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

// Check if the cURL execution was successful
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 session
curl_close($ch);

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

Node.js

Install the required dependency:

npm install axios

Request example

1. Output the full response

const axios = require('axios');

async function callDashScope() {
    // If not using an environment variable, set your API key directly (e.g., apiKey='sk-xxx').
    // For security, we recommend using environment variables instead of hardcoding keys.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';// Replace with your application ID.

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

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

        if (response.status === 200) {
            // Handle 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();

Expand the following panel to view the content:

2. Output only the content of the text field

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

async function callDashScope() {
    // If not using an environment variable, set your API key directly (e.g., apiKey='sk-xxx').
    // For security, we recommend using environment variables instead of hardcoding keys.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID'; // Replace with your application ID.

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

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

        if (response.status === 200) {
            // Transform stream to parse the SSE protocol for streaming responses.
            const sseTransformer = new Transform({
                transform(chunk, encoding, callback) {
                    this.buffer += chunk.toString();
                    
                    // Split by SSE events (two newline characters).
                    const events = this.buffer.split(/\n\n/);
                    this.buffer = events.pop() || ''; // Keep any incomplete part.
                    
                    events.forEach(eventData => {
                        const lines = eventData.split('\n');
                        let textContent = '';
                        
                        // Parse 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 parsing error:', e.message);
                                }
                            }
                        });

                        if (textContent) {
                            // Add a newline and push it.
                            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 newlines.
                })
                .on('end', () => console.log(""))
                .on('error', err => console.error("Pipe error:", err));

        } else {
            console.log("Request failed with 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 not using an environment variable, set your API key directly (e.g., apiKey="sk-xxx").
        // For security, we recommend using environment variables instead of hardcoding keys.
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
        string appId = "APP_ID"; // Replace with your 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 not using an environment variable, set your API key directly (e.g., apiKey := "sk-xxx").
	// For security, we recommend using environment variables instead of hardcoding keys.
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // Replace with your application ID.

	if apiKey == "" {
		fmt.Println("Ensure the DASHSCOPE_API_KEY environment variable is set.")
		return
	}

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

	// Create the request body, where incremental_output enables the streaming response.
	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 an 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 request headers. Set X-DashScope-SSE to "enable" to enable the streaming response.
	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
	}

	// Handle 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
		}
	}
}

File Q&A

Pass the URLs of your files, such as documents, images, and videos, in the file_list parameter to enable the file Q&A feature.

Application configuration: Enable the Pre-parse Files switch in your application.

Python

Request example

# The Dashscope SDK version must be 1.24.7 or later.
import os
from http import HTTPStatus
from dashscope import Application

responses = Application.call(
    # If you have not configured an environment variable for your API key, replace the next line with api_key="sk-xxx". For security, do not hardcode your API Key in production code.
    api_key=os.getenv("DASHSCOPE_API_KEY"), 
    app_id='YOUR_APP_ID',  # Replace YOUR_APP_ID with your application ID
    prompt='Summarize the file content in one sentence',
    stream=True,  # Streaming output
    incremental_output=True, # Incremental output
    file_list=["https://dashscope.oss-cn-beijing.aliyuncs.com/audios/welcome.mp3"],  
)

for response in responses:
    if response.status_code != HTTPStatus.OK:
        print(f'request_id={response.request_id}')
        print(f'code={response.status_code}')
        print(f'message={response.message}')
        print(f'For more information, see https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
    else:
        print('%s\n' % (response.output.text)) 

Response example

This file is a short welcome
message that says, "Welcome
 to Alibaba Cloud."

Java

Request example

// The Dashscope SDK version must be 2.21.13 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;
import java.util.Collections;
import java.util.List;

public class Main {
    public static void appCall() throws NoApiKeyException, InputRequiredException {
        ApplicationParam param = ApplicationParam.builder()
                // If you have not configured an environment variable for your API key, replace the next line with .apiKey("sk-xxx"). For security, do not hardcode your API Key in production code.
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .appId("YOUR_APP_ID") // Replace with your actual application ID
                .prompt("Summarize the file content in one sentence")
                .files(Arrays.asList(
                        "https://dashscope.oss-cn-beijing.aliyuncs.com/audios/welcome.mp3"))
                .build();

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

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

Response example

This file is a short welcome message that says, "Welcome to Alibaba Cloud."

curl

Request example

curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/{YOUR_APP_ID}/completion \
        --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
        --header 'Content-Type: application/json' \
        --data '{
        "input": {
            "prompt": "Summarize the file content in one sentence",
            "file_list":["https://dashscope.oss-cn-beijing.aliyuncs.com/audios/welcome.mp3"]
        },
        "debug": {}
        }'

Response example

{
    "output": {
        "finish_reason": "stop",
        "reject_status": false,
        "session_id": "545547dddcbf4296af0173da1a6e5a74",
        "text": "This file is a welcome message from Alibaba Cloud that says, \"Welcome to Alibaba Cloud.\""
    },
    "usage": {
        "models": [
            {
                "input_tokens": 103,
                "model_id": "qwen-plus-latest",
                "output_tokens": 304
            }
        ]
    },
    "request_id": "6900cfac-0aa5-4c6e-aa9c-7a69f7b4d5bc"
}

Visual understanding

Enable the visual understanding feature by passing an image URL or a Base64-encoded Data URL to the image_list parameter. The application must use the Image and Video Understanding model.

Note

To use a local image, encode it into a Base64 string and construct a Data URL in the data:[MIME_type];base64,{base64_image} format. The MIME_type must match the image format. For example, use image/png for PNG, image/jpeg for JPEG, and image/webp for WebP.

Python

URL request example

import os
from http import HTTPStatus
# Use dashscope SDK version 1.20.14 or later.
from dashscope import Application
response = Application.call(
    # If the environment variable is not set, replace the next line with api_key="sk-xxx" using your Model Studio API Key.
    # Do not hardcode the API Key in production code to avoid security risks.
    api_key=os.getenv("DASHSCOPE_API_KEY"), 
    app_id='APP_ID',  # Replace APP_ID with your application ID.
    prompt='What is this?',
    image_list=['https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg'],
)

if response.status_code != HTTPStatus.OK:
    print(f'request_id={response.request_id}')
    print(f'code={response.status_code}')
    print(f'message={response.message}')
    print(f'For more information, see https://help.aliyun.com/en/model-studio/developer-reference/error-code')
else:
    print('%s\n' % (response.output.text))  # Process and output only the text.
    # print('%s\n' % (response.usage))

Base64 encoding example

import os
import base64
from http import HTTPStatus
from dashscope import Application

# Encode the local image into 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.

# Construct the Data URL. Note: The MIME type must match the image format.
data_url = f"data:image/jpeg;base64,{base64_image}"

# Call the application API.
response = Application.call(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    app_id='APP_ID',  # Replace APP_ID with your application ID.
    prompt='What is in this image?',
    image_list=[data_url],  # Use the Data URL.
)

if response.status_code != HTTPStatus.OK:
    print(f'request_id={response.request_id}')
    print(f'code={response.status_code}')
    print(f'message={response.message}')
    print(f'For more information, see https://help.aliyun.com/en/model-studio/developer-reference/error-code')
else:
    print('%s\n' % (response.output.text))

Java

URL request example

// Use 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 the environment variable is not set, replace the next line with .apiKey("sk-xxx") using your Model Studio API Key.
                // Do not hardcode the API Key in production code to avoid security risks.
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .appId("APP_ID") // Replace with your 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());// Process and output only the text.
    }

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

Base64 encoding example

// Use 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 into 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.

        // Construct the Data URL. Note: 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 your 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("For more information, see https://help.aliyun.com/en/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 into a Base64 string.
base64_image=$(base64 -i /path/to/your/image.jpeg)  # macOS/Linux

# Construct the Data URL. Note: 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 the environment variable is not set, replace the next line with $api_key="sk-xxx" using your Model Studio API Key.
# Do not hardcode the API Key in production code to avoid security risks.
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Replace with your actual application ID.

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

// Construct 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 if json_encode was successful.
if (json_last_error() !== JSON_ERROR_NONE) {
    die("JSON encoding failed with error: " . json_last_error_msg());
}

// Initialize a cURL session.
$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 if the cURL execution was successful.
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 session.
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 dependency:

npm install axios

URL request example

import axios from 'axios';
async function callDashScope() {
    // If the environment variable is not set, replace the next line with apiKey='sk-xxx' using your Model Studio API Key.
    // Do not hardcode the API Key in production code to avoid security risks.
    const apiKey = process.env.DASHSCOPE_API_KEY;
    const appId = 'APP_ID';// Replace with your 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 the environment variable is not set, replace the next line with apiKey="sk-xxx" using your Model Studio API Key.
        // Do not hardcode the API Key in production code to avoid security risks.
        string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");;
        string appId = "APP_ID";// Replace with your actual application ID.
        
        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("Make sure the DASHSCOPE_API_KEY environment variable 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 the environment variable is not set, replace the next line with apiKey := "sk-xxx" using your Model Studio API Key.
	// Do not hardcode the API Key in production code to avoid security risks.
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	appId := "APP_ID" // Replace with your actual application ID.

	if apiKey == "" {
		fmt.Println("Make sure the DASHSCOPE_API_KEY environment variable 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 an 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))
}

Pass custom parameters

Pass custom parameters using biz_params. For more information, see Call an agent application - Pass custom parameters.

Python

Request example

import os
from http import HTTPStatus
# Use dashscope SDK version 1.14.0 or later.
from dashscope import Application
biz_params = {
    # Pass custom input parameters for the agent application's tool. Replace <TOOL_ID> with your tool ID.
    "user_defined_params": {
        "<TOOL_ID>": {
            "article_index": 2}}}
response = Application.call(
        # If the environment variable is not set, replace the next line with api_key="sk-xxx". Avoid hardcoding the API Key in production to reduce security risks.
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        app_id='APP_ID',
        prompt='Dormitory rules',
        biz_params=biz_params)

if response.status_code != HTTPStatus.OK:
    print(f'request_id={response.request_id}')
    print(f'code={response.status_code}')
    print(f'message={response.message}')
    print(f'For more information, see https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
else:
    print('%s\n' % (response.output.text))

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 input parameters for the agent application's tool. Replace <TOOL_ID> with your tool ID.
                "{\"user_defined_params\":{\"<TOOL_ID>\":{\"article_index\":2}}}";
        ApplicationParam param = ApplicationParam.builder()
                // If the environment variable is not set, replace the next line with .apiKey("sk-xxx"). Avoid hardcoding the API Key in production to reduce security risks.
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .appId("APP_ID")
                .prompt("Dormitory rules")
                .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("For more information, see https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
        }
        System.exit(0);
    }
}

HTTP

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 rules",
        "biz_params":
        {
            "user_defined_params":
            {
                "<TOOL_ID>":
                    {
                    "article_index": 2
                    }
            }
        }
    },
    "parameters":  {},
    "debug":{}
}'
Replace APP_ID with your application ID. Replace <TOOL_ID> with your tool ID.

app_id string (Required)

The application ID.

Obtain this from the application card in Application Management.

In the Java SDK, this parameter is appId. For HTTP calls, replace APP_ID in the URL with your application ID.

prompt string (Required)

The user input that guides the application's response.

For HTTP calls, place the prompt in the input object.

session_id string (Optional)

The identifier for the conversation history.

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

This ID expires after 1 hour of inactivity.

In the Java SDK, use setSessionId. For HTTP calls, place the session_id in the input object.

workspace string (Optional)

The workspace identifier. For more information, see Obtain Workspace ID.

You need to pass the workspace ID only when you call an application in a sub-workspace.

For HTTP calls, specify the X-DashScope-WorkSpace header.

stream boolean (Optional, default: false)

Specifies whether to stream the response.

We recommend that you set this to true to improve the reading experience and reduce the risk of timeouts.

Valid values:

  • false (default): The full response is returned only after generation is complete.

  • true (recommended): The response is streamed in chunks as it is generated. You must assemble these chunks to form the complete response.

To enable streaming output with the Java SDK, use the streamCall interface. For HTTP calls, set the X-DashScope-SSE header to enable.

incremental_output boolean (Optional, default: false)

Specifies whether to enable incremental output in streaming output mode.

We recommend setting this to true to improve the reading experience.

Valid values:

  • false (default): Each output contains the entire sequence generated so far. The final output is the complete result.

    I
    I like
    I like apple
    I like apple.
  • true (recommended): Each chunk contains only new content. You must concatenate the chunks to get the full result.

    I
     like
     apple
    .
In the Java SDK, this parameter is incrementalOutput. For HTTP calls, place incremental_output in the parameters object.

enable_thinking boolean (Optional, default: false)

This parameter toggles between thinking and non-thinking modes for deep-thinking models.

Valid values:

  • False (default): Non-thinking mode. The final answer is returned directly in the text field.

  • True: Enables thinking mode. The model first outputs its thinking process and then returns the final answer.

Priority:

  • If this parameter is not set in the API call, the thinking mode setting configured for the model in the application is used.

  • If enable_thinking is set in the call, the API parameter takes precedence.

Important

To obtain the content of the thinking process, you must set has_thoughts to True:

  1. The thinking process is retrieved from the thought field.

  2. The final answer is obtained from the text field.

Enabling enable_thinking may not always output the thinking process.
In the Java SDK, this parameter is enableThinking. For HTTP calls, place enable_thinking in the parameters object.
Requires Java Dashscope SDK version 2.20.0 or later.

has_thoughts boolean (Optional, default: false)

Specifies whether to output the thinking process of a model that has thinking mode enabled. The process is returned in the thoughts field.

Valid values:

  • True: Output the process.

  • False (default): Do not output the process.

In the Java SDK, this parameter is hasThoughts. For HTTP calls, place has_thoughts in the parameters object.

image_list array (Optional)

A list of images. This parameter supports image URLs and Data URLs (Base64-encoded). The application must use an Image and Video Understanding model.

The base64 encoding format can be constructed as a Data URL: data:[MIME_type];base64,{base64_image}. For a detailed description and code examples, see the Visual Understanding section.

In the Java SDK, this parameter is images. For HTTP calls, place image_list in the input object.

file_list array (Optional)

A list of file URLs.

In the Java SDK, this parameter is files. For HTTP calls, place file_list in the input object.
Requires Python Dashscope SDK version 1.24.7 or later, or Java Dashscope SDK version 2.21.13 or later.

model_id string (Optional)

The model name.

You can use this parameter to specify the model to be used for the current API call.

Priority: If the model_id passed through the API is different from the one configured in the console, the API parameter value takes precedence.

In the Java SDK, this parameter is modelId. For HTTP calls, place model_id in the parameters object.
Requires Java Dashscope SDK version 2.19.3 or later.

Response object

Example success response

{
    "status_code": 200,
    "request_id": "fdfc3182-bc9d-4b45-a287-cd83b13aca02",
    "code": "",
    "message": "",
    "output": {
        "text": "Hello! I am Qianwen, a large-scale language model from Alibaba Group. I can help you answer questions, create text such as stories, official documents, emails, and scripts, perform logical reasoning, write code, and more. How can I help you?",
        "finish_reason": "stop",
        "session_id": "cbb2e26ac4cc4cc3b2d114e1f73c127e",
        "thoughts": null,
        "doc_references": null,
        "workflow_message": null
    },
    "usage": {
        "models": [
            {
                "model_id": "qwen-plus-latest",
                "input_tokens": 142,
                "output_tokens": 296
            }
        ]
    }
}

Example error response

If a request fails, the code and message fields indicate the reason for the error.

The following example shows an error response when an invalid API-KEY is provided.

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

status_code string

The status code of the response.

A value of 200 indicates that the request was successful. Other values indicate that the request failed.

If the request fails, use code to get the error code and message to get the error message.

The Java SDK does not return this parameter. If the call fails, the SDK throws an exception. The exception includes the status_code value.

request_id string

A unique identifier for this call.

In the Java SDK, this parameter is returned as requestId.

code string

The error code. This field is empty if the call is successful.

Only the Python SDK returns this parameter.

message string

A detailed error message. This field is empty if the request is successful.

Only the Python SDK returns this parameter.

output object

The result of the request.

output properties

text string

The content generated by the model.

finish_reason string

The reason the generation stopped.

stop indicates a natural stop (a predefined stop sequence). null indicates a forced stop (for example, the maximum length limit is reached or the generation is manually stopped).

session_id string

A unique identifier for the current conversation.

Pass this ID in subsequent requests to include the conversation history.

thoughts array

When you make a call, set the has_thoughts parameter to True to view the the thinking process of the Deep Thinking Model in thoughts.

thoughts properties

thought string

The thinking process of the model.

Procedure

  1. In the console, select the Deep Thinking Model for your application and publish it.

  2. Set the has_thoughts parameter to true in your API call.

action_type string

The type of action performed by the model. For example, reasoning indicates the thinking process of the Deep Thinking Model.

action_name string

The name of the action being executed, such as the thinking process.

action string

The step being executed.

action_input_stream string

The streaming input for the action.

action_input string

The input for the action.

usage object

Usage details for this request.

usage properties

models array

Information about the model used in this call.

models properties

model_id string

The ID of the model used for the request.

input_tokens integer

The length, in tokens, of the user input text.

output_tokens integer

The length, in tokens, of the model output.

QPM limit

The default QPM limit per application is 15,000.

Error codes

If a call fails, refer to the error codes for a solution.