您可以通过DashScope SDK或HTTP的方式来集成百炼应用(智能体、工作流或智能体编排)到您的业务系统中。
前提条件
您可以使用DashScope SDK或HTTP接口调用百炼的应用,请您根据您的需求,参考以下方式准备您的计算环境。
调用方式 | 准备条件 |
通过DashScope SDK调用 | DashScope SDK提供了Python和Java两个版本,请参考DashScope SDK,安装最新版SDK。 如果您需要通过代理server或者pvl进行访问,可以自定义endpoint: Python可以添加到环境变量,需要配置的自定义endpoint:
或者添加到代码中,位置在调用
Java直接在代码中添加,位置如下:
请将Your_Custom_DashScope替换为您自定义的部分,如:dashscope。 |
通过HTTP调用 | 如果您通过HTTP方式进行调用,需要配置的endpoint:
|
无论使用哪种调用方式,建议您配置API Key到环境变量。
如何使用
单轮对话
您可以参考以下示例代码,通过DashScope SDK或HTTP方式调用百炼的应用,体验单轮对话的功能。
Python
请求示例
import os
from http import HTTPStatus
from dashscope import Application
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
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='你是谁?')
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://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code')
else:
print(response.output.text)
响应示例
我是阿里云开发的一款超大规模语言模型,我叫通义千问。我被设计用来帮助用户生成各种类型的文本,如文章、故事、诗歌、故事等,并能根据不同的场景和需求进行调整和优化。此外,我还能够回答各种问题,提供信息和解释,辅助学习和研究。如果您有任何需要,欢迎随时向我提问!
Java
请求示例
// 建议dashscope SDK的版本 >= 2.12.0
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
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://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
响应示例
text: 我是阿里云开发的一款超大规模语言模型,我叫通义千问。
HTTP
curl
请求示例
curl -X POST https://dashscope-intl.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。
响应示例
{"output":{"finish_reason":"stop",
"session_id":"232ea2e9e6ef448db6b14465c06a9a56",
"text":"我是来自阿里云的超大规模语言模型,我叫通义千问。我是一个能够回答问题、创作文字,还能表达观点、撰写代码的AI助手。如果您有任何问题或需要帮助,请随时告诉我,我会尽力为您提供帮助。"},
"usage":{"models":[{"output_tokens":51,"model_id":"qwen-max","input_tokens":121}]},
"request_id":"661c9cad-e59c-9f78-a262-78eff243f151"}%
PHP
请求示例
<?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-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
// 构造请求数据
$data = [
"input" => [
'prompt' => '你是谁?'
]
];
// 将数据编码为 JSON
$dataString = json_encode($data);
// 检查 json_encode 是否成功
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// 初始化 cURL 对话
$ch = curl_init($url);
// 设置 cURL 选项
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
]);
// 执行请求
$response = curl_exec($ch);
// 检查 cURL 执行是否成功
if ($response === false) {
die("cURL Error: " . curl_error($ch));
}
// 获取 HTTP 状态码
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 关闭 cURL 对话
curl_close($ch);
// 解码响应数据
$response_data = json_decode($response, true);
// 处理响应
if ($status_code == 200) {
if (isset($response_data['output']['text'])) {
echo "{$response_data['output']['text']}\n";
} else {
echo "No text in response.\n";
}}
else {
if (isset($response_data['request_id'])) {
echo "request_id={$response_data['request_id']}\n";}
echo "code={$status_code}\n";
if (isset($response_data['message'])) {
echo "message={$response_data['message']}\n";}
else {
echo "message=Unknown error\n";}
}
?>
响应示例
我是来自阿里云的超大规模语言模型,我叫通义千问。
Node.js
需安装相关依赖:
npm install axios
请求示例
const axios = require('axios');
async function callDashScope() {
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';// 替换为实际的应用 ID
const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "你是谁?"
},
parameters: {},
debug: {}
};
try {
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
console.log(`${response.data.output.text}`);
} else {
console.log(`request_id=${response.headers['request_id']}`);
console.log(`code=${response.status}`);
console.log(`message=${response.data.message}`);
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();
响应示例
我是来自阿里云的大规模语言模型,我叫通义千问。
C#
请求示例
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
//若没有配置环境变量,可用百炼API Key将下行替换为:apiKey="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
string appId = "YOUR_APP_ID"; // 替换为实际的应用ID
string url = $"https://dashscope-intl.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}");
}
}
}
}
响应示例
{
"output": {
"finish_reason": "stop",
"session_id": "c274e14a58d9492f9baeffdc003a97c5",
"text": "我是阿里云开发的一款超大规模语言模型,我叫通义千问。我被设计用来帮助用户生成各种类型的文本,如文章、故事、诗歌、故事等,并能根据不同的场景和需求进行变换和创新。此外,我还能够回答各种问题,提供信息和解释,帮助用户解决问题和获取知识。如果你有任何问题或需要帮助,请随时告诉我!"
},
"usage": {
"models": [
{
"output_tokens": 79,
"model_id": "qwen-plus",
"input_tokens": 74
}
]
},
"request_id": "5c4b86b1-cd2d-9847-8d00-3fba8f187bc6"
}
Go
请求示例
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // 替换为实际的应用 ID
if apiKey == "" {
fmt.Println("请确保设置了DASHSCOPE_API_KEY。")
return
}
url := fmt.Sprintf("https://dashscope-intl.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))
}
}
响应示例
{
"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"
}
调用智能体应用实现Prompt样例库功能时,还需要在上述代码的parameters对象中添加并设置has_thoughts
参数为True,检索的过程信息在thoughts
字段中返回。
多轮对话
相比于单轮对话,多轮对话可以让大模型参考历史对话信息,更符合日常交流的场景。阿里云百炼应用提供云端托管多轮对话功能,通过session_id
进行多轮对话,阿里云百炼云端将自动托管多轮对话。
上一次调用后返回的session_id
作为下一次调用时的传入参数,实现在下一次调用大模型服务时,携带了上一次调用的对话信息。
目前仅智能体应用和对话型工作流应用支持多轮对话功能。
Python
请求示例
import os
from http import HTTPStatus
from dashscope import Application
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
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://www.alibabacloud.com/help/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://www.alibabacloud.com/help/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()
响应示例
我具备多种技能,可以协助你完成各种任务。以下是一些主要的技能:
1. **信息查询**:提供天气、新闻、历史事实、科学知识等各种信息。
2. **语言处理**:翻译文本、纠正语法错误、生成文章和故事。
3. **技术问题解答**:解答编程、软件使用、技术故障排除等问题。
4. **学习辅导**:帮助解答数学、物理、化学等学科的问题。
5. **生活建议**:提供健康、饮食、旅行、购物等方面的建议。
6. **娱乐互动**:讲笑话、玩文字游戏、进行简单的聊天互动。
7. **日程管理**:提醒重要日期、安排日程、设置提醒。
8. **数据分析**:解释数据图表、提供数据分析建议。
9. **情感支持**:倾听你的感受、提供安慰和支持。
如果你有具体的需求或问题,可以直接告诉我,我会尽力帮助你!
session_id=98ceb3ca0c4e4b05a20a00f913050b42
Java
请求示例
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import java.util.Arrays;
import java.util.List;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
}
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://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
响应示例
我具备多项技能,可以为您提供多种帮助。以下是一些主要的技能:
1. **多语言理解与生成**:我能理解和生成包括中文、英文在内的多种语言文本。
2. **信息检索与综合**:我可以根据您的问题查找相关信息并进行整理和总结。
3. **写作辅助**:无论是撰写文章、报告还是创意写作,我都能提供支持。
4. **编程助手**:对于程序员来说,我可以帮助解答编程相关的问题,提供代码示例等。
5. **教育辅导**:在学习过程中遇到困难时,我可以作为助手提供帮助,涵盖从数学到历史等多个学科领域。
6. **生活建议**:关于健康饮食、旅行规划等方面的问题我也能给出一些建议。
7. **情感交流**:虽然我是AI,但我努力以一种温暖和支持的方式与您交流。
如果您有任何具体需求或想要进一步了解某个方面的内容,请随时告诉我!
, session_id: f2e94a980a34424fa25be45a7048d77c
HTTP
curl
请求示例(上一轮对话)
curl -X POST https://dashscope-intl.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": {}
}'
响应示例
{
"output": {
"finish_reason": "stop",
"session_id": "4f8ef7233dc641aba496cb201fa59f8c",
"text": "我是通义千问,由阿里云开发的AI助手。我被设计用来回答各种问题、提供信息和与用户进行对话。有什么我可以帮助你的吗?"
},
"usage": {
"models": [
{
"output_tokens": 36,
"model_id": "qwen-plus",
"input_tokens": 75
}
]
},
"request_id": "e571b14a-423f-9278-8d1e-d86c418801e0"
}
请求示例(下一轮对话)
curl -X POST https://dashscope-intl.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": {}
}'
响应示例
{
"output": {
"finish_reason": "stop",
"session_id": "4f8ef7233dc641aba496cb201fa59f8c",
"text": "作为AI助手,我具备多种技能,可以帮助你完成各种任务,包括但不限于:
1. **知识查询**:我可以帮助你查找各种领域的信息,比如科学、历史、文化、技术等。
2. **语言翻译**:我可以帮你翻译不同语言的文字,支持多种语言之间的互译。
3. **文本生成**:我可以生成文章、故事、诗歌、新闻稿等各种类型的文本。
4. **问题解答**:无论是学术问题、生活常识还是技术难题,我都可以尝试为你提供答案。
5. **对话交流**:我可以与你进行自然流畅的对话,提供情感支持或娱乐。
6. **代码编写与调试**:我可以帮助你编写代码、解决编程中的问题。
7. **数据分析**:我可以帮助你分析数据,提供统计结果和可视化建议。
8. **创意启发**:如果你需要创意灵感,比如设计、广告词、营销策略等,我也可以提供帮助。
如果你有任何具体的需求或问题,欢迎随时告诉我!"
},
"usage": {
"models": [
{
"output_tokens": 208,
"model_id": "qwen-plus",
"input_tokens": 125
}
]
},
"request_id": "9de2c3ed-e1f0-9963-85f4-8f289203418b"
}
PHP
请求示例(上一轮对话)
<?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-intl.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";}
}
?>
响应示例
我是来自阿里云的超大规模语言模型,我叫通义千问。
session_id=2e658bcb514f4d30ab7500b4766a8d43
请求示例(下一轮对话)
<?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-intl.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";}
}
?>
响应示例
我具备多项技能,包括但不限于:
1. **多语言能力**:我可以理解和生成多种语言的文字内容。
2. **写作与创作**:帮助撰写文章、故事、诗歌等创意内容。
3. **知识问答**:回答来自各个领域的常识性和专业性问题。
4. **代码编写与理解**:能够编写简单的程序代码,并帮助解释或调试代码。
5. **逻辑推理**:解决需要逻辑思考的问题和谜题。
6. **情感支持**:提供正面的心理支持和鼓励。
7. **游戏娱乐**:参与文字游戏或其他形式的互动娱乐活动。
我的目标是成为您的得力助手,在您需要的时候提供帮助和支持。如果您有任何具体需求或想要尝试的功能,请随时告诉我!
session_id=2e658bcb514f4d30ab7500b4766a8d43
Node.js
需安装相关依赖:
npm install axios
请求示例(上一轮对话)
const axios = require('axios');
async function callDashScope() {
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';// 替换为实际的应用 ID
const url = `https://dashscope-intl.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();
响应示例
我是通义千问,由阿里云开发的人工智能助手。我可以回答各种问题、提供信息和与用户进行对话。有什么我可以帮助你的吗?
session_id=fe4ce8b093bf46159ea9927a7b22f0d3
请求示例(下一轮对话)
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-intl.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();
响应示例
我具备多种技能,可以帮助你处理不同的任务和问题。以下是一些主要的技能领域:
1. **信息查询与检索**:我可以帮助查找特定的信息、数据或新闻。
2. **写作与创作**:包括撰写文章、故事、诗歌、报告等。
3. **语言翻译**:能够提供不同语言之间的翻译服务。
4. **教育辅导**:解答学术问题,帮助理解复杂的概念。
5. **技术支持**:解决计算机使用中遇到的技术难题。
6. **生活建议**:提供建议关于健康、饮食、旅行等方面。
7. **娱乐互动**:讲笑话、玩文字游戏等轻松活动。
如果你有具体的需求或想了解更详细的某一方面,请告诉我!
session_id=fe4ce8b093bf46159ea9927a7b22f0d3
C#
请求示例(上一轮对话)
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
//若没有配置环境变量,可用百炼API Key将下行替换为:apiKey="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
string appId = "YOUR_APP_ID"; // 替换为实际的应用ID
string url = $"https://dashscope-intl.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}");
}
}
}
}
响应示例
{
"output": {
"finish_reason": "stop",
"session_id": "7b830e4cc8fe44faad0e648f9b71435f",
"text": "我是通义千问,由阿里云开发的AI助手。我被设计用来回答各种问题、提供信息和与用户进行对话。有什么我可以帮助你的吗?"
},
"usage": {
"models": [
{
"output_tokens": 36,
"model_id": "qwen-plus",
"input_tokens": 75
}
]
},
"request_id": "53691ae5-be17-96c6-a830-8f0f92329028"
}
请求示例(下一轮对话)
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-intl.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}");
}
}
}
}
响应示例
{
"output": {
"finish_reason": "stop",
"session_id": "7b830e4cc8fe44faad0e648f9b71435f",
"text": "我具备多种技能,可以:
- 回答广泛领域的知识性问题
- 提供学习资源和建议
- 协助解决技术问题
- 进行多语言交流
- 帮助规划行程和活动
- 提供日常生活中的实用建议
如果你有任何具体需求或问题,欢迎随时告诉我!"
},
"usage": {
"models": [
{
"output_tokens": 70,
"model_id": "qwen-plus",
"input_tokens": 123
}
]
},
"request_id": "da5044ed-461e-9e91-8ca5-38a3c72a8306"
}
Go
请求示例(上一轮对话)
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // 替换为实际的应用 ID
if apiKey == "" {
fmt.Println("请确保设置了DASHSCOPE_API_KEY。")
return
}
url := fmt.Sprintf("https://dashscope-intl.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))
}
}
响应示例
{
"output": {
"finish_reason": "stop",
"session_id": "f7eea37f0c734c20998a021b688d6de2",
"text": "我是通义千问,由阿里云开发的AI助手。我被设计用来回答各种问题、提供信息和与用户进行对话。有什么我可以帮助你的吗?"
},
"usage": {
"models": [
{
"output_tokens": 36,
"model_id": "qwen-plus",
"input_tokens": 75
}
]
},
"request_id": "fa65e14a-ab63-95b2-aa43-035bf5c51835"
}
请求示例(下一轮对话)
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-intl.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))
}
}
响应示例
{
"output": {
"finish_reason": "stop",
"session_id": "f7eea37f0c734c20998a021b688d6de2",
"text": "我具备多种技能,可以:
- 回答各种知识性问题,如科学、历史、文化等领域的疑问。
- 提供实用建议,比如旅行攻略、健康小贴士、学习方法等。
- 协助处理文字工作,例如撰写文章、编辑文档、创作故事或诗歌。
- 进行多语言翻译,支持多种语言之间的互译。
- 与用户进行自然流畅的对话,陪伴聊天、解答疑惑。
如果你有任何具体需求,欢迎告诉我!"
},
"usage": {
"models": [
{
"output_tokens": 104,
"model_id": "qwen-plus",
"input_tokens": 125
}
]
},
"request_id": "badccade-9f54-986b-8d8c-75ef15e9616c"
}
YOUR_APP_ID替换为实际的应用 ID。下一轮对话的输入参数session_id
字段值替换为实际上一轮对话返回的session_id值。
自定义参数透传
当您需要通过改变参数让同一个智能体或工作流适应不同的业务场景时,可以利用自定义参数来传递配置信息。在应用的调用过程中透传自定义参数,有以下两种方式:1.智能体应用的自定义插件的参数和鉴权透传;2.工作流应用和智能体编排应用的自定义输入参数透传。需要透传的参数都需要使用biz_params
传递。
更多关于透传功能的调用细节请参考:应用的参数透传。
在工作流应用和智能体编排应用中,支持自定义开始节点的参数。
参考下面在工作流应用中透传城市名参数的例子,在应用的开始节点设置String类型变量city,同时在Prompt中插入变量city和变量query,发布应用。
调用时通过
biz_params
传递city,通过prompt
传递query。Python
请求示例
import os from http import HTTPStatus from dashscope import Application import dashscope dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1' # 工作流和智能体编排应用自定义参数透传 biz_params = {"city": "杭州"} 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='查询这个城市的行政区域划分', 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://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code') else: print(f'{response.output.text}') # 处理只输出文本text
响应示例
杭州市,作为浙江省的省会城市,其行政区域划分包括10个市辖区:上城区、拱墅区、西湖区、滨江区、萧山区、余杭区、临平区、钱塘区、富阳区、临安区。每个区都有其独特的特色和发展重点。 - 上城区:位于杭州市中心地带,是杭州的政治、经济、文化中心之一。 - 拱墅区:以运河文化为特色,拥有众多历史文化遗产。 - 西湖区:著名的西湖风景区就位于此区,是旅游观光的重要目的地。 - 滨江区:高新技术产业聚集地,阿里巴巴等知名企业坐落于此。 - 萧山区:东南部的一个行政区,经济发展迅速,特别是制造业方面。 - 余杭区:近年来发展快速,尤其是互联网经济领域,阿里巴巴总部也设在这里(注:阿里巴巴总部实际位于滨江区)。 - 临平区:新成立的行政区,旨在促进该地区经济社会全面发展。 - 钱塘区:同样是一个较新的行政区划调整结果,强调创新发展和生态保护相结合。 - 富阳区:位于杭州西南方向,以其丰富的自然景观和悠久的历史文化著称。 - 临安区:地处杭州西部,以生态优美闻名,并且有着深厚的文化底蕴。 请注意,随着时间推移,具体的城市规划可能会有所变化,请参考最新的官方信息。
Java
请求示例
import com.alibaba.dashscope.app.*; import com.alibaba.dashscope.exception.ApiException; import com.alibaba.dashscope.exception.InputRequiredException; import com.alibaba.dashscope.exception.NoApiKeyException; import com.alibaba.dashscope.utils.JsonUtils; import io.reactivex.Flowable; import com.alibaba.dashscope.utils.Constants; public class Main { static { Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1"; } public static void appCall() throws NoApiKeyException, InputRequiredException { String bizParams = "{\"city\":\"杭州\"}"; 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://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code"); } System.exit(0); } }
响应示例
杭州市是浙江省的省会城市,其行政区域划分主要包括10个市辖区:上城区、拱墅区、西湖区、滨江区、萧山区、余杭区、临平区、钱塘区、富阳区、临安区。每个区都有自己的特色和发展重点。 - 上城区:位于杭州市中心,拥有许多历史文化遗产。 - 拱墅区:以大运河文化而闻名,同时也是一个重要的商业和居住区。 - 西湖区:以其美丽的自然风光著称,包括著名的西湖风景区。 - 滨江区:高新技术产业集聚地,杭州国家高新技术产业开发区就设在这里。 - 萧山区:经济发展迅速,尤其在制造业方面表现突出。 - 余杭区:近年来随着阿里巴巴等高科技企业的发展而快速崛起。 - 临平区:2021年由原余杭区部分区域调整而来,注重生态建设和科技创新。 - 钱塘区:同样是在2021年成立的新区,定位为杭州东部交通枢纽及产业发展新高地。 - 富阳区:历史悠久的文化名城,也是造纸业的重要基地之一。 - 临安区:位于杭州西部,森林覆盖率高,生态环境良好。 这些区域共同构成了杭州市独特的地理格局和社会经济结构。如果你对某个特定区域感兴趣或需要更详细的信息,请告诉我!
HTTP
curl
请求示例
curl -X POST https://dashscope-intl.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": { "city": "杭州"} }, "parameters": {} }'
YOUR_APP_ID替换为实际的应用 ID。
响应示例
{"output":{"finish_reason":"stop","session_id":"c211219896004b50a1f6f66f2ec5413e", "text":"杭州市下辖10个区、1个县,代管2个县级市,分别为: 上城区、拱墅区、西湖区、滨江区、萧山区、余杭区、临平区、钱塘区、富阳区、临安区、桐庐县、淳安县、建德市、诸暨市。 注意,诸暨市由浙江省直辖、杭州市与绍兴市共同管理。"},"usage":{}, "request_id":"02c3c9e1-7912-9505-91aa-248d04fb1f5d"}
PHP
请求示例
<?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-intl.aliyuncs.com/api/v1/apps/$application_id/completion"; // 构造请求数据 $data = [ "input" => [ 'prompt' => '查询这个城市的行政区域划分', 'biz_params' => [ 'city' => '杭州' ] ], ]; // 将数据编码为 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"; } }
响应示例
杭州市是浙江省的省会城市,其行政区域划分主要包括10个市辖区:上城区、拱墅区、西湖区、滨江区、萧山区、余杭区、临平区、钱塘区、富阳区、临安区。 每个区都有自己的特色和发展重点,比如: - **上城区**和**拱墅区**位于杭州市中心,商业繁华,历史悠久。 - **西湖区**以美丽的西湖而闻名,同时也是一个重要的科教文化区。 - **滨江区**则以其高新技术产业发展著称。 - **萧山区**、**余杭区**等则是近年来随着城市发展迅速崛起的新城区或经济开发区。 - **临安区**、**富阳区**等地则更多保留了自然风光与乡村风貌。 请注意,中国的行政区划可能会根据国家政策调整有所变化,请通过官方渠道获取最新信息。
Node.js
需安装相关依赖:
npm install axios
请求示例
const axios = require('axios'); async function callDashScope() { // 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。 const apiKey = process.env.DASHSCOPE_API_KEY; const appId = 'YOUR_APP_ID'; // 替换为实际的应用 ID const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`; const data = { input: { prompt: "查询这个城市的行政区域划分", biz_params: { 'city': '杭州', }, }, 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();
响应示例
杭州市是浙江省的省会,其行政区域划分包括10个市辖区。具体如下: 1. 上城区(Shàngchéng Qū):位于杭州市中心偏南,是杭州历史最悠久、文化底蕴最深厚的区域之一。 2. 拱墅区(Gǒngshù Qū):原为下城区和拱墅区合并而成的新区,位于杭州市北部。 3. 西湖区(Xīhú Qū):以世界文化遗产西湖而闻名,拥有丰富的自然与人文景观。 4. 滨江区(Bīnjiāng Qū):地处钱塘江南岸,是一个高新技术产业集聚地。 5. 萧山区(Xiāoshān Qū):位于杭州市东部,是中国重要的制造业基地之一。 6. 余杭区(Yúháng Qū):曾经是中国四大名镇之一的临平所在地,现已成为杭州重要的经济发展区。 7. 富阳区(Fùyáng Qū):位于杭州市西南部,因富春江穿流其间而得名。 8. 临安区(Lín'ān Qū):位于杭州市西部山区,以其美丽的自然风光著称。 9. 钱塘区(Qiántáng Qū):成立于2021年,由原大江东产业集聚区及部分萧山区组成,旨在促进杭州东部地区的发展。 10. 临平区(Lín Píng Qū):从余杭区分设出来的一个新行政区划,主要涵盖原余杭区内的临平街道等地。 以上信息反映了截至我最后更新时的情况,请注意行政区划可能会有所调整,请以官方发布的最新消息为准。
C#
请求示例
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-intl.aliyuncs.com/api/v1/apps/{appId}/completion"; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); string jsonContent = @"{ ""input"": { ""prompt"": ""查询这个城市的行政区域划分"", ""biz_params"":{ ""city"":""杭州"" } }, ""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}"); } } } }
响应示例
{ "output": { "finish_reason": "stop", "session_id": "7a9ff57eec7d475fa5d487de5f5178d2", "text": "杭州市是浙江省的省会,它下辖有10个市辖区:上城区、拱墅区、西湖区、滨江区、萧山区、余杭区、临平区、钱塘区、富阳区和临安区。每个区都有其独特的地理位置和发展特色。例如,西湖区以美丽的自然风光著称,尤其是著名的杭州西湖就位于此;而滨江区则更多地以其高新技术产业发展闻名。此外,随着城市的发展,行政区划也可能会有所调整,请关注官方发布的最新信息。" }, "usage": { }, "request_id": "d2c2fcc9-f821-98c9-9430-8704a2a41225" }
Go
请求示例
package main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" ) func main() { // 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。 apiKey := os.Getenv("DASHSCOPE_API_KEY") appId := "YOUR_APP_ID" // 替换为实际的应用 ID if apiKey == "" { fmt.Println("请确保设置了DASHSCOPE_API_KEY。") return } url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId) // 创建请求体 requestBody := map[string]interface{}{ "input": map[string]interface{}{ "prompt": "查询这个城市的行政区域划分", "biz_params": map[string]interface{}{ "city": "杭州", }, }, "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)) } }
响应示例
{ "output": { "finish_reason": "stop", "session_id": "2dc3e1a9dcd248c6bb9ca92bffc3e745", "text": "杭州市,简称“杭”,是浙江省的省会城市。根据最新的行政区划调整,杭州市现辖10个市辖区、2个县级市和1个县,具体如下: - 市辖区(10个):上城区、拱墅区、西湖区、滨江区、萧山区、余杭区、临平区、钱塘区、富阳区、临安区。 - 县级市(2个):建德市、桐庐县(注意这里的桐庐实际上被列为县级市处理,但准确地说它是一个县)。 - 县(1个):淳安县。 请注意,随着时间的变化,行政区域可能会有所调整,请以官方最新发布的消息为准。上述信息基于较新的资料整理而来,对于最新的变动情况,建议访问政府官方网站获取最准确的信息。" }, "usage": { }, "request_id": "d3c8f368-b645-9446-bfe4-20ca51821a02" }
在智能体应用中,自定义插件的参数透传功能使用
user_defined_params
传递参数信息。自定义插件的用户级鉴权功能使用user_defined_tokens
传递鉴权信息,其中user_token
传递的值为该插件需要的鉴权信息,如API_KEY。插件中传入带有
x-source
属性的参数才会产生效果,同时,目标插件的描述请使用自然语言描述插件的功能,帮助大模型判断当前任务是否需要调用当前插件。参考下面查询寝室公约内容的例子,在应用中单击选择插件添加需要使用的自定义插件后,单击发布应用。
自定义插件参数透传
Python
请求示例
import os from http import HTTPStatus # 建议dashscope SDK 的版本 >= 1.14.0 from dashscope import Application import dashscope dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1' 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://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code') else: print('%s\n' % (response.output.text)) # 处理只输出文本text # print('%s\n' % (response.usage))
响应示例
寝室公约的第二条规定如下: "寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。" 这表明在寝室内,成员之间应该培养一种积极正面的生活和学习氛围,彼此帮助和支持,同时也要学会理解和尊重他人。如果您需要了解公约的其他条款,请告诉我!
Java
请求示例
import com.alibaba.dashscope.app.*; import com.alibaba.dashscope.exception.ApiException; import com.alibaba.dashscope.exception.InputRequiredException; import com.alibaba.dashscope.exception.NoApiKeyException; import com.alibaba.dashscope.utils.JsonUtils; import com.alibaba.dashscope.utils.Constants; public class Main { static { Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1"; } 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://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code"); } System.exit(0); } }
响应示例
寝室公约的第二条规定如下: 第二条 寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。 这强调了在共同生活环境中,室友之间应该保持积极正面的关系,通过相互帮助和支持来营造一个和谐的生活和学习氛围。如果有更多具体的条款需要了解,请告知我。
HTTP
curl
请求示例
curl -X POST https://dashscope-intl.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。
响应示例
{"output": {"finish_reason":"stop", "session_id":"e151267ffded4fbdb13d91439011d31e", "text":"寝室公约的第二条内容是:“寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。”这意呀着在寝室生活中,大家要彼此支持,共同创造一个和谐、积极向上的生活环境。"}, "usage":{"models":[{"output_tokens":94,"model_id":"qwen-max","input_tokens":453}]}, "request_id":"a39fd2b5-7e2c-983e-84a1-1039f726f18a"}%
PHP
请求示例
<?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-intl.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";} } ?>
响应示例
寝室公约的第二条规定:寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。这是为了保证大家能在一个和谐友爱的环境中生活和学习。如果有更多具体的条款需要了解,或者有其他问题,随时可以问我!
Node.js
需安装相关依赖:
npm install axios
请求示例
const axios = require('axios'); async function callDashScope() { // 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。 const apiKey = process.env.DASHSCOPE_API_KEY; const appId = 'YOUR_APP_ID';// 替换为实际的应用 ID const pluginCode = 'YOUR_PLUGIN_CODE';// 替换为实际的插件ID const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`; const data = { input: { prompt: "寝室公约内容", biz_params: { user_defined_params: { [pluginCode]: { // article_index为自定义插件的变量,替换为实际的插件变量 'article_index': 3 } } } }, parameters: {}, debug: {} }; try { console.log("Sending request to DashScope API..."); const response = await axios.post(url, data, { headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' } }); if (response.status === 200) { if (response.data.output && response.data.output.text) { console.log(`${response.data.output.text}`); } } else { console.log("Request failed:"); if (response.data.request_id) { console.log(`request_id=${response.data.request_id}`); } console.log(`code=${response.status}`); if (response.data.message) { console.log(`message=${response.data.message}`); } else { console.log('message=Unknown error'); } } } catch (error) { console.error(`Error calling DashScope: ${error.message}`); if (error.response) { console.error(`Response status: ${error.response.status}`); console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`); } } } callDashScope();
响应示例
寝室公约的第三条规定如下: 注意安全用电,杜绝火灾隐患。寝室内严禁使用明火、违规电器、各种灶具以及其他违规物品,不得存放易爆、易燃物品,私接电源。 如果您需要了解更多的规定,请告诉我。
C#
请求示例
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-intl.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}"); } } } }
响应示例
{ "output": { "finish_reason": "stop", "session_id": "237ca6187c814f3b9e7461090a5f8b74", "text": "寝室公约的第二条规定如下: "寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。" 这表示在寝室内,成员之间需要建立起一种积极正面的关系,通过帮助、关心和支持彼此来营造一个和谐的生活和学习环境。同时也要学会理解和接受室友之间的差异,以真诚的态度去交流沟通。如果还有其他条款或具体内容想要了解,请告诉我!" }, "usage": { "models": [ { "output_tokens": 133, "model_id": "qwen-max", "input_tokens": 829 } ] }, "request_id": "64e8c359-d071-9d2e-bb94-187e86cc3a79" }
Go
请求示例
package main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" ) func main() { // 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。 apiKey := os.Getenv("DASHSCOPE_API_KEY") appId := "YOUR_APP_ID" // 替换为实际的应用 ID pluginCode := "YOUR_PLUGIN_CODE" // 替换为实际的插件 ID if apiKey == "" { fmt.Println("请确保设置了DASHSCOPE_API_KEY。") return } url := fmt.Sprintf("https://dashscope-intl.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)) } }
响应示例
{ "output": { "finish_reason": "stop", "session_id": "860d2a4c1f3649ac880298537993cb51", "text": "寝室公约的第二条规定如下: 寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。 这强调了在宿舍生活中,室友之间应该保持良好的互助关系,同时也要互相尊重对方。您想要了解其他条款的内容吗?" }, "usage": { "models": [ { "output_tokens": 84, "model_id": "qwen-max", "input_tokens": 876 } ] }, "request_id": "0a250055-90a4-992d-9276-e268ad35d1ab" }
自定义插件用户级鉴权
Python
请求示例
from http import HTTPStatus import os # 建议dashscope SDK 的版本 >= 1.14.0 from dashscope import Application import dashscope dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1' biz_params = { # 智能体应用的自定义插件鉴权透传,自定义的插件ID替换{your_plugin_code},鉴权信息替换YOUR_TOKEN,如API key "user_defined_params": { "{your_plugin_code}": { "article_index": 2}}, "user_defined_tokens": { "{your_plugin_code}": { "user_token": "YOUR_TOKEN"}}} 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://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code') else: print('%s\n' % (response.output.text)) # 处理只输出文本text # print('%s\n' % (response.usage))
响应示例
寝室公约的第二条规定如下: 寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。 如果您需要了解更多的规定内容,请告诉我。
Java
请求示例
import com.alibaba.dashscope.app.*; import com.alibaba.dashscope.exception.ApiException; import com.alibaba.dashscope.exception.InputRequiredException; import com.alibaba.dashscope.exception.NoApiKeyException; import com.alibaba.dashscope.utils.JsonUtils; import com.alibaba.dashscope.utils.Constants; public class Main { static { Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1"; } public static void appCall() throws NoApiKeyException, InputRequiredException { String bizParams = // {your_plugin_code}替换为实际的插件ID,YOUR_TOKEN替换为实际的Token,如API key "{\"user_defined_params\":{\"{your_plugin_code}\":{\"article_index\":2}}," + "\"user_defined_tokens\":{\"{your_plugin_code}\":{\"user_token\":\"YOUR_TOKEN\"}}}"; 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://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code"); } System.exit(0); } }
响应示例
寝室公约的第二条规定如下: 寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。 如果您需要查询更多的规定内容,请告诉我。
HTTP
curl
请求示例
curl -X POST https://dashscope-intl.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 } }, "user_defined_tokens": { "{your_plugin_code}": { "user_token": "YOUR_TOKEN" } } } }, "parameters": {}, "debug":{} }'
YOUR_APP_ID替换为实际的应用 ID。
响应示例
{"output":{"finish_reason":"stop", "session_id":"d3b5c3e269dc40479255a7a02df5c630", "text":"寝室公约的第二条内容为:“寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。”这强调了寝室生活中成员之间和谐相处与共同进步的重要性。"}, "usage":{"models":[{"output_tokens":80,"model_id":"qwen-max","input_tokens":432}]}, "request_id":"1f77154c-edc3-9003-b622-816fa2f849cf"}%
PHP
请求示例
<?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-intl.aliyuncs.com/api/v1/apps/$application_id/completion"; // 构造请求数据 $data = [ "input" => [ 'prompt' => '寝室公约内容', 'biz_params' => [ 'user_defined_params' => [ '{your_plugin_code}' => [//{your_plugin_code}替换为实际的插件ID 'article_index' => 2 ] ], 'user_defined_tokens' => [ '{your_plugin_code}' => [//{your_plugin_code}替换为实际的插件ID 'user_token' => 'YOUR_TOKEN'//替换为实际的Token,如API key ] ] ] ], ]; // 将数据编码为 JSON $dataString = json_encode($data); // 检查 json_encode 是否成功 if (json_last_error() !== JSON_ERROR_NONE) { die("JSON encoding failed with error: " . json_last_error_msg()); } // 初始化 cURL 对话 $ch = curl_init($url); // 设置 cURL 选项 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Authorization: Bearer ' . $api_key ]); // 执行请求 $response = curl_exec($ch); // 检查 cURL 执行是否成功 if ($response === false) { die("cURL Error: " . curl_error($ch)); } // 获取 HTTP 状态码 $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // 关闭 cURL 对话 curl_close($ch); // 解码响应数据 $response_data = json_decode($response, true); // 处理响应 if ($status_code == 200) { if (isset($response_data['output']['text'])) { echo "{$response_data['output']['text']}\n"; } else { echo "No text in response.\n"; } }else { if (isset($response_data['request_id'])) { echo "request_id={$response_data['request_id']}\n";} echo "code={$status_code}\n"; if (isset($response_data['message'])) { echo "message={$response_data['message']}\n";} else { echo "message=Unknown error\n";} } ?>
响应示例
寝室公约的第二条规定如下: > 寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。 如果需要了解更多的公约内容或其他信息,请随时告诉我!
Node.js
需安装相关依赖:
npm install axios
请求示例
const axios = require('axios'); async function callDashScope() { // 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。 const apiKey = process.env.DASHSCOPE_API_KEY; const appId = 'YOUR_APP_ID';// 替换为实际的应用 ID const pluginCode = 'YOUR_PLUGIN_CODE';// 替换为实际的插件ID const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`; const data = { input: { prompt: "寝室公约内容", biz_params: { user_defined_params: { [pluginCode]: { // article_index为自定义插件的变量,替换为实际的插件变量 'article_index': 6 } }, user_defined_tokens: { [pluginCode]: { // YOUR_TOKEN替换为实际的鉴权信息,如API key user_token: 'YOUR_TOKEN' } } } }, parameters: {}, debug: {} }; try { console.log("Sending request to DashScope API..."); const response = await axios.post(url, data, { headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' } }); if (response.status === 200) { if (response.data.output && response.data.output.text) { console.log(`${response.data.output.text}`); } } else { console.log("Request failed:"); if (response.data.request_id) { console.log(`request_id=${response.data.request_id}`); } console.log(`code=${response.status}`); if (response.data.message) { console.log(`message=${response.data.message}`); } else { console.log('message=Unknown error'); } } } catch (error) { console.error(`Error calling DashScope: ${error.message}`); if (error.response) { console.error(`Response status: ${error.response.status}`); console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`); } } } callDashScope();
响应示例
寝室公约的第六条规定:养成良好的作息习惯,每一位寝室成员都享有休息的权利和承担保证他人休息权利和义务。如果你需要了解更多的规定内容,请进一步说明。
C#
请求示例
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-intl.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 // YOUR_TOKEN替换为实际的Token,如API key string jsonContent = $@"{{ ""input"": {{ ""prompt"": ""寝室公约内容"", ""biz_params"": {{ ""user_defined_params"": {{ ""{pluginCode}"": {{ ""article_index"": 2 }} }}, ""user_defined_tokens"": {{ ""{pluginCode}"": {{ ""user_token"": ""YOUR_TOKEN"" }} }} }} }}, ""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}"); } } } }
响应示例
{ "output": { "finish_reason": "stop", "session_id": "1a1913a9922a401f8eba36df8ea1a062", "text": "寝室公约的第二条规定如下: 寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。 如需了解更详细的公约内容,请进一步指明。" }, "usage": { "models": [ { "output_tokens": 66, "model_id": "qwen-max", "input_tokens": 802 } ] }, "request_id": "04bac806-c5e6-9fab-a846-a66641862be9" }
Go
请求示例
package main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" ) func main() { // 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。 apiKey := os.Getenv("DASHSCOPE_API_KEY") appId := "YOUR_APP_ID" // 替换为实际的应用 ID pluginCode := "YOUR_PLUGIN_CODE" // 替换为实际的插件 ID if apiKey == "" { fmt.Println("请确保设置了DASHSCOPE_API_KEY。") return } url := fmt.Sprintf("https://dashscope-intl.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": 10, }, }, "user_defined_tokens": map[string]interface{}{ pluginCode: map[string]interface{}{ "user_token": "YOUR_USER_TOKEN", // 替换实际的鉴权 token,如API key }, }, }, }, "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)) } }
响应示例
{ "output": { "finish_reason": "stop", "session_id": "b8e051ba7e954ff8919208e7b84430fa", "text": "寝室公约的第十条规定,寝室成员应共同努力,营造和维护内务整洁干净、美观、高文化品味的寝室环境。如果需要了解完整的寝室公约内容,可能还需要查看其他条款或直接咨询宿舍管理部门。对于更多具体内容,您还有想要了解的部分吗?" }, "usage": { "models": [ { "output_tokens": 70, "model_id": "qwen-max", "input_tokens": 855 } ] }, "request_id": "0921ee34-2754-9616-a826-cea33a0e0a14" }
流式输出
大模型并不是一次性生成最终结果,而是逐步生成中间结果,最终结果由中间结果拼接而成。使用非流式输出方式需要等待模型生成结束后再将生成的中间结果拼接后返回,而流式输出可以实时地将中间结果返回,您可以在模型进行输出的同时进行阅读,减少等待模型回复的时间。
流式输出的实现在Python SDK中需要设置stream
为True,Java SDK中流式接口为streamCall
,HTTP调用时需要设置Header中的 X-DashScope-SSE
为 enable。
工作流应用和智能体编排应用的流式输出实现还需要设置has_thoughts
为True,结果在thoughts
字段中返回。
如果您想要增量输出回复则设置incremental_output
为True。
参考下方示例:
智能体应用流式输出调用示例如下:
Python
请求示例
import os from http import HTTPStatus from dashscope import Application import dashscope dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1' 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://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code') else: print(f'{response.output.text}\n') # 处理只输出文本text
响应示例
我是来自 阿里 云 的大规模语言模型 ,我叫通 义千问。
Java
请求示例
// 建议dashscope SDK的版本 >= 2.15.0 import com.alibaba.dashscope.app.*; import com.alibaba.dashscope.exception.ApiException; import com.alibaba.dashscope.exception.InputRequiredException; import com.alibaba.dashscope.exception.NoApiKeyException; import io.reactivex.Flowable;// 流式输出 // 智能体应用调用实现流式输出结果 import com.alibaba.dashscope.utils.Constants; public class Main { static { Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1"; } 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://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code"); } System.exit(0); } }
响应示例
我是阿里 云 开发的一款超大规模语言 模型,我叫 通义千问 。
HTTP
curl
请求示例
curl -X POST https://dashscope-intl.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。
响应示例
id:1 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":"我是"},"usage":{"models":[{"input_tokens":203,"output_tokens":1,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"} id:2 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":"来自"},"usage":{"models":[{"input_tokens":203,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"} id:3 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":"阿里"},"usage":{"models":[{"input_tokens":203,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"} id:4 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":"云"},"usage":{"models":[{"input_tokens":203,"output_tokens":4,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"} id:5 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":"的超大规模语言"},"usage":{"models":[{"input_tokens":203,"output_tokens":8,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"} id:6 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":"模型,我叫"},"usage":{"models":[{"input_tokens":203,"output_tokens":12,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"} id:7 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":"通义千问"},"usage":{"models":[{"input_tokens":203,"output_tokens":16,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"} id:8 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"null","text":"。"},"usage":{"models":[{"input_tokens":203,"output_tokens":17,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"} id:9 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"70ac158ae65f4764b9228a52951f3711","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":203,"output_tokens":17,"model_id":"qwen-max"}]},"request_id":"f66273ce-1a4d-9107-9c8a-da2a0f7267b5"}
PHP
请求示例
<?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-intl.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"; } ?>
响应示例
id:1 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":"我是阿里"},"usage":{"models":[{"input_tokens":58,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"} id:2 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":"云"},"usage":{"models":[{"input_tokens":58,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"} id:3 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":"开发"},"usage":{"models":[{"input_tokens":58,"output_tokens":4,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"} id:4 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":"的一款超大规模语言"},"usage":{"models":[{"input_tokens":58,"output_tokens":8,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"} id:5 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":"模型,我叫"},"usage":{"models":[{"input_tokens":58,"output_tokens":12,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"} id:6 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":"通义千问"},"usage":{"models":[{"input_tokens":58,"output_tokens":16,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"} id:7 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"null","text":"。"},"usage":{"models":[{"input_tokens":58,"output_tokens":17,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"} id:8 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"232f8a3622774c5182997c6f262c59f9","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":58,"output_tokens":17,"model_id":"qwen-max"}]},"request_id":"e682ec04-28a5-9957-ac48-76f87693cab5"}
Node.js
需安装相关依赖:
npm install axios
请求示例
const axios = require('axios'); async function callDashScope() { //若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。 const apiKey = process.env.DASHSCOPE_API_KEY; const appId = 'YOUR_APP_ID';// 替换为实际的应用 ID const url = `https://dashscope-intl.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();
响应示例
id:1 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"bb9fb75687104983ae47fc1f34ef36a1","finish_reason":"null","text":"你好!"},"usage":{"models":[{"input_tokens":56,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"d96ec7e0-5ad8-9f19-82c1-9c87f86e12b8"} id:2 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"bb9fb75687104983ae47fc1f34ef36a1","finish_reason":"null","text":"有什么"},"usage":{"models":[{"input_tokens":56,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"d96ec7e0-5ad8-9f19-82c1-9c87f86e12b8"} id:3 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"bb9fb75687104983ae47fc1f34ef36a1","finish_reason":"null","text":"可以帮助"},"usage":{"models":[{"input_tokens":56,"output_tokens":4,"model_id":"qwen-max"}]},"request_id":"d96ec7e0-5ad8-9f19-82c1-9c87f86e12b8"} id:4 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"bb9fb75687104983ae47fc1f34ef36a1","finish_reason":"null","text":"你的吗?"},"usage":{"models":[{"input_tokens":56,"output_tokens":7,"model_id":"qwen-max"}]},"request_id":"d96ec7e0-5ad8-9f19-82c1-9c87f86e12b8"} id:5 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"bb9fb75687104983ae47fc1f34ef36a1","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":56,"output_tokens":7,"model_id":"qwen-max"}]},"request_id":"d96ec7e0-5ad8-9f19-82c1-9c87f86e12b8"}
C#
请求示例
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-intl.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"); 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}"); } } } }
响应示例
id:1 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"0c60c5cc649f431193dbabfd00973bda","finish_reason":"null","text":"我是"},"usage":{"models":[{"input_tokens":74,"output_tokens":1,"model_id":"qwen-plus"}]},"request_id":"6b83b0a8-0c82-935b-809a-12bbde366add"} id:2 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"0c60c5cc649f431193dbabfd00973bda","finish_reason":"null","text":"通"},"usage":{"models":[{"input_tokens":74,"output_tokens":2,"model_id":"qwen-plus"}]},"request_id":"6b83b0a8-0c82-935b-809a-12bbde366add"} id:3 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"0c60c5cc649f431193dbabfd00973bda","finish_reason":"null","text":"义"},"usage":{"models":[{"input_tokens":74,"output_tokens":3,"model_id":"qwen-plus"}]},"request_id":"6b83b0a8-0c82-935b-809a-12bbde366add"} id:4 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"0c60c5cc649f431193dbabfd00973bda","finish_reason":"null","text":"千"},"usage":{"models":[{"input_tokens":74,"output_tokens":4,"model_id":"qwen-plus"}]},"request_id":"6b83b0a8-0c82-935b-809a-12bbde366add"} id:5 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"0c60c5cc649f431193dbabfd00973bda","finish_reason":"null","text":"问,由阿里"},"usage":{"models":[{"input_tokens":74,"output_tokens":8,"model_id":"qwen-plus"}]},"request_id":"6b83b0a8-0c82-935b-809a-12bbde366add"} id:6 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"0c60c5cc649f431193dbabfd00973bda","finish_reason":"null","text":"云开发的AI"},"usage":{"models":[{"input_tokens":74,"output_tokens":12,"model_id":"qwen-plus"}]},"request_id":"6b83b0a8-0c82-935b-809a-12bbde366add"} id:7 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"0c60c5cc649f431193dbabfd00973bda","finish_reason":"null","text":"助手。我被"},"usage":{"models":[{"input_tokens":74,"output_tokens":16,"model_id":"qwen-plus"}]},"request_id":"6b83b0a8-0c82-935b-809a-12bbde366add"} id:8 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"0c60c5cc649f431193dbabfd00973bda","finish_reason":"null","text":"设计用来帮助用户"},"usage":{"models":[{"input_tokens":74,"output_tokens":20,"model_id":"qwen-plus"}]},"request_id":"6b83b0a8-0c82-935b-809a-12bbde366add"} id:9
Go
请求示例
package main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" ) func main() { // 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。 apiKey := os.Getenv("DASHSCOPE_API_KEY") appId := "YOUR_APP_ID" // 替换为实际的应用 ID if apiKey == "" { fmt.Println("请确保设置了DASHSCOPE_API_KEY。") return } url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId) // 创建请求体 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 } // 设置请求头 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() // 读取响应 body, err := io.ReadAll(resp.Body) if err != nil { fmt.Printf("Failed to read response: %v\n", err) return } // 处理响应 if resp.StatusCode == http.StatusOK { fmt.Println("Request successful:") fmt.Println(string(body)) } else { fmt.Printf("Request failed with status code: %d\n", resp.StatusCode) fmt.Println(string(body)) } }
响应示例
Request successful: id:1 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"我是"},"usage":{"models":[{"input_tokens":74,"output_tokens":1,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"} id:2 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"阿里"},"usage":{"models":[{"input_tokens":74,"output_tokens":2,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"} id:3 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"云"},"usage":{"models":[{"input_tokens":74,"output_tokens":3,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"} id:4 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"开发"},"usage":{"models":[{"input_tokens":74,"output_tokens":4,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"} id:5 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"的一款超大规模语言"},"usage":{"models":[{"input_tokens":74,"output_tokens":8,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"} id:6 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"模型,我叫"},"usage":{"models":[{"input_tokens":74,"output_tokens":12,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"} id:7 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"通义千问"},"usage":{"models":[{"input_tokens":74,"output_tokens":16,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"} id:8 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"。我被设计"},"usage":{"models":[{"input_tokens":74,"output_tokens":20,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"} id:9 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"用来帮助用户生成"},"usage":{"models":[{"input_tokens":74,"output_tokens":24,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"} id:10 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"各种文本,如"},"usage":{"models":[{"input_tokens":74,"output_tokens":28,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"} id:11 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"文章、故事、"},"usage":{"models":[{"input_tokens":74,"output_tokens":32,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"} id:12 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"诗歌、故事等"},"usage":{"models":[{"input_tokens":74,"output_tokens":36,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"} id:13 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":",并能根据不同的"},"usage":{"models":[{"input_tokens":74,"output_tokens":40,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"} id:14 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"场景和需求进行"},"usage":{"models":[{"input_tokens":74,"output_tokens":44,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"} id:15 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"调整和优化。"},"usage":{"models":[{"input_tokens":74,"output_tokens":48,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"} id:16 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"此外,我还能够"},"usage":{"models":[{"input_tokens":74,"output_tokens":52,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"} id:17 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"回答各种问题,"},"usage":{"models":[{"input_tokens":74,"output_tokens":56,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"} id:18 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"提供信息查询、"},"usage":{"models":[{"input_tokens":74,"output_tokens":60,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"} id:19 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"知识解答、解决问题"},"usage":{"models":[{"input_tokens":74,"output_tokens":64,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"} id:20 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"等服务。如果您"},"usage":{"models":[{"input_tokens":74,"output_tokens":68,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"} id:21 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"有任何问题或需要"},"usage":{"models":[{"input_tokens":74,"output_tokens":72,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"} id:22 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"任何帮助,请随时"},"usage":{"models":[{"input_tokens":74,"output_tokens":76,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"} id:23 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"告诉我,我会尽力"},"usage":{"models":[{"input_tokens":74,"output_tokens":80,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"} id:24 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"null","text":"提供支持。"},"usage":{"models":[{"input_tokens":74,"output_tokens":83,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"} id:25 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"12455d1550ca4da1bcb9b2fb2ce42f74","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":74,"output_tokens":83,"model_id":"qwen-plus"}]},"request_id":"5d50e301-e23f-9a5f-aaa7-faf431d6d3d8"}
工作流应用和智能体编排应用的流式输出实现还需要设置
has_thoughts
为True。所有节点的流式输出(能流式的会流式输出比如LLM节点,非流式的会同步输出比如文本转换节点)在应用API中的thoughts
字段返回。这样既不会破坏结束节点最终的结果,也能满足用户多变的流式需求。参考下面多节点示例。如图所示已发布的工作流应用配置,对杭州的美食和景点进行流式输出。
通过API调用。
Python
请求示例
import os from http import HTTPStatus from dashscope import Application import dashscope dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1' biz_params = { "city": "杭州"} responses = Application.call( # 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。 api_key=os.getenv("DASHSCOPE_API_KEY"), # 替换为实际的应用 ID app_id='YOUR_APP_ID', prompt='你好', biz_params=biz_params, # 开启流式输出 stream=True, # incremental_output为true开启增量输出,为false关闭增量输出,不填写默认false incremental_output=True, # 工作流应用和智能体编排应用的流式输出实现需要设置has_thoughts为True has_thoughts=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://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code') else: print(f'{response.output.thoughts}\n') # 处理输出只返回thoughts;在output的thoughts字段中返回过程信息
响应示例
[ApplicationThought(thought=None, action_type=None, response='{"nodeName":"开始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_Ilo9","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_Ilo9"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)] [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"开始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_Bsvj","nodeResult":"{\\"result\\":\\"西湖醋鱼,\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_Ilo9"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)] [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"开始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_Bsvj","nodeResult":"{\\"result\\":\\"东坡肉,\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_Ilo9"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)] [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"开始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_Bsvj","nodeResult":"{\\"result\\":\\"知味观小\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_Ilo9"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)] [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"开始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_Bsvj","nodeResult":"{\\"result\\":\\"笼包,龙井虾仁,\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_Ilo9"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)] [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"开始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_Bsvj","nodeResult":"{\\"result\\":\\"叫化鸡\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_Ilo9","nodeExecTime":"1332ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)] [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"开始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_Bsvj","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_Ilo9","nodeExecTime":"1332ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"LLM_vQDv","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_vQDv"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)] [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"开始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_Bsvj","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_Ilo9","nodeExecTime":"1332ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_kBgf","nodeResult":"{\\"result\\":\\"西湖,灵隐\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_vQDv"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)] [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"开始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_Bsvj","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_Ilo9","nodeExecTime":"1332ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_kBgf","nodeResult":"{\\"result\\":\\"寺,宋城\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_vQDv"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)] [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"开始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_Bsvj","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_Ilo9","nodeExecTime":"1332ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_kBgf","nodeResult":"{\\"result\\":\\",西溪湿地\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_vQDv"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)] [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"开始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_Bsvj","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_Ilo9","nodeExecTime":"1332ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_kBgf","nodeResult":"{\\"result\\":\\",千岛湖\\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_vQDv"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)] [ApplicationThought(thought=None, action_type=None, response='{"nodeName":"开始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_Bsvj","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_Ilo9","nodeExecTime":"1332ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"大模型_kBgf","nodeResult":"{\\"result\\":\\"\\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_vQDv","nodeExecTime":"948ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None), ApplicationThought(thought=None, action_type=None, response='{"nodeName":"结束","nodeResult":"{\\"result\\":\\"西湖,灵隐寺,宋城,西溪湿地,千岛湖\\"}","nodeType":"End","nodeStatus":"success","nodeId":"End_DrQn7F","nodeExecTime":"1ms"}', action_name=None, action=None, action_input_stream=None, action_input=None, observation=None)]
Java
请求示例
// 建议dashscope SDK的版本 >= 2.15.0 import com.alibaba.dashscope.app.*; import com.alibaba.dashscope.exception.ApiException; import com.alibaba.dashscope.exception.InputRequiredException; import com.alibaba.dashscope.exception.NoApiKeyException; import com.alibaba.dashscope.utils.JsonUtils; import io.reactivex.Flowable; import com.alibaba.dashscope.utils.Constants; public class Main { static { Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1"; } public static void streamCall() throws NoApiKeyException, InputRequiredException { String bizParams = "{\"city\":\"杭州\"}"; 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("你好") .bizParams(JsonUtils.parse(bizParams)) .incrementalOutput(true) // 增量输出 .hasThoughts(true) // 工作流应用实现流式输出需要设置此参数为true,输出结果在thoughts字段中查看 .build(); Application application = new Application(); Flowable<ApplicationResult> result = application.streamCall(param); // 实现流式输出 result.blockingForEach(data -> { System.out.printf("%s\n",data.getOutput().getThoughts());// 处理输出只展示thoughts字段 }); } public static void main(String[] args) { try { streamCall(); } catch (ApiException | NoApiKeyException | InputRequiredException e) { System.out.printf("Exception: %s", e.getMessage()); System.out.println("请参考文档:https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code"); } System.exit(0); } }
响应示例
[ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"开始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_S78u","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_S78u"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)] [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"开始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"大模型_UTh7","nodeResult":"{\"result\":\"西湖醋鱼,\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_S78u"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)] [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"开始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"大模型_UTh7","nodeResult":"{\"result\":\"龙井虾仁\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_S78u"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)] [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"开始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"大模型_UTh7","nodeResult":"{\"result\":\",东坡肉,知味小\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_S78u"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)] [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"开始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"大模型_UTh7","nodeResult":"{\"result\":\"笼,叫花\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_S78u"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)] [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"开始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"大模型_UTh7","nodeResult":"{\"result\":\"鸡\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_S78u","nodeExecTime":"1164ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"LLM_5ZzA","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_5ZzA"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)] [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"开始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"大模型_UTh7","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_S78u","nodeExecTime":"1164ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"大模型_jjc0","nodeResult":"{\"result\":\"西湖,\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_5ZzA"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)] [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"开始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"大模型_UTh7","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_S78u","nodeExecTime":"1164ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"大模型_jjc0","nodeResult":"{\"result\":\"灵隐\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_5ZzA"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)] [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"开始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"大模型_UTh7","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_S78u","nodeExecTime":"1164ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"大模型_jjc0","nodeResult":"{\"result\":\"寺,宋城\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_5ZzA"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)] [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"开始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"大模型_UTh7","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_S78u","nodeExecTime":"1164ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"大模型_jjc0","nodeResult":"{\"result\":\",西溪湿地,千岛湖\"}","nodeType":"LLM","nodeStatus":"executing","nodeId":"LLM_5ZzA"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)] [ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"开始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"大模型_UTh7","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_S78u","nodeExecTime":"1164ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"大模型_jjc0","nodeResult":"{\"result\":\"\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_5ZzA","nodeExecTime":"938ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null), ApplicationOutput.Thought(thought=null, actionType=null, response={"nodeName":"结束","nodeResult":"{\"result\":\"西湖,灵隐寺,宋城,西溪湿地,千岛湖\"}","nodeType":"End","nodeStatus":"success","nodeId":"End_DrQn7F","nodeExecTime":"5ms"}, actionName=null, action=null, actionInputStream=null, actionInput=null, observation=null)]
HTTP
curl
请求示例
curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \ --header 'X-DashScope-SSE: enable' \ --header "Authorization: Bearer $DASHSCOPE_API_KEY" \ --header 'Content-Type: application/json' \ --data '{ "input": { "prompt": "你好", "biz_params": { "city": "杭州"} }, "parameters": { "has_thoughts": true, "incremental_output": true }, "debug": {} }'
YOUR_APP_ID替换为实际的应用 ID。
响应示例
id:1 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"2d55b40211054ac3b5f05478aea677b5","finish_reason":"null"},"usage":{},"request_id":"a8db9989-8fae-9698-a407-ab362bbb88d8"} id:2 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"}, {"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"2d55b40211054ac3b5f05478aea677b5","finish_reason":"null"},"usage":{},"request_id":"a8db9989-8fae-9698-a407-ab362bbb88d8"} id:3 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"}, {"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"西湖醋\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"2d55b40211054ac3b5f05478aea677b5","finish_reason":"null"},"usage":{},"request_id":"a8db9989-8fae-9698-a407-ab362bbb88d8"} id:4 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"}, {"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"鱼\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"2d55b40211054ac3b5f05478aea677b5","finish_reason":"null"},"usage":{},"request_id":"a8db9989-8fae-9698-a407-ab362bbb88d8"} id:5 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"}, {"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",龙井虾仁\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"2d55b40211054ac3b5f05478aea677b5","finish_reason":"null"},"usage":{},"request_id":"a8db9989-8fae-9698-a407-ab362bbb88d8"} id:6 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"}, {"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",东坡肉,叫花鸡\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"2d55b40211054ac3b5f05478aea677b5","finish_reason":"null"},"usage":{},"request_id":"a8db9989-8fae-9698-a407-ab362bbb88d8"} id:7 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"}, {"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",知味小笼\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1996ms\"}"}, {"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"2d55b40211054ac3b5f05478aea677b5","finish_reason":"null"},"usage":{},"request_id":"a8db9989-8fae-9698-a407-ab362bbb88d8"} id:8 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1996ms\"}"}, {"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"西湖,宋\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"2d55b40211054ac3b5f05478aea677b5","finish_reason":"null"},"usage":{},"request_id":"a8db9989-8fae-9698-a407-ab362bbb88d8"} id:9 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1996ms\"}"}, {"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"城,灵隐寺\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"2d55b40211054ac3b5f05478aea677b5","finish_reason":"null"},"usage":{},"request_id":"a8db9989-8fae-9698-a407-ab362bbb88d8"} id:10 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1996ms\"}"}, {"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",西溪国家湿地公园,雷\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"2d55b40211054ac3b5f05478aea677b5","finish_reason":"null"},"usage":{},"request_id":"a8db9989-8fae-9698-a407-ab362bbb88d8"} id:11 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1996ms\"}"}, {"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"峰塔\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_vQDv\",\"nodeExecTime\":\"1383ms\"}"}, {"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"西湖,宋城,灵隐寺,西溪国家湿地公园,雷峰塔\\\"}\",\"nodeType\":\"End\",\"nodeStatus\":\"success\",\"nodeId\":\"End_DrQn7F\",\"nodeExecTime\":\"1ms\"}"}],"session_id":"2d55b40211054ac3b5f05478aea677b5","finish_reason":"stop","text":"西湖,宋城,灵隐寺,西溪国家湿地公园,雷峰塔"},"usage":{},"request_id":"a8db9989-8fae-9698-a407-ab362bbb88d8"}
PHP
请求示例
<?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-intl.aliyuncs.com/api/v1/apps/$application_id/completion"; // 构造请求数据 $data = [ "input" => [ 'prompt' => '你好', 'biz_params' => [ 'city' => '杭州' ] ], "parameters" => [ 'has_thoughts' => true, // 工作流应用和编排应用必须设置此参数为true,过程信息在thoughts中返回 '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"; } ?>
响应示例
id:1 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"} id:2 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"开始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_Ilo9\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"} id:3 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"开始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"西湖醋鱼\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"} id:4 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"开始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\",\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"} id:5 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"开始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"东坡肉,知味小笼\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"} id:6 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"开始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\",龙井虾\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"} id:7 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"开始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"仁,叫化鸡\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1486ms\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"} id:8 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"开始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1486ms\"}"},{"response":"{\"nodeName\":\"LLM_vQDv\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"} id:9 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"开始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1486ms\"}"},{"response":"{\"nodeName\":\"大模型_kBgf\",\"nodeResult\":\"{\\\"result\\\":\\\"西湖,灵隐\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"} id:10 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"开始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1486ms\"}"},{"response":"{\"nodeName\":\"大模型_kBgf\",\"nodeResult\":\"{\\\"result\\\":\\\"寺,宋城\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"} id:11 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"开始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1486ms\"}"},{"response":"{\"nodeName\":\"大模型_kBgf\",\"nodeResult\":\"{\\\"result\\\":\\\",西溪湿地\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"null"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"} id:12 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"开始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_Bsvj\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"1486ms\"}"},{"response":"{\"nodeName\":\"大模型_kBgf\",\"nodeResult\":\"{\\\"result\\\":\\\",杭州塔\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_vQDv\",\"nodeExecTime\":\"899ms\"}"},{"response":"{\"nodeName\":\"结束\",\"nodeResult\":\"{\\\"result\\\":\\\"西湖,灵隐寺,宋城,西溪湿地,杭州塔\\\"}\",\"nodeType\":\"End\",\"nodeStatus\":\"success\",\"nodeId\":\"End_DrQn7F\",\"nodeExecTime\":\"0ms\"}"}],"session_id":"a3b73a6db84d444d8efdab2b2e754f52","finish_reason":"stop","text":"西湖,灵隐寺,宋城,西溪湿地,杭州塔"},"usage":{},"request_id":"795e98eb-5de3-969f-a9b5-5983d1b6d955"}
Node.js
需安装相关依赖:
npm install axios
请求示例
const axios = require('axios'); async function callDashScope() { // 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。 const apiKey = process.env.DASHSCOPE_API_KEY; const appId = 'YOUR_APP_ID';// 替换为实际的应用 ID const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`; const data = { input: { prompt: "你好", biz_params:{ 'city':'杭州' } }, parameters: { 'incremental_output' : 'true', 'has_thoughts':'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) { console.log("Request successful:"); // 处理流式响应 response.data.on('data', (chunk) => { console.log(`Received chunk: ${chunk.toString()}`); }); response.data.on('end', () => { console.log("Stream ended."); }); response.data.on('error', (error) => { console.error(`Stream error: ${error.message}`); }); } 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();
响应示例
/opt/homebrew/bin/node ./index.js Sending request to DashScope API... Request successful: Received chunk: id:1 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:2 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:3 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"西湖醋\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:4 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"鱼,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:5 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"龙井虾仁\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:6 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",东坡肉\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:7 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",知味观\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:8 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"小笼包,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:9 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"叫花鸡\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"2180ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:10 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"2180ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"西湖,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:11 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"2180ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"灵隐\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:12 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"2180ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"寺,宋城,西溪湿地\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:13 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"2180ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",千岛湖\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"null"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Received chunk: id:14 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"2180ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_5ZzA\",\"nodeExecTime\":\"855ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"西湖,灵隐寺,宋城,西溪湿地,千岛湖\\\"}\",\"nodeType\":\"End\",\"nodeStatus\":\"success\",\"nodeId\":\"End_DrQn7F\",\"nodeExecTime\":\"1ms\"}"}],"session_id":"7e9fcc8be3294954815c1a0a956d5e55","finish_reason":"stop","text":"西湖,灵隐寺,宋城,西溪湿地,千岛湖"},"usage":{},"request_id":"e52dce21-16a4-9a3d-ad6c-88e8921e927f"} Stream ended.
C#
请求示例
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-intl.aliyuncs.com/api/v1/apps/{appId}/completion"; // 工作流应用和智能体编排应用实现流式输出需要设置has_thoughts为true using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); client.DefaultRequestHeaders.Add("X-DashScope-SSE", "enable"); string jsonContent = @"{ ""input"": { ""prompt"": ""你好"", ""biz_params"":{ ""city"":""杭州"" } }, ""parameters"": { ""incremental_output"": true, ""has_thoughts"": true }, ""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}"); } } } }
响应示例
id:1 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"ed976b73d9be46f7aff888b9440fe5d6","finish_reason":"null"},"usage":{},"request_id":"32c86a8c-dbd1-9c12-a175-8837224a13e0"} id:2 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"ed976b73d9be46f7aff888b9440fe5d6","finish_reason":"null"},"usage":{},"request_id":"32c86a8c-dbd1-9c12-a175-8837224a13e0"} id:3 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"西湖醋\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"ed976b73d9be46f7aff888b9440fe5d6","finish_reason":"null"},"usage":{},"request_id":"32c86a8c-dbd1-9c12-a175-8837224a13e0"} id:4 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"鱼,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"ed976b73d9be46f7aff888b9440fe5d6","finish_reason":"null"},"usage":{},"request_id":"32c86a8c-dbd1-9c12-a175-8837224a13e0"} id:5 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"龙井虾仁\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"ed976b73d9be46f7aff888b9440fe5d6","finish_reason":"null"},"usage":{},"request_id":"32c86a8c-dbd1-9c12-a175-8837224a13e0"} id:6 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",知味小\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"ed976b73d9be46f7aff888b9440fe5d6","finish_reason":"null"},"usage":{},"request_id":"32c86a8c-dbd1-9c12-a175-8837224a13e0"} id:7 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"笼,东坡\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"ed976b73d9be46f7aff888b9440fe5d6","finish_reason":"null"},"usage":{},"request_id":"32c86a8c-dbd1-9c12-a175-8837224a13e0"} id:8 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"肉,叫花\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_Ilo9\"}"}],"session_id":"ed976b73d9be46f7aff888b9440fe5d6","finish_reason":"null"},"usage":{},"request_id":"32c86a8c-dbd1-9c12-a175-8837224a13e0"} id:9 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"鸡\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"2199ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"ed976b73d9be46f7aff888b9440fe5d6","finish_reason":"null"},"usage":{},"request_id":"32c86a8c-dbd1-9c12-a175-8837224a13e0"} id:10 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"2199ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"西湖,灵隐\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"ed976b73d9be46f7aff888b9440fe5d6","finish_reason":"null"},"usage":{},"request_id":"32c86a8c-dbd1-9c12-a175-8837224a13e0"} id:11 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"2199ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"寺,宋城\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"ed976b73d9be46f7aff888b9440fe5d6","finish_reason":"null"},"usage":{},"request_id":"32c86a8c-dbd1-9c12-a175-8837224a13e0"} id:12 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"2199ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",西溪湿地\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"ed976b73d9be46f7aff888b9440fe5d6","finish_reason":"null"},"usage":{},"request_id":"32c86a8c-dbd1-9c12-a175-8837224a13e0"} id:13 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"2199ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",雷峰塔\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_vQDv\"}"}],"session_id":"ed976b73d9be46f7aff888b9440fe5d6","finish_reason":"null"},"usage":{},"request_id":"32c86a8c-dbd1-9c12-a175-8837224a13e0"} id:14 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_Ilo9\",\"nodeExecTime\":\"2199ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_vQDv\",\"nodeExecTime\":\"1145ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"西湖,灵隐寺,宋城,西溪湿地,雷峰塔\\\"}\",\"nodeType\":\"End\",\"nodeStatus\":\"success\",\"nodeId\":\"End_DrQn7F\",\"nodeExecTime\":\"0ms\"}"}],"session_id":"ed976b73d9be46f7aff888b9440fe5d6","finish_reason":"stop","text":"西湖,灵隐寺,宋城,西溪湿地,雷峰塔"},"usage":{},"request_id":"32c86a8c-dbd1-9c12-a175-8837224a13e0"}
Go
请求示例
package main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" ) func main() { // 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。 apiKey := os.Getenv("DASHSCOPE_API_KEY") appId := "YOUR_APP_ID" // 替换为实际的应用 ID if apiKey == "" { fmt.Println("请确保设置了DASHSCOPE_API_KEY。") return } url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId) // 创建请求体 requestBody := map[string]interface{}{ "input": map[string]interface{}{ "prompt": "你好", "biz_params": map[string]interface{}{ "city": "杭州", // 参数透传 }, }, "parameters": map[string]interface{}{ "incremental_output": true, // 设置此参数为true可以增量输出结果 "has_thoughts": true, // 工作流应用和智能体编排应用实现流式输出需要设置此参数为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 } // 设置请求头 req.Header.Set("Authorization", "Bearer "+apiKey) req.Header.Set("Content-Type", "application/json") req.Header.Set("X-DashScope-SSE", "enable") // 流式输出请求需设置此参数为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() // 读取响应 body, err := io.ReadAll(resp.Body) if err != nil { fmt.Printf("Failed to read response: %v\n", err) return } // 处理响应 if resp.StatusCode == http.StatusOK { fmt.Println("Request successful:") fmt.Println(string(body)) } else { fmt.Printf("Request failed with status code: %d\n", resp.StatusCode) fmt.Println(string(body)) } }
响应示例
Request successful: id:1 event:result :HTTP_STATUS/200 data:{"output":{"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:2 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:3 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"西湖醋\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:4 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"鱼,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:5 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"龙井虾仁\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:6 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",东坡肉\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:7 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",知味小\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:8 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"笼,叫花\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_S78u\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:9 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"鸡\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"1680ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:10 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"1680ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"西湖,灵隐\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:11 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"1680ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"寺,宋城\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:12 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"1680ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",西溪湿地\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:13 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"1680ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\",千岛湖\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_5ZzA\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:14 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"1680ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_5ZzA\",\"nodeExecTime\":\"1760ms\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"null"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"} id:15 event:result :HTTP_STATUS/200 data:{"output":{"thoughts":[{"response":"{\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_S78u\",\"nodeExecTime\":\"1680ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_5ZzA\",\"nodeExecTime\":\"1760ms\"}"},{"response":"{\"nodeResult\":\"{\\\"result\\\":\\\"西湖,灵隐寺,宋城,西溪湿地,千岛湖\\\"}\",\"nodeType\":\"End\",\"nodeStatus\":\"success\",\"nodeId\":\"End_DrQn7F\",\"nodeExecTime\":\"1ms\"}"}],"session_id":"f3f5c63ec17d44b2a2e9aa18f0e6a22c","finish_reason":"stop","text":"西湖,灵隐寺,宋城,西溪湿地,千岛湖"},"usage":{},"request_id":"dfea28e9-801b-9c10-a4e7-c8fef790d34f"}
thoughts
内每一项都是一个节点的执行详情,如下以一个LLM节点结果为例。
data: { "output": { "thoughts": [ { "response": "{"nodeName":"开始","nodeType":"Start","nodeStatus":"success","nodeId":"Start_bYxoRU","nodeExecTime":"0ms"}" }, { "response": "{"nodeName":"大模型_Bsvj","nodeResult":"{\"result\":\"仁,叫化鸡\"}","nodeType":"LLM","nodeStatus":"success","nodeId":"LLM_Ilo9","nodeExecTime":"1486ms"}" } ], "session_id": "a3b73a6db84d444d8efdab2b2e754f52", "finish_reason": "null" }, "usage": { }, "request_id": "795e98eb-5de3-969f-a9b5-5983d1b6d955" }
如果用户关注一个LLM节点(以上方LLM_Ilo9为例)的流式结果,可以关注每次推送的
thoughts
中nodeId为LLM_Ilo9的节点输出。如果节点发生失败,则整个任务也会失败。
知识库过滤
知识库功能作为百炼的RAG能力,能有效的为大模型补充私有知识和提供最新信息。智能体应用开启知识检索增强功能或工作流应用创建知识库节点后,您在调用应用时可以指定要检索的范围,提高大模型的回答准确性。更多知识库功能请参考:知识库。
调用时知识库ID是必传参数,但如果在应用中配置了知识库,则调用时可不传入。
检索指定的知识库:在
rag_options
中传入知识库ID。知识库ID可以在知识索引页面获取,也可以使用调用CreateIndex接口返回的
Data.Id
。目前仅非结构化数据的知识库支持通过API进行创建。
可以是智能体应用已经关联的知识库,也可以是没有关联的知识库。
只会在指定的知识库里检索。例如,网页端的智能体应用里引用了知识库A,而API调用时只指定了知识库B,那么不会检索知识库A,只会检索知识库B。
此处选择了百炼系列手机产品介绍.docx作为一个非结构化数据知识库的文件作为示例:
Python
请求示例
import os from http import HTTPStatus # 建议dashscope SDK 的版本 >= 1.20.11 from dashscope import Application import dashscope dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1' 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://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code') else: print('%s\n' % (response.output.text)) # 处理只输出文本text # print('%s\n' % (response.usage))
响应示例
根据您的预算,我推荐您选择**百炼 Zephyr Z9**。这款手机的参考售价在2499-2799元之间,符合您的预算需求。它拥有轻巧的6.4英寸1080 x 2340像素屏幕设计,搭配128GB存储与6GB RAM,适合日常使用。此外,它还配备了4000mAh电池以及支持30倍数字变焦的镜头,能够很好地满足拍照及续航的需求。如果您追求的是轻薄便携且功能全面的手机,那么百炼 Zephyr Z9会是一个不错的选择。
Java
请求示例
// 建议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; import com.alibaba.dashscope.utils.Constants; public class Main { static { Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1"; } 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://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code"); } System.exit(0); } }
响应示例
在3000元预算范围内,我推荐您考虑**百炼 Zephyr Z9**。这款手机定价在2499至2799之间,非常符合您的预算要求。它具有以下特点: - **轻巧设计**:6.4英寸屏幕大小适中,便于单手操作。 - **性能均衡**:搭载128GB存储与6GB RAM,对于日常使用来说足够了。 - **续航能力**:配备4000mAh电池,可以满足一天的正常使用需求。 - **拍照功能**:具备30倍数字变焦镜头,适合捕捉远处景物。 如果您更注重游戏体验或对其他方面有特别的需求,请告诉我,以便我能提供更加个性化的建议!
HTTP
curl
请求示例
curl -X POST https://dashscope-intl.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。
响应示例
{"output":{"finish_reason":"stop","session_id":"d1208af96f9a4d8390e9b29e86f0623c", "text":"在3000元以下的价格范围内,我向您推荐百炼 Zephyr Z9。 这款手机定价在2499至2799元之间,完美符合您的预算要求。 它拥有轻巧的6.4英寸1080 x 2340像素显示屏,搭配了128GB的存储空间和6GB的RAM,足以应对日常使用中的各种应用程序和多任务处理。 此外,它配备了一块4000mAh的电池,能够确保您一整天的使用无虞,还搭载了30倍数字变焦镜头,方便您捕捉生活中的细节。 综上所述,百炼 Zephyr Z9在性价比、设计与功能上都是一个不错的选择。"}, "usage":{"models":[{"output_tokens":158,"model_id":"qwen-max","input_tokens":1025}]}, "request_id":"eb2d40f7-bede-9d48-88dc-08abdcdd0351"}%
PHP
请求示例
<?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-intl.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";} } ?>
响应示例
在3000元以下的预算范围内,我推荐您考虑**百炼 Zephyr Z9**。这款手机定价在2499-2799元之间,非常适合您的预算。它具有轻巧的设计,配备6.4英寸1080 x 2340像素屏幕、128GB存储与6GB RAM,能够很好地满足日常使用需求。此外,其4000mAh电池可以保证一天的正常使用,并且配备了30倍数字变焦镜头来捕捉远处细节,既轻薄又不失强大功能。
Node.js
需安装相关依赖:
npm install axios
请求示例
const axios = require('axios'); async function callDashScope() { // 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。 const apiKey = process.env.DASHSCOPE_API_KEY; const appId = 'YOUR_APP_ID';//替换为实际的应用 ID const url = `https://dashscope-intl.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();
响应示例
在3000元以下的预算内,我推荐您考虑**百炼 Zephyr Z9**。这款手机参考售价为3999-4299元,但如果能赶上促销活动或折扣,可能会降到您的预算范围内。 ### 百炼 Zephyr Z9 ——轻薄便携的艺术 - **屏幕**: 6.4英寸 1080 x 2340像素 - **存储与RAM**: 128GB存储 / 6GB RAM - **电池**: 4000mAh - **相机**: 30倍数字变焦镜头 这款手机的特点是轻薄便携,日常使用非常方便,而且具有不错的续航能力。如果您更关注性价比和日常使用体验,百炼 Zephyr Z9 是一个不错的选择。 如果您的预算非常严格,建议关注电商平台的促销活动,或者考虑其他品牌的同价位手机。希望这些建议对您有所帮助!
C#
请求示例
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-intl.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}"); } } } }
响应示例
{ "output": { "finish_reason": "stop", "session_id": "2344ddc540ec4c5fa110b92d813d3807", "text": "根据您的预算,我推荐您考虑**百炼 Zephyr Z9**。这款手机的参考售价在2499-2799元之间,符合您的预算需求。它拥有6.4英寸1080 x 2340像素屏幕、128GB存储空间和6GB RAM,对于日常使用来说已经足够了。此外,4000mAh电池可以保证一天内的正常使用,而30倍数字变焦镜头则能满足您拍摄远处景物的需求。这是一款轻薄便携且功能全面的选择。" }, "usage": { "models": [ { "output_tokens": 121, "model_id": "qwen-max", "input_tokens": 1841 } ] }, "request_id": "99fceedf-2034-9fb0-aaad-9c837136801f" }
Go
请求示例
package main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" ) func main() { // 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。 apiKey := os.Getenv("DASHSCOPE_API_KEY") appId := "YOUR_APP_ID" // 替换为实际的应用 ID if apiKey == "" { fmt.Println("请确保设置了DASHSCOPE_API_KEY。") return } url := fmt.Sprintf("https://dashscope-intl.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)) } }
响应示例
{ "output": { "finish_reason": "stop", "session_id": "fadbb4d1fe094ade88985620363506e6", "text": "根据您的预算,我为您推荐**百炼 Zephyr Z9**。这款手机的价格在2499-2799元之间,非常适合3000元以下的预算需求。它拥有轻巧的6.4英寸1080 x 2340像素屏幕设计,搭配128GB存储与6GB RAM,能够满足日常使用的需求。同时,4000mAh电池确保了一天的使用无忧,而30倍数字变焦镜头则可以捕捉远处的细节,是一款性价比很高的选择。" }, "usage": { "models": [ { "output_tokens": 119, "model_id": "qwen-max", "input_tokens": 1055 } ] }, "request_id": "3a755dd7-58a0-9a5e-8a07-b85b1db838a6" }
检索指定的非结构化数据文档:在
rag_options
中传入知识库ID、文档ID、文档标签tags或文档元数据metadata(键值对)。检索指定的文档ID:传入文档ID。
文档ID可以在数据管理页面获取。
可以传入多个文档ID,仅支持已建知识索引的文档。
传入文档ID时,传入文档所属的知识库ID才会生效。
只会在指定的文档里检索。例如:网页端的智能体应用里引用了知识库A,而API调用时指定了文档ID和其所属的知识库B的ID,那么不会检索知识库A的文档,只会检索知识库B的文档。
此处示例选择百炼系列手机产品介绍.docx作为非结构化数据知识库文件。
Python
请求示例
import os from http import HTTPStatus # 建议dashscope SDK 的版本 >= 1.20.11 from dashscope import Application import dashscope dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1' 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,逗号隔开多个 "file_ids": ["YOUR_FILE_ID1", "YOUR_FILE_ID2"], # 替换为实际的非结构化文档 ID,逗号隔开多个 "metadata_filter": { # 文档元数据键值对,逗号隔开多个 "key1": "value1", "key2": "value2" }, "tags": ["tag1", "tag2"] # 文档标签,逗号隔开多个 } ) 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://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code') else: print('%s\n' % (response.output))
响应示例
{ "text": "在3000元以下的预算范围内,我推荐您考虑**百炼 Zephyr Z9**。这款手机的特点如下: - **屏幕**:6.4英寸 1080 x 2340像素,适合日常使用和娱乐。 - **内存与存储**:6GB RAM + 128GB 存储空间,能够满足大部分用户对于流畅度以及存储的需求。 - **电池容量**:4000mAh,提供了一整天的使用保障。 - **摄像头功能**:配备了一个支持30倍数字变焦的镜头,可以捕捉到更远距离的细节。 - **其他特性**:设计轻薄便携,易于携带。 参考售价为2499至2799元之间,正好符合您的预算要求,并且提供了不错的性价比。希望这些建议对您有所帮助!", "finish_reason": "stop", "session_id": "10bdea3d1435406aad8750538b701bee", "thoughts": null, "doc_references": null }
Java
请求示例
// 建议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 com.google.gson.JsonObject; import java.util.List; import com.alibaba.dashscope.utils.Constants; public class Main { static { Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1"; } public static void streamCall() throws NoApiKeyException, InputRequiredException { JsonObject metadataFilter = new JsonObject(); metadataFilter.addProperty("key1", "value1"); // 元数据键值对 metadataFilter.addProperty("key2", "value2"); // 多个重复调用addProperty ApplicationParam param = ApplicationParam.builder() // 若没有配置环境变量,可用百炼API Key将下行替换为:.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。 .apiKey(System.getenv("DASHSCOPE_API_KEY")) .appId("a1930cf4ad2a4153b8887f7b17969ba3") // 替换为实际的应用ID .prompt("请帮我推荐一款3000元左右的手机") .ragOptions(RagOptions.builder() .pipelineIds(List.of("PIPELINES_ID1","PIPELINES_ID2")) // 替换为实际指定的知识库 ID,逗号隔开多个 .fileIds(List.of("FILE_ID1", "FILE_ID2")) // 替换为实际指定的非结构化文档 ID,逗号隔开多个 .tags(List.of("tags1", "tags2")) // 替换为指定的文档标签 ID,逗号隔开多个 .metadataFilter(metadataFilter) .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://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code"); } System.exit(0); } }
响应示例
根据您的预算,我为您推荐**百炼 Zephyr Z9**。这款手机的价格在2499-2799元之间,非常适合您3000元左右的预算范围。 ### 百炼 Zephyr Z9 产品亮点: - **屏幕**:6.4英寸、1080 x 2340像素,提供清晰细腻的视觉体验。 - **存储与运行内存**:128GB存储空间和6GB RAM,足以应对日常使用需求。 - **电池**:4000mAh容量电池可以确保一整天的正常使用。 - **摄像头**:支持30倍数字变焦镜头,能够捕捉远处细节。 - **设计**:轻薄便携,适合追求时尚与便捷的用户。 这款手机不仅价格适中,而且配置均衡,在外观设计上也非常出色,是这个价位段非常不错的选择。希望这些建议对您有所帮助!如果还有其他需求或疑问,请随时告诉我。
HTTP
curl
请求示例
curl -X POST https://dashscope-intl.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"], "file_ids":["YOUR_FILE_ID1"], "metadata_filter":{ "name":"张三"}, "tags":"手机" } }, "debug": {} }'
YOUR_APP_ID替换为实际的应用 ID,YOUR_PIPELINE_ID1替换为指定的知识库ID,YOUR_FILE_ID1替换为指定的非结构化文档ID,metadata_filter内的键值对替换为实际的元数据。
响应示例
{"output":{"finish_reason":"stop","session_id":"f2f114864dd24a458f923aab0ec99a1d", "text":"根据您的预算,我推荐您考虑“通义 Vivid 7”。它拥有 6.5 英寸 1080 x 2400 像素的全面屏,具备 AI 智能摄影功能,能够让您拍摄出具有专业级色彩与细节的照片。 其硬件配置包括 8GB RAM 和 128GB 存储空间,确保了流畅的操作体验;4500mAh 的电池容量也能较好地满足日常使用需求。 此外,侧面指纹解锁的设计既便捷又安全。参考售价为 2999 至 3299 元之间,符合您的预算范围。"}, "usage":{"models":[{"output_tokens":141,"model_id":"qwen-plus","input_tokens":1610}]}, "request_id":"d815d3d1-8cef-95e2-b895-89fc8d0e0f84"}%
PHP
请求示例
<?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-intl.aliyuncs.com/api/v1/apps/$application_id/completion"; // 构造请求数据 $data = [ "input" => [ 'prompt' => '请帮我推荐一款3000元以下的手机' ], "parameters" => [ 'rag_options' => [ 'pipeline_ids' => ['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2'],// 替换为指定的知识库 ID,逗号隔开多个 'file_ids' => ['YOUR_FILE_ID1','YOUR_FILE_ID2'],// 替换为实际的文档 ID,逗号隔开多个 "metadata_filter" => [ // 元数据键值对 "key1" => "value1", "key2" => "value2" ], "tags" => ["标签1", "标签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";} } ?>
响应示例
根据您的预算,我为您推荐**百炼 Zephyr Z9**。这款手机的参考售价在2499-2799元之间,非常适合3000元以下的需求。它拥有轻巧的6.4英寸1080 x 2340像素设计,搭配128GB存储与6GB RAM,可以满足日常使用需求。此外,其配备4000mAh电池确保一天无忧,并且还有30倍数字变焦镜头捕捉远处细节,是一款既轻薄又不失强大的选择。
Node.js
需安装相关依赖:
npm install axios
请求示例
const axios = require('axios'); async function callDashScope() { // 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。 const apiKey = process.env.DASHSCOPE_API_KEY; const appId = 'YOUR_APP_ID';//替换为实际的应用 ID const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`; const data = { input: { prompt: "请帮我推荐一款3000元以下的手机" }, parameters: { rag_options:{ pipeline_ids:['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2'], // 替换为指定的知识库 ID,多个请用逗号隔开 file_ids:['YOUR_FILE_ID1','YOUR_FILE_ID2'], // 替换为指定的文件 ID,多个请用逗号隔开 metadata_filter:{ // 元数据键值对,多个请用逗号隔开 'key1':'value1', 'key2':'value2' }, tags: ['标签1', '标签2'] // 文档标签,多个请用逗号隔开 } }, 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();
响应示例
在3000元以下的预算范围内,我推荐您考虑**百炼 Zephyr Z9**。这款手机的价格区间是2499-2799元,它拥有轻薄便携的设计,配备6.4英寸1080 x 2340像素屏幕、128GB存储与6GB RAM,能够满足日常使用需求。其4000mAh电池保证了一天的使用时间,而30倍数字变焦镜头则可以帮助捕捉到更远距离的细节。总体来说,这是一款性价比较高的选择。
C#
请求示例
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,YOUR_FILE_ID1替换为指定的非结构化文档 ID if (string.IsNullOrEmpty(apiKey)) { Console.WriteLine("请确保设置了 DASHSCOPE_API_KEY。"); return; } string url = $"https://dashscope-intl.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""], ""file_ids"":[""YOUR_FILE_ID1""], ""metadata_filter"":{{ ""name"":""张三"" }}, ""tags"":""手机"" }} }}, ""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}"); } } } }
响应示例
{ "output": { "finish_reason": "stop", "session_id": "be9b5a1964fe41c9bbfd8674226bd238", "text": "根据您的预算,我为您推荐**百炼 Zephyr Z9**。这款手机售价在2499-2799元之间,非常适合3000元以下的预算要求。 ### 产品亮点 - **轻薄设计**:采用6.4英寸屏幕,分辨率1080 x 2340像素,外观精致且便于携带。 - **性能均衡**:配备6GB RAM和128GB存储空间,能够满足日常使用需求。 - **长效续航**:内置4000mAh电池,确保您一整天的正常使用不受影响。 - **出色摄影**:支持30倍数字变焦功能,轻松捕捉远方美景或细节。 如果您追求的是性价比高、能满足基本需求同时又具备一定特色的智能手机,那么百炼 Zephyr Z9将是一个不错的选择。" }, "usage": { "models": [ { "output_tokens": 180, "model_id": "qwen-max", "input_tokens": 1055 } ] }, "request_id": "d0811195-0b3f-931e-90b8-323a65053d9c" }
Go
请求示例
package main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" ) func main() { // 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。 apiKey := os.Getenv("DASHSCOPE_API_KEY") appId := "YOUR_APP_ID" // 替换为实际的应用 ID if apiKey == "" { fmt.Println("请确保设置了DASHSCOPE_API_KEY。") return } url := fmt.Sprintf("https://dashscope-intl.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 "file_ids": []string{"YOUR_FILE_ID1"}, // 替换为指定的非结构化文档 ID "metadata_filter": map[string]string{ "name": "张三", // 元数据键值对 }, "tags": "手机", // 非结构化数据文档标签 }, }, "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)) } }
响应示例
{ "output": { "finish_reason": "stop", "session_id": "9de268b3d84748b5ac6321aba72b6ecd", "text": "根据您的预算,我推荐您考虑**百炼 Zephyr Z9**。这款手机的参考售价为2499-2799元,非常适合3000元以下的需求。它具有以下特点: - 轻巧的6.4英寸1080 x 2340像素屏幕设计。 - 搭配128GB存储与6GB RAM,能够满足日常使用需求。 - 配备了4000mAh电池,保证了一天的正常使用。 - 后置摄像头支持30倍数字变焦镜头,可以捕捉到远处的细节。 如果您对摄影或者游戏没有特别高的要求,那么百炼 Zephyr Z9应该是一个不错的选择。" }, "usage": { "models": [ { "output_tokens": 156, "model_id": "qwen-max", "input_tokens": 1055 } ] }, "request_id": "8940b597-92e1-9471-b4eb-896e563c479d" }
检索结构化数据文档里的指定数据:在
rag_options
中传入知识库ID、结构化数据文档的“结构化数据表头+值”的键值对。Python
请求示例
import os from http import HTTPStatus # 建议dashscope SDK 的版本 >= 1.20.11 from dashscope import Application import dashscope dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1' 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,逗号隔开多个 "structured_filter": { # 结构化数据键值对,对应结构化数据,逗号隔开多个 "key1": "value1", "key2": "value2" } } ) 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://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code') else: print('%s\n' % (response.output))
响应示例
{ "text": "我为您推荐"百炼"这款手机,它的价格是2999元,符合您的预算要求。如果您需要了解更多信息,比如性能、外观等,请告诉我。", "finish_reason": "stop", "session_id": "80a3b868b5ce42c8a12f01dccf8651e2", "thoughts": null, "doc_references": null }
Java
请求示例
// 建议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 com.google.gson.JsonObject; import java.util.List; import com.alibaba.dashscope.utils.Constants; public class Main { static { Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1"; } public static void streamCall() throws NoApiKeyException, InputRequiredException { JsonObject structureFilter = new JsonObject(); structureFilter.addProperty("key1", "value1"); // 结构化数据键值对 structureFilter.addProperty("key2", "value2"); // 多个重复调用addProperty 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() .pipelineIds(List.of("PIPELINE_ID1","PIPELINE_ID2")) // 替换为实际指定的知识库 ID,逗号隔开多个 .structuredFilter(structureFilter) .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://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code"); } System.exit(0); } }
响应示例
我为您推荐"百炼"这款手机,它的价格是2999.0元,符合您的预算要求。如果您需要了解更多关于这款手机的信息,比如配置、性能等,请告诉我,我会为您提供更详细的资料。
HTTP
curl
请求示例
curl -X POST https://dashscope-intl.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"], "structured_filter":{ "price":"2999"} } }, "debug": {} }'
YOUR_APP_ID替换为实际的应用 ID,YOUR_PIPELINE_ID1替换为指定的知识库ID。
响应示例
{"output":{"finish_reason":"stop","session_id":"d6bc4206f9cc4d368d534f8aa4e502bc", "text":"我为您推荐一款价格接近3000元的手机:\n\n- **百炼手机**,价格为2999元。 \n\n这款手机性价比高,能满足您的预算需求。 如果您需要更多关于这款手机的详细信息或者有其他特定需求(比如摄像头性能、处理器型号等),请告诉我,我会尽力提供更详尽的信息。"}, "usage":{"models":[{"output_tokens":73,"model_id":"qwen-max","input_tokens":235}]},"request_id":"934e1258-219c-9ef1-8982-fc1bcefb8f11"}%
PHP
请求示例
<?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-intl.aliyuncs.com/api/v1/apps/$application_id/completion"; // 构造请求数据 $data = [ "input" => [ 'prompt' => '请帮我推荐一款3000元以下的手机' ], "parameters" => [ 'rag_options' => [ 'pipeline_ids' => ['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2'],// 替换为指定的知识库 ID,逗号隔开多个 "structured_filter" => [ // 结构化数据键值对,多个逗号隔开 "key1" => "value1", "key2" => "value2" ] ] ] ]; // 将数据编码为 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";} } ?>
响应示例
我为您推荐"百炼"这款手机,它的价格是2999元,符合您的预算要求。如果您需要了解更多关于这款手机的信息,请告诉我。
Node.js
需安装相关依赖:
npm install axios
请求示例
const axios = require('axios'); async function callDashScope() { // 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。 const apiKey = process.env.DASHSCOPE_API_KEY; const appId = 'YOUR_APP_ID'; // 替换为实际的应用 ID // YOUR_PIPELINE_ID1替换为指定的知识库ID, 多个知识库ID之间用逗号隔开 const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`; const data = { input: { prompt: "请帮我推荐一款3000元以下的手机" }, parameters: { rag_options:{ pipeline_ids:['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2'], structured_filter:{ 'key1':'value1', 'key2':'value2' } } }, 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();
响应示例
我为您推荐"百炼"这款手机,它的价格是2999元,符合您的预算要求。如果您需要了解更多详情或有其他特定需求,请告诉我!
C#
请求示例
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-intl.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""], ""structured_filter"":{{ ""price"":""2999"" }} }} }}, ""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}"); } } } }
响应示例
{ "output": { "finish_reason": "stop", "session_id": "108e9104568e44f1915fb3d3d44fdc92", "text": "我为您推荐"百炼"这款手机,它的价格是2999.0元,符合您的预算要求。如果您需要更多关于这款手机的信息或者其他建议,请告诉我。" }, "usage": { "models": [ { "output_tokens": 38, "model_id": "qwen-max", "input_tokens": 104 } ] }, "request_id": "d6d103f4-5c22-9782-9682-45d51a5607f9" }
Go
请求示例
package main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" ) func main() { // 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。 apiKey := os.Getenv("DASHSCOPE_API_KEY") appId := "YOUR_APP_ID" // 替换为实际的应用 ID if apiKey == "" { fmt.Println("请确保设置了DASHSCOPE_API_KEY。") return } url := fmt.Sprintf("https://dashscope-intl.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 "structured_filter": map[string]string{ "price": "2999", // 结构化数据键值对 }, }, }, "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)) } }
响应示例
{ "output": { "finish_reason": "stop", "session_id": "9e0a031b51d1492e8b613ca391b445b0", "text": "我推荐您考虑"百炼"这款手机,它的价格是2999.0元,符合您的预算要求。如果您需要更多关于这款手机的信息或者其他推荐,请告诉我。" }, "usage": { "models": [ { "output_tokens": 39, "model_id": "qwen-max", "input_tokens": 104 } ] }, "request_id": "036abd4f-10c8-9709-881d-8cc9f8095d54" }
调用时可以在上述代码中设置has_thoughts
参数为True,处理代码输出完整响应结果,参与检索的知识库信息会在output
中的thoughts
字段中返回。
在智能体应用的检索配置中打开展示回答来源开关并发布应用,可在调用的返回结果中查看回答来源。
API参考
您可以通过应用调用API参考查看完整的参数列表。