应用调用

更新时间:2025-03-27 03:08:22

本文介绍调用百炼应用时的输入输出参数。

相关指南:请参考应用调用

调用方式

您可以使用DashScope SDKHTTP接口调用百炼的应用(智能体、工作流或智能体编排)。

如果您在应用内选择了DeepSeek大语言模型,请参见DeepSeek系列模型应用调用

您可以通过本文默认的公网终端节点https://dashscope.aliyuncs.com/api/v1/访问百炼平台,也可以通过私网终端节点访问百炼平台以提高数据传输的安全性及传输效率。

您需要已创建百炼应用获取API Key配置API Key到环境变量。如果通过SDK调用,还需要安装DashScope SDK

请求体

请求示例

单轮对话
多轮对话
参数传递
流式输出
检索知识库
长期记忆
上传文件
Python
Java
HTTP

请求示例

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='YOUR_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)

请求示例

// 建议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("YOUR_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);
    }
}
curl
PHP
Node.js
C#
Go

请求示例

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": "你是谁?"
    },
    "parameters":  {},
    "debug": {}
}' 
YOUR_APP_ID替换为实际的应用 ID。

请求示例

<?php

# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_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";}
}
?>

需安装相关依赖:

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 = 'YOUR_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();

请求示例

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 = "YOUR_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}");
            }
        }
    }
}

请求示例

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 := "YOUR_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_idmessages实现。更多用法请参阅多轮对话

目前仅智能体应用对话型工作流应用支持多轮对话。
Python
Java
HTTP

请求示例

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='YOUR_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='YOUR_APP_ID',  # 替换为实际的应用 ID
                prompt='你有什么技能?',
                session_id=response.output.session_id)  # 上一轮response的session_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()

请求示例

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("YOUR_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);
    }
}
curl
PHP
Node.js
C#
Go

请求示例(上一轮对话)

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": "你是谁?"
    },
    "parameters":  {},
    "debug": {}
}' 

请求示例(下一轮对话)

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": "你有什么技能?",
        "session_id":"4f8ef7233dc641aba496cb201fa59f8c"
    },
    "parameters":  {},
    "debug": {}
}' 

请求示例(上一轮对话)

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

需安装相关依赖:

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 = 'YOUR_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 = 'YOUR_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();

请求示例(上一轮对话)

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 = "YOUR_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 = "YOUR_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}");
            }
        }
    }
}

请求示例(上一轮对话)

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 := "YOUR_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 := "YOUR_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))
	}
}
YOUR_APP_ID替换为实际的应用 ID。下一轮对话的输入参数session_id字段值替换为实际上一轮对话返回的session_id值。

参数传递通过biz_params实现。更多用法请参阅自定义参数的传递方法

Python
Java
HTTP

请求示例

import os
from http import HTTPStatus
# 建议dashscope SDK 的版本 >= 1.14.0
from dashscope import Application
biz_params = {
    # 智能体应用的自定义插件输入参数传递,自定义的插件ID替换your_plugin_code
    "user_defined_params": {
        "your_plugin_code": {
            "article_index": 2}}}
response = Application.call(
        # 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        app_id='YOUR_APP_ID',
        prompt='寝室公约内容',
        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'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
else:
    print('%s\n' % (response.output.text))  # 处理只输出文本text
    # print('%s\n' % (response.usage))

请求示例

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

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

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

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

请求示例

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": "寝室公约内容",
        "biz_params": 
        {
            "user_defined_params":
            {
                "{your_plugin_code}":
                    {
                    "article_index": 2
                    }
            }
        } 
    },
    "parameters":  {},
    "debug":{}
}'
YOUR_APP_ID替换为实际的应用 ID。

请求示例

<?php

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

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

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

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

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

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

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

需安装相关依赖:

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 = 'YOUR_APP_ID';// 替换为实际的应用 ID
    const pluginCode = 'YOUR_PLUGIN_CODE';// 替换为实际的插件ID
    const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;

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

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

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

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

请求示例

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 = "YOUR_APP_ID";// 替换为实际的应用ID

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

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

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

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

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

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

