新版智能体应用 API 参考

本文介绍 DashScope API 调用阿里云百炼新版智能体应用的输入与输出参数,并提供典型场景下的调用示例。

相关指南:新版智能体应用(Agent 2.0)

重要

本文档仅适用于中国大陆版(北京地域)。

调用方式

  • HTTP 接口调用

    请求地址:POST https://dashscope.aliyuncs.com/api/v1/apps/APP_ID/completion

    其中 APP_ID 需替换为您的实际应用 ID。
  • SDK 调用

    Python/Java SDK:已默认配置正确的 endpoint

    自定义 endpoint:可通过 base_url 参数配置

前置准备

开始前,请确保您已完成以下操作:

  1. 创建应用:前往应用管理创建阿里云百炼新版智能体应用并获取应用 ID;

  2. 获取 API Key:通过密钥管理获取,并配置API Key到环境变量

  3. 安装SDK(可选):若使用 SDK 调用,请安装相应语言的DashScope SDK

请求体

单轮对话

Python

请求示例

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

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'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
else:
    print(response.output.text)

Java

请求示例

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

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

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

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

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

HTTP

curl

请求示例

curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "prompt": "你是谁?"
    },
    "parameters":  {},
    "debug": {}
}' 
APP_ID替换为实际的应用 ID。

PHP

请求示例

<?php

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

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

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

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

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

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

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

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

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

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

Node.js

需安装相关依赖:

npm install axios

请求示例

const axios = require('axios');

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

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

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

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

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

callDashScope();

C#

请求示例

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

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

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

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

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

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

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

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

Go

请求示例

package main

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

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

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

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

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

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

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

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

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

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

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

多轮对话

多轮对话通过session_id维护会话上下文:

1. 首次请求:无需传入 session_id,响应中会返回新生成的session_id。

2. 后续请求:携带上一次响应的 session_id 即可延续对话。

3. 有效期:session_id 在最后一次请求后 1 小时内有效。

Python

请求示例

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

    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'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
        return response

    responseNext = Application.call(
                # 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
                api_key=os.getenv("DASHSCOPE_API_KEY"),
                app_id='APP_ID',  # 替换为实际的应用 ID
                prompt='你有什么技能?',
                session_id=response.output.session_id)  # 上一轮responsesession_id

    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'请参考文档:https://help.aliyun.com/zh/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

请求示例

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

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

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

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

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

HTTP

curl

请求示例(上一轮对话)

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

请求示例(下一轮对话)

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

PHP

请求示例(上一轮对话)

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

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

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

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

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

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

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

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

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

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

请求示例(下一轮对话)

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

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

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

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

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

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

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

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

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

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

Node.js

需安装相关依赖:

npm install axios

请求示例(上一轮对话)

const axios = require('axios');

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

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

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

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

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

请求示例(下一轮对话)

const axios = require('axios');

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

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

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

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

C#

请求示例(上一轮对话)

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

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

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

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

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

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

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

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

请求示例(下一轮对话)

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

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

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

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

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

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

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

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

Go

请求示例(上一轮对话)

package main

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

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

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

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

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

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

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

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

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

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

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

请求示例(下一轮对话)

package main

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

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

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

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

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

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

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

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

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

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

	// 处理响应
	if resp.StatusCode == http.StatusOK {
		fmt.Println("Request successful:")
		fmt.Println(string(body))
	} else {
		fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
		fmt.Println(string(body))
	}
}
APP_ID替换为实际的应用 ID。下一轮对话的输入参数session_id字段值替换为实际上一轮对话返回的session_id值。

流式输出

通过stream实现流式输出。

Python

请求示例

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

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'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
    else:
        print(f'{response.output.text}\n')  # 处理只输出文本text

Java

请求示例

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

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

HTTP

curl

请求示例

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

    },
    "parameters":  {
        "incremental_output":true
    },
    "debug": {}
}'
APP_ID替换为实际的应用 ID。

PHP

请求示例

<?php

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

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

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

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

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

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

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

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

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

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

Node.js

需安装相关依赖:

npm install axios

请求示例

1.输出完整响应

const axios = require('axios');

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

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

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

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

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

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

callDashScope();

可展开折叠面板查看具体内容:

2.只输出text字段内容

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

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

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

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

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

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

        if (response.status === 200) {
            // // 处理流式响应 SSE协议解析转换流
            const sseTransformer = new Transform({
                transform(chunk, encoding, callback) {
                    this.buffer += chunk.toString();
                    
                    // 按SSE事件分割(两个换行符)
                    const events = this.buffer.split(/\n\n/);
                    this.buffer = events.pop() || ''; // 保留未完成部分
                    
                    events.forEach(eventData => {
                        const lines = eventData.split('\n');
                        let textContent = '';
                        
                        // 解析事件内容
                        lines.forEach(line => {
                            if (line.startsWith('data:')) {
                                try {
                                    const jsonData = JSON.parse(line.slice(5).trim());
                                    if (jsonData.output?.text) {
                                        textContent = jsonData.output.text;
                                    }
                                } catch(e) {
                                    console.error('JSON解析错误:', e.message);
                                }
                            }
                        });

                        if (textContent) {
                            // 添加换行符并推送
                            this.push(textContent + '\n');
                        }
                    });
                    
                    callback();
                },
                flush(callback) {
                    if (this.buffer) {
                        this.push(this.buffer + '\n');
                    }
                    callback();
                }
            });
            sseTransformer.buffer = '';

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

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

callDashScope();

C#

请求示例

using System.Net;
using System.Text;

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

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

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

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

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

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

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

Go

请求示例

package main

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

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

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

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

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

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

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

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

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

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

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

文件问答

指定file_list传入文件(文档、图片、音视频)URL,启用文件问答功能。

应用配置:应用内需开启预解析文件开关。

Python

请求示例

# Dashscope SDK 的版本至少应为1.24.7
import os
from http import HTTPStatus
from dashscope import Application

responses = Application.call(
    # 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
    api_key=os.getenv("DASHSCOPE_API_KEY"), 
    app_id='YOUR_APP_ID',  # 应用ID替换YOUR_APP_ID
    prompt='一句话总结文件内容',
    stream=True,  # 流式输出
    incremental_output=True, # 增量输出
    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'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
    else:
        print('%s\n' % (response.output.text)) 

响应示例

该文件是一条简短的欢迎
信息,内容为"欢迎
与使用阿里云"。

Java

请求示例

// dashscope SDK 的版本 >= 2.21.13;
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()
                // 若没有配置环境变量,可用百炼API Key将下行替换为:.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .appId("YOUR_APP_ID") // 替换为实际的应用ID
                .prompt("一句话总结文件内容")
                .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());// 处理只输出文本text
    }

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

响应示例

该文件是一条简短的欢迎信息,内容为"欢迎与使用阿里云"。

curl

请求示例

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": "一句话总结文件内容",
            "file_list":["https://dashscope.oss-cn-beijing.aliyuncs.com/audios/welcome.mp3"]
        },
        "debug": {}
        }'

响应示例

{
    "output": {
        "finish_reason": "stop",
        "reject_status": false,
        "session_id": "545547dddcbf4296af0173da1a6e5a74",
        "text": "该文件是阿里云的欢迎提示,内容为\"欢迎与使用阿里云\"。"
    },
    "usage": {
        "models": [
            {
                "input_tokens": 103,
                "model_id": "qwen-plus-latest",
                "output_tokens": 304
            }
        ]
    },
    "request_id": "6900cfac-0aa5-4c6e-aa9c-7a69f7b4d5bc"
}

视觉理解

指定 image_list传入图像URL启用视觉理解功能。应用配置:应用内需使用视觉理解模型。

Python

请求示例

import os
from http import HTTPStatus
# 建议dashscope SDK 的版本 >= 1.20.14
from dashscope import Application
response = Application.call(
    # 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
    api_key=os.getenv("DASHSCOPE_API_KEY"), 
    app_id='APP_ID',  # 应用ID替换APP_ID
    prompt='这是什么',
    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'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
else:
    print('%s\n' % (response.output.text))  # 处理只输出文本text
    # print('%s\n' % (response.usage))

Java

请求示例

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

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

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

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

HTTP

curl

请求示例

curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/{APP_ID}/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "input": {
        "prompt": "这是什么",
        "image_list":["https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"]
    },
    "debug": {}
}'

PHP

请求示例

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

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

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

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

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

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

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

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

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

Node.js

需安装相关依赖:

npm install axios

请求示例

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

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

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

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

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

callDashScope();

C#

请求示例

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

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

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

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

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

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

Go

请求示例

package main

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

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

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

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

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

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

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

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

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

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

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

app_id string (必选)

应用标识。

应用管理的应用卡片上获取。

Java SDK中为 appId。通过 HTTP 调用时,请将实际的应用 ID 放入 URL 中,替换APP_ID

prompt string (必选)

用户的输入指令,用于指导应用生成回复。

通过 HTTP 调用时,请将 prompt 放入 input 对象中。

session_id string (可选)

历史对话标识。

传入session_id时,请求将自动携带云端存储的对话历史。此时必须传递prompt

该 ID 在连续 1 小时内无任何请求后将自动失效。

Java SDK 中为 setSessionId。通过 HTTP 调用时,请将 session_id 放入 input 对象中。

workspace string (可选)

业务空间标识。相关文档:获取Workspace ID

仅调用子业务空间的应用时需传递workspace ID

通过 HTTP 调用时,请指定Header中的 X-DashScope-WorkSpace

stream boolean(可选) 默认值为 false

是否以流式输出方式回复。

推荐设置为true,可提升阅读体验并降低超时风险。

参数值:

  • false(默认):模型生成全部内容后一次性返回;

  • true(推荐):边生成边输出,每生成一部分内容即返回一个数据块(chunk)。需实时逐个读取这些块以拼接完整回复。