请求示例

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 := "YOUR_APP_ID"           // 替换为实际的应用 ID
	pluginCode := "YOUR_PLUGIN_CODE" // 替换为实际的插件 ID

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

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

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

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

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

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

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

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

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

是否流式输出通过设置stream实现。更多用法请参阅流式输出

Python
Java
HTTP

请求示例

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',
            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

请求示例

// 建议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("YOUR_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);
    }
}
curl
PHP
Node.js
C#
Go

请求示例

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' \
--header 'X-DashScope-SSE: enable' \
--data '{
    "input": {
        "prompt": "你是谁?"

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

请求示例

<?php

// 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_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";
}
?>

需安装相关依赖:

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 = 'YOUR_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();

请求示例

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 = "YOUR_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}");
            }
        }
    }
}

请求示例

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 := "YOUR_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
		}
	}
}

检索知识库通过传递rag_options实现更多用法请参阅检索知识库

Python
Java
HTTP

请求示例

import os
from http import HTTPStatus
# 建议dashscope SDK 的版本 >= 1.20.11
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='YOUR_APP_ID',  # 应用ID替换YOUR_APP_ID
    prompt='请帮我推荐一款3000元以下的手机',
    rag_options={
        "pipeline_ids": ["YOUR_PIPELINE_ID1","YOUR_PIPELINE_ID2"],  # 替换为实际的知识库ID,逗号隔开多个
    }
)

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

请求示例

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

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

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

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

请求示例

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": "请帮我推荐一款3000元以下的手机"
    },
    "parameters":  {
                    "rag_options" : {
                    "pipeline_ids":["YOUR_PIPELINE_ID1"]}
    },
    "debug": {}
}'
YOUR_APP_ID替换为实际的应用 ID,YOUR_PIPELINE_ID1替换为指定的知识库ID。

请求示例

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

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

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

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

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

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

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

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

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

需安装相关依赖:

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 = 'YOUR_APP_ID';//替换为实际的应用 ID

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

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

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

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

callDashScope();

请求示例

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 = "YOUR_APP_ID";// 替换为实际的应用ID
        // YOUR_PIPELINE_ID1替换为指定的知识库ID
        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("请确保设置了 DASHSCOPE_API_KEY。");
            return;
        }

        string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";
        
        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
            string jsonContent = $@"{{
                ""input"": {{
                    ""prompt"": ""请帮我推荐一款3000元以下的手机""
                }},
                ""parameters"": {{
                    ""rag_options"" : {{
                        ""pipeline_ids"":[""YOUR_PIPELINE_ID1""]
                    }}
                }},
                ""debug"": {{}}
            }}";

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

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

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

请求示例

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 := "YOUR_APP_ID" // 替换为实际的应用 ID

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

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

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

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

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

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

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

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

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

查看检索过程信息:调用时在代码中添加has_thoughts并设置为True,则检索的过程信息会在outputthoughts字段中返回。

长期记忆功能通过指定memory_id参数实现,更多用法请参阅长期记忆

目前仅智能体应用支持长期记忆。
Python
Java
HTTP

请求示例(生成记忆体内容)

# DashScope SDK版本不低于1.22.1
from http import HTTPStatus
import os
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='YOUR_APP_ID',  # 请输入实际的应用 ID
            prompt='用户饮食偏好:面食',
            memory_id='YOUR_MEMORY_ID')  # 请输入实际的记忆体 ID

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

请求示例(再次调用)

# DashScope SDK版本不低于1.22.1
from http import HTTPStatus
import os
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='YOUR_APP_ID',  # 请输入实际的应用 ID
            prompt='美食推荐',
            memory_id='YOUR_MEMORY_ID')  # 请输入实际的记忆体 ID

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

请求示例(生成记忆体内容)

// DashScope SDK版本不低于2.17.0
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;

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

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

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

请求示例(再次调用)

// DashScope SDK版本不低于2.17.0
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;

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

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

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

请求示例(生成记忆体内容)

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": "用户饮食偏好:面食",
        "memory_id": "YOUR_MEMORY_ID"
    },
    "parameters":  {},
    "debug": {}
}'  
YOUR_APP_ID替换为实际的应用 ID。

请求示例(再次调用)

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": "美食推荐",
        "memory_id": "YOUR_MEMORY_ID"
    },
    "parameters":  {},
    "debug": {}
}'  
YOUR_APP_ID替换为实际的应用 ID。

请求示例(生成记忆体内容)

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

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

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

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

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

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

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

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

请求示例(再次调用)

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

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

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

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

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

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

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

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

需安装相关依赖:

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 = 'YOUR_APP_ID';// 替换为实际的应用 ID
    const memoryId = 'YOUR_MEMORY_ID';// 替换为实际的memory_id

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

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

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

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

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

callDashScope();

请求示例(再次调用)

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 = 'YOUR_APP_ID';// 替换为实际的应用 ID
    const memoryId = 'YOUR_MEMORY_ID';// 替换为实际的memory_id

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

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

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

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

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

callDashScope();

请求示例(生成记忆体内容)

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 = "YOUR_APP_ID";// 替换为实际的应用ID
        string memoryId = "YOUR_MEMORY_ID";//替换为实际的memory_id
        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("请确保设置了 DASHSCOPE_API_KEY。");
            return;
        }

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

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

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

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

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

请求示例(再次调用)

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 = "YOUR_APP_ID";// 替换为实际的应用ID
        string memoryId = "YOUR_MEMORY_ID";//替换为实际的memory_id
        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("请确保设置了 DASHSCOPE_API_KEY。");
            return;
        }

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

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

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

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

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

请求示例(生成记忆体内容)

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 := "YOUR_APP_ID" // 替换为实际的应用 ID

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

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

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

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

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

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

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

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

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

请求示例(再次调用)

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 := "YOUR_APP_ID" // 替换为实际的应用 ID

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

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

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

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

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

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

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

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

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

智能体应用中支持您通过session_file_ids在当前请求中上传文件,更多用法请参阅上传文件

Python
Java
HTTP

请求示例

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='YOUR_APP_ID',  # 应用ID替换YOUR_APP_ID
    prompt='请根据以下文件帮我推荐一款3000元以下的手机',
    rag_options={
        "session_file_ids": ["FILE_ID1"],  # FILE_ID1 替换为实际的临时文件ID,逗号隔开多个
    }
)

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

请求示例

// 建议dashscope SDK 的版本 >= 2.17.0;
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.google.gson.JsonObject;
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("请根据以下文件帮我推荐一款3000元左右的手机")
                .ragOptions(RagOptions.builder()
                        .sessionFileIds(List.of("FILE_ID1", "FILE_ID2"))  // 替换为实际指定的临时文件 ID,逗号隔开多个
                        .build())
                .build();

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

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

请求示例

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": "请根据以下文件帮我推荐一款3000元以下的手机"
    },
    "parameters":  {
                    "rag_options" : {
                    "session_file_ids":["FILE_ID1"]}
    },
    "debug": {}
}'

请求示例

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

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

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

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

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

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

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

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

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

需安装相关依赖:

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 = 'YOUR_APP_ID';//替换为实际的应用 ID

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

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

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

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

callDashScope();

请求示例

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 = "YOUR_APP_ID";// 替换为实际的应用ID
        // FILE_ID1替换为指定的临时文件ID
        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("请确保设置了 DASHSCOPE_API_KEY。");
            return;
        }

        string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";
        
        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
            string jsonContent = $@"{{
                ""input"": {{
                    ""prompt"": ""请根据以下文件帮我推荐一款3000元以下的手机""
                }},
                ""parameters"": {{
                    ""rag_options"" : {{
                        ""session_file_ids"":[""FILE_ID1""]
                    }}
                }},
                ""debug"": {{}}
            }}";

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

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

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

请求示例

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 := "YOUR_APP_ID" // 替换为实际的应用 ID

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

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

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

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

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

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

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

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

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

app_id string (必选)

应用的标识。

我的应用页面的应用卡片上可以获取应用ID。

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

prompt string (必选)

输入当前期望应用执行的指令prompt,用来指导应用生成回复。