通过Java SDK实现流式输出请通过streamCall接口调用;通过HTTP实现流式输出请在Header中指定X-DashScope-SSEenable

incremental_output boolean(可选)默认值为 false

流式输出模式下是否开启增量输出。

推荐设置为true,可提升阅读体验。

参数值:

  • false(默认):每次输出当前已经生成的整个序列,最后一次输出为生成的完整结果。

    I
    I like
    I like apple
    I like apple.
  • true(推荐):增量输出,即后续输出内容不包含已输出的内容。需要实时地逐个读取这些片段以获得完整的结果。

    I
    like
    apple
    .
Java SDK中为incrementalOutput通过HTTP调用时,请将incremental_output放入parameters对象中。

enable_thinking boolean (可选)默认值为 false

此参数用于在深度思考模型中切换思考模式和非思考模式。

参数值:

  • false(默认):非思考模式。直接返回最终答案(text字段)。

  • true:启用思考模式。模型先输出思考过程,再返回最终答案。

优先级:

  • 若调用时未设置此参数,以应用内模型的思考模式开关状态为准。

  • 若调用时设置了enable_thinking,以 API 参数为准。

重要

要获取思考过程的内容,必须同时将has_thoughts设为true,则:

  1. 思考过程:thought字段获取。

  2. 最终答案:text字段获取。

开启enable_thinking有极小概率不会输出思考过程。
Java SDK中为enableThinking。通过HTTP调用时,请将 enable_thinking 放入 parameters 对象中。
Java Dashscope SDK的版本至少应为2.20.0

has_thoughts boolean (可选)默认值为 false

是否输出已开启思考模式的模型思考过程,在thoughts字段中查看。

参数值:

  • True:输出。

  • False(默认):不输出。

Java SDK 中为 hasThoughts。通过 HTTP 调用时,请将 has_thoughts 放入 parameters 对象中。

image_list array (可选)

图片 URL 列表。

应用内需选择通义千问VL系列模型

Java SDK 中为 images。通过 HTTP 调用时,请将 image_list 放入 input 对象中。

file_list array (可选)

文件 URL 列表。

Java SDK中为 files。通过HTTP调用时,请将 file_list 放入 input 对象中。
Python Dashscope SDK 的版本至少应为1.24.7,Java Dashscope SDK的版本至少应为2.21.13。

model_id string (可选)

模型名称。

API 调用时,可通过此参数传递本次调用使用的模型名称

优先级:当通过 API 传递的model_id与控制台配置不同时,以 API 参数值为准。

Java SDK 中为 modelId。通过HTTP调用时,请将 model_id 放入 parameters 对象中。
Java Dashscope SDK 的版本至少应为2.19.3

响应对象

成功响应示例

{
    "status_code": 200,
    "request_id": "fdfc3182-bc9d-4b45-a287-cd83b13aca02",
    "code": "",
    "message": "",
    "output": {
        "text": "你好!我是通义千问,阿里巴巴集团旗下的超大规模语言模型。我可以帮助你回答问题、创作文字,比如写故事、写公文、写邮件、写剧本、逻辑推理、编程等等。有什么需要我帮忙的吗?",
        "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
            }
        ]
    }
}

异常响应示例

在访问请求出错的情况下,输出的结果中会通过 code 和 message 指明错误原因。

此处展示未传入正确API-KEY的异常响应示例。

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

status_code string

返回的状态码。

200表示请求成功,否则表示请求失败。

请求失败可通过code获取错误码、message获取错误详细信息。

Java SDK不会返回该参数。调用失败会抛出异常,异常信息为status_codemessage的内容。

request_id string

本次调用的唯一标识符。

Java SDK返回参数为requestId

code string

表示错误码,调用成功时为空值。

只有Python SDK返回该参数。

message string

表示错误详细信息,请求成功则忽略。

只有Python SDK返回该参数。

output object

调用结果信息。

output属性

text string

模型生成的回复内容。

finish_reason string

完成原因。

stop为自然结束(遇预设标记),null为强制中断(如达到最大长度限制或手动停止)。

session_id string

当前对话的唯一标识。

在后续请求中传入,可携带历史对话记录。

thoughts array

调用时将has_thoughts参数设置为True,即可在thoughts中查看深度思考模型的思考过程。

thoughts属性

thought string

模型的思考过程。

使用步骤

  1. 控制台应用内选择深度思考模型,并成功发布;

  2. API 调用时将 has_thoughts 参数设为 True

action_type string

大模型返回的执行步骤类型。如reasoning表示深度思考模型的思考过程。

action_name string

执行的action名称,如思考过程。

action string

执行的步骤。

action_input_stream string

入参的流式结果。

action_input string

输入参数。

usage object

表示本次请求使用的数据信息。

usage属性

models array

本次调用的模型信息。

models属性

model_id string

本次应用调用到的模型 ID。

input_tokens integer

用户输入文本转换成Token后的长度。

output_tokens integer

模型生成回复转换为Token后的长度。

错误码

如果调用失败并返回报错信息,请参阅错误信息进行解决。