暂不支持传入文件。如果应用使用的是Qwen-Long模型,应用调用方法与其他模型一致。

当您通过传入messages自己管理对话历史时,则无需传递prompt

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

session_id string (可选)

历史对话的唯一标识。

传入session_id时,请求将自动携带云端存储的对话历史。具体用法请参考多轮对话

传入session_id时,prompt为必传。
若同时传入session_idmessages,则优先使用传入的messages
目前仅智能体应用和对话型工作流应用支持多轮对话。
Java SDK中为setSessionId。通过HTTP调用时,请将 session_id 放入 input 对象中。

messages array (可选)

由历史对话组成的消息列表。

用于自主管理上下文实现多轮对话,具体用法请参考多轮对话

核心规则:

  • 当使用 messages 管理对话时,无需传递 prompt

  • 若同时传入 messages 和 prompt

    • prompt 会被转换为一条 {"role": "user", "content": "您的prompt"},自动追加到 messages 末尾,生成最终上下文。

    • 示例:

      // 原始传入
      {
        "messages": [{"role": "user", "content": "你好"}], 
        "prompt": "推荐一部电影"
      }
      // 实际生效的messages
      [
        {"role": "user", "content": "你好"}, 
        {"role": "user", "content": "推荐一部电影"}
      ]
  • 若同时传入session_idmessages,则大模型优先使用messages中的内容,session_id将被忽略。

目前仅智能体应用和对话型工作流应用支持多轮对话。
通过HTTP调用时,请将messages 放入 input 对象中。
使用该参数,Python Dashscope SDK的版本至少应为1.20.14,Java Dashscope SDK的版本至少应为2.17.0。

消息类型

System Message object(可选)

系统消息,用于告知模型要扮演的角色或行为。如果设置系统消息,请放在messages列表的第一位,且只能有一个。

属性

content string (必选)

消息内容。

role string (必选)

固定为system

User Message object(必选)

用户消息,表示您发送给模型的文本。可以有多个,但messages列表的最后一位必须是用户消息

属性

content string (必选)

用户消息的内容。

属性

text string

传入的文本信息。

role string (必选)

用户消息的角色,固定为user

Assistant Message object(可选)

助手消息,表示模型对用户消息的回复。如果设置助手消息,请放在User Message后面形成“一问一答”。

属性

content string (必选)

助手消息的内容。

role string (必选)

助手消息的角色,固定为assistant

workspace string (可选)

业务空间标识。

调用子业务空间的应用时需传递workspace标识,调用默认业务空间的应用时无需传递workspace

在子业务空间里,点击我的应用页面的应用卡片上的调用,即可在应用API代码中获取子业务空间的workspace标识,具体请参考获取Workspace ID

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

stream boolean(可选)

是否流式输出回复。

参数值:

  • false(默认值):模型生成完所有内容后一次性返回结果。

  • true:边生成边输出,即每生成一部分内容就立即输出一个片段(chunk)。

Java SDK中为streamCall。通过HTTP调用时,请指定Header中的 X-DashScope-SSE enable。

incremental_output boolean(可选)

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

参数值:

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

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

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

flow_stream_mode object(可选)

工作流应用的流式输出模式。具体使用方法请参考流式输出

参数值及使用方法如下:

  • full_thoughts(默认值):

    • 描述:所有节点的流式结果在thoughts字段中输出。

    • 要求:同时必须要设置has_thoughtsTrue。

  • agent_format

    • 描述:使用与智能体应用相同的输出模式。

    • 效果:在控制台应用中,可选择打开指定节点的结果返回开关,则该节点的流式结果将在outputtext字段中输出。

    • 场景:适合只关心中间指定节点输出的场景。

    结果返回开关当前仅支持文本转换节点、大模型节点以及结束节点(结束节点默认打开)。
    在并行节点中同时开启结果返回开关,会导致内容混杂。因此,开启开关的节点需要有明确的输出先后顺序。
Java SDK中暂未开放此参数。通过HTTP调用时,请将flow_stream_mode放入parameters对象中。

biz_params object (可选)

应用通过自定义节点或自定义插件传递参数时,使用该字段进行传递。具体使用方法请参考自定义参数传递

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

属性

user_defined_params object (可选)

表示自定义插件参数信息。

属性

plugin_id string (可选)

表示插件ID,可在插件卡片上获取。your_plugin_code字段替换为实际的插件ID。

${plugin_params} string(可选)

对象最内侧包含的多个键值对。每个键值对表示用户自定义的待传递参数名及其指定值。如:

"article_index": 2

user_defined_tokens object(可选)

表示自定义插件的用户级鉴权信息。

属性

plugin_id string (可选)

插件 ID,可在插件卡片中获取。通过your_plugin_code字段传递。

user_token string (可选)

传递该插件需要的用户鉴权信息,如实际DASHSCOPE_API_KEY的值

memory_id string (可选)

长期记忆体ID。

在百炼控制台应用中打开长期记忆开关并发布应用,通过指定 memory_id 调用应用时,系统依据用户偏好信息自动构建和保存长期记忆。后续使用同一 memory_id 调用时,系统会恢复这些长期记忆,并与最新的用户消息合并提供给模型处理。

memory_id的创建方法请参见CreateMemory。详细调用方法请参见长期记忆

Java SDK中为memoryId。通过HTTP调用时,请将 memory_id 放入input 对象中。
目前仅智能体应用支持长期记忆。

has_thoughts boolean (可选)

是否输出插件调用、知识检索的过程,或DeepSeek-R1 类模型思考过程。

参数值:

  • True:输出在thoughts字段中。

  • False(默认值):不输出。

调用智能体应用实现Prompt样例库时,需要将此参数设置为True。

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

image_list Array (可选)

图片链接列表。用于传递图片链接。

支持以下两种使用场景:

  • 图片检索:在智能体应用中,根据上传的图片链接,检索包含图片链接的结构化知识库。

  • 图片理解:在通义千问VL模型智能体应用中,还可以直接提问图片内容。

"image_list" : ["https://example.com/images/example.jpg"]
#这是一个虚构的URL,请替换为实际存在的图片URL
可以是多个,每个图片链接之间通过英文逗号分隔。
Java SDK中为images。通过HTTP调用时,请将 image_list 放入 input 对象中。

rag_options Array (可选)

用于配置与检索相关的参数。包括但不限于对指定的知识库或文档进行检索。详细用法和规则请参见检索知识库

Java SDK中为ragOptions。通过HTTP调用时,请将 rag_options 放入 parameters 对象中。
目前仅智能体应用(包括RAG应用)支持此类检索参数。

属性

pipeline_ids Array 必选)

知识库ID,传入该参数将对指定知识库内所有文档进行检索。

可以在知识索引页面获取知识库ID,也可以使用CreateIndex接口(仅支持非结构化知识库)返回的Data.Id

使用步骤如下:

  1. 在百炼控制台智能体应用中打开知识库检索增强开关,并发布应用。

    RAG应用跳过此步骤。
  2. 三种方式检索指定知识库

    1. 在应用内单击配置知识库,关联指定知识库,并发布应用。

    2. 直接发布应用,调用时通过此参数传递指定知识库ID。

    3. 既在应用内关联指定知识库,又在调用时通过此参数传递指定知识库ID。

  3. API调用。具体用法请参考检索知识库

知识库ID上限5个,每个ID之间用英文逗号分隔,例如["知识库ID1", "知识库ID2"]。如果知识库ID传入多于5个,只生效前5个。
Java SDK中为pipelineIds

file_ids Array (可选)

非结构化文档ID,传入该参数将对指定非结构化文档进行检索。

数据管理页面的文档列表中可以获取文档ID,也可以使用AddFile接口导入文档返回的ID

传入文档ID时,还需要传入文档所属的知识库ID才会生效。
文档ID上限100每个ID之间用英文逗号分隔,例如["文档ID1", "文档ID2"]
Java SDK中为fileIds

metadata_filter Object (可选)

非结构化文档的元数据,传入该参数将对具备该元数据的非结构化文档进行检索。

知识索引页面,进入某个知识库后可以查看非结构化文档的元数据(Meta信息)。在创建非结构化知识库时可以设置元数据。调用ListChunks接口可获取指定文档的所有文本切片的详细信息。

传入元数据时,还需要传入所属的知识库ID才会生效。
Java SDK中为metadataFilter

tags Array (可选)

非结构化文档的标签,传入该参数将对具备该标签的非结构化文档进行检索。

数据管理页面,可以查看非结构化文档的标签。也可以通过DescribeFile接口获取文档标签。

可以是多个tag,每个tag之间用英文逗号分隔,例如["标签1", "标签2"]

structured_filter Object (可选)

结构化文档的列名和值,键值对形式。

传入该参数,将对结构化文档里符合条件的内容进行检索。

知识索引页面,进入某个知识库后可以单击查看索引查看结构化文档的索引信息。调用ListChunks接口可获取所有文本切片的详细信息。

可以是多个,每对键值对之间用英文逗号分隔。
Java SDK中为structuredFilter

session_file_ids Array (可选)

临时文件ID列表。

用于在智能体应用当前请求中上传临时文件ID。

基于这些文件,应用可临时扩展知识库、回答文件内容等。详细调用方法请参考上传临时文件

文件ID以“file_session”开头。

获取方式:根据API上传文件中的步骤 1、2 和 3 完成文件上传后获取。

步骤中需注意必须设置CategoryTypeSESSION_FILECategoryIddefault,否则获取的ID无效。
每个文件ID之间用英文逗号分隔,例如["文件ID1", "文件ID2"]。
Java SDK中为sessionFileIds
Python Dashscope SDK的版本至少应为1.20.14,Java Dashscope SDK的版本至少应为2.17.0。

支持上传的文件上限10个。支持上传本地的文档、图片、视频或音频,格式要求为:

文档(单文件不超过100MB):.doc,.docx,.wps,.ppt,.pptx,.xls,.xlsx,.md,.txt,.pdf;

图片(单文件不超过20MB):.png,.jpg,.jpeg,.bmp,.gif;

目前仅支持上传包含文字内容的本地图片。

视频(单文件不超过512MB):.mp4,.mkv,.avi,.mov,.wmv;

音频(单文件不超过512MB):.aac,.amr,.flac,.flv,.m4a,.mp3,.mpeg,.ogg,.opus,.wav,.webm,.wma;

响应对象

响应示例

status_code integer

返回的状态码。

200表示请求成功,否则表示请求失败。可以通过code获取错误码,通过message字段获取错误详细信息。

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

单轮对话响应示例

{
    "output": {
        "finish_reason": "stop",
        "session_id": "6105c965c31b40958a43dc93c28c7a59",
        "text": "我是通义千问,由阿里云开发的AI助手。我被设计用来回答各种问题、提供信息和与用户进行对话。有什么我可以帮助你的吗?"
    },
    "usage": {
        "models": [
            {
                "output_tokens": 36,
                "model_id": "qwen-plus",
                "input_tokens": 74
            }
        ]
    },
    "request_id": "f97ee37d-0f9c-9b93-b6bf-bd263a232bf9"
}

指定知识库响应示例

调用应用指定知识库功能时想要输出召回文档中被模型引用的文档信息,可在百炼控制台的智能体应用内,单击检索配置打开展示回答来源开关并发布应用。

{
    "text": "根据您的预算,我推荐您考虑百炼 Zephyr Z9。这款手机轻巧便携,拥有6.4英寸1080 x 2340像素的屏幕,搭配128GB存储与6GB RAM,非常适合日常使用<ref>[1]</ref>。此外,它还配备了4000mAh电池以及30倍数字变焦镜头,能够捕捉远处细节,价格区间在2499-2799元之间,完全符合您的预算需求<ref>[1]</ref>。",
    "finish_reason": "stop",
    "session_id": "6c1d47fa5eca46b2ad0668c04ccfbf13",
    "thoughts": null,
    "doc_references": [
        {
            "index_id": "1",
            "title": "百炼手机产品介绍",
            "doc_id": "file_7c0e9abee4f142f386e488c9baa9cf38_10317360",
            "doc_name": "百炼系列手机产品介绍",
            "doc_url": null,
            "text": "【文档名】:百炼系列手机产品介绍\n【标题】:百炼手机产品介绍\n【正文】:参考售价:5999- 6499。百炼 Ace Ultra ——游戏玩家之选:配备 6.67英寸 1080 x 2400像素屏幕,内置 10GB RAM与 256GB存储,确保游戏运行丝滑无阻。百炼 Ace Ultra ——游戏玩家之选:配备 6.67英寸 1080 x 2400像素屏幕,内置 10GB RAM与 256GB存储,确保游戏运行丝滑无阻。5500mAh电池搭配液冷散热系统,长时间游戏也能保持冷静。高动态双扬声器,沉浸式音效升级游戏体验。参考售价:3999- 4299。百炼 Zephyr Z9 ——轻薄便携的艺术:轻巧的 6.4英寸 1080 x 2340像素设计,搭配 128GB存储与 6GB RAM,日常使用游刃有余。4000mAh电池确保一天无忧,30倍数字变焦镜头捕捉远处细节,轻薄而不失强大。参考售价:2499- 2799。百炼 Flex Fold+ ——折叠屏新纪元:集创新与奢华于一身,主屏 7.6英寸 1800 x 2400像素与外屏 4.7英寸 1080 x 2400像素,多角度自由悬停设计,满足不同场景需求。512GB存储、12GB RAM,加之 4700mAh电池与 UTG超薄柔性玻璃,开启折叠屏时代新篇章。此外,这款手机还支持双卡双待、卫星通话,帮助您在世界各地都能畅联通话。参考零售价:9999- 10999。\n",
            "biz_id": null,
            "images": [

            ],
            "page_number": [
                0]
        }]
}

异常响应示例

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

此处以未传入正确API-KEY为例,向您展示异常响应的示例。

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

request_id string

当前的请求ID。

Java SDK返回参数为requestId

code string

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

详情请参见错误信息

该参数仅支持Python SDK。

message string

表示失败详细信息,成功忽略。

该参数仅支持Python SDK。

output object

表示调用结果信息。

output属性

text string

模型生成的回复内容。

finish_reason string

完成原因。

正在生成时为null,生成结束时如果由于停止token导致则为stop

session_id string

当前对话的唯一标识。

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

thoughts array

调用时将has_thoughts参数设置为True,即可在thoughts中查看插件调用、知识检索的过程,或DeepSeek-R1 类模型思考过程。

thoughts属性

thought string

模型思考过程。

action_type string

大模型返回的执行步骤类型。如API表示执行API插件、agentRag表示执行知识检索、reasoning表示执行DeepSeek-R1 类模型思考。

action_name string

执行的action名称,如知识检索、API插件、思考过程。

action string

执行的步骤。

action_input_stream string

入参的流式结果。

action_input string

插件的输入参数。

observation string

检索或插件的过程。

reasoningContent string

如果在工作流应用中选择了DeepSeek-R1 类模型,并设置了has_thoughts参数为True,则调用时模型的思考过程将在此字段返回。

doc_references array

检索的召回文档中被模型引用的文档信息。

在百炼控制台的智能体应用内,单击检索配置打开展示回答来源开关并发布应用,doc_references才可能包含有效信息。

doc_references属性

index_id string

模型引用的召回文档索引,如[1]。

title string

模型引用的文本切片标题。

doc_id string

模型引用的文档ID。

doc_name string

模型引用的文档名。

text string

模型引用的具体文本内容。

images array

模型引用的图片URL列表。

page_number array

模型引用的文本切片的页码。

此参数仅支持在20241025日后创建的知识库。
如需使用该参数,Python Dashscope SDK的版本至少应为1.20.14;Java Dashscope SDK的版本至少应为2.16.10。

usage object

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

usage属性

models array

本次应用调用到的模型信息。

models属性

model_id string

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

input_tokens integer

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

output_tokens integer

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

错误码

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

  • 本页导读 (1)
  • 调用方式
  • 请求体
  • 请求示例
  • 响应对象
  • 响应示例
  • 错误码