You can integrate Model Studio applications (agents, workflows, or agent orchestration) into your business systems via the DashScope SDK or HTTP.
Prerequisites
- You have obtained an API key: Obtain and configure an API key.
- You have created a Model Studio application and obtained the APP_ID (Model Studio application ID): obtain it from the application card on the My Applications page.
Regardless of the calling method, we recommend that you configure your API key in environment variables. If you call through the DashScope SDK, you also need to install the DashScope SDK.
How to use
QuickStart
- Python
- Java
- HTTP
Request exampleResponse example
Copy
import os
import dashscope
from dashscope import DashScopeError
# The following is the configuration for the Singapore region. Replace {WorkspaceId} with your workspace ID. The region value varies by region.
client = dashscope.Client(
# If not using an environment variable, set your API key directly (e.g., api_key="sk-xxx"). However, it is not recommended to hardcode your API key in code in production environments, to reduce the risk of API key leakage.
api_key=os.getenv("DASHSCOPE_API_KEY"),
workspace="{WorkspaceId}",
region="ap-southeast-1",
)
try:
response = client.apps.completions.create(
app_id='APP_ID', # Replace with the actual application ID
prompt='你是谁?')
print(response.text)
except DashScopeError as e:
print(f'request_id={e.request_id}')
print(f'code={e.code}')
print(f'message={e.message}')
print(f'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
Copy
我是阿里云开发的一款超大规模语言模型,我叫千问。我被设计用来帮助用户生成各种类型的文本,如文章、故事、诗歌、故事等,并能根据不同的场景和需求进行调整和优化。此外,我还能够回答各种问题,提供信息和解释,辅助学习和研究。如果您有任何需要,欢迎随时向我提问!
Request exampleResponse example
Copy
// Recommended dashscope SDK version >= 2.12.0
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
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()
// If you have not configured an environment variable, replace the following line with .apiKey("sk-xxx") using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("APP_ID")
.prompt("你是谁?")
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
System.out.printf("text: %s\n",
result.getOutput().getText());
}
public static void main(String[] args) {
try {
appCall();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.err.println("message:"+e.getMessage());
System.out.println("请参考文档:https://www.alibabacloud.com/help/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
Copy
text: 我是阿里云开发的一款超大规模语言模型,我叫千问。
- curl
- PHP
- Node.js
- C#
- Go
Request example
Copy
curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/apps/APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "你是谁?"
},
"parameters": {},
"debug": {}
}'
Replace APP_ID with your actual application ID.Response example
Copy
{"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"}%
Request exampleResponse example
Copy
<?php
# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'APP_ID'; // Replace with the actual application ID
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
// Construct request data
$data = [
"input" => [
'prompt' => '你是谁?'
]
];
// Encode data as JSON
$dataString = json_encode($data);
// Check if json_encode was successful
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// Initialize the cURL session
$ch = curl_init($url);
// Set cURL options
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
]);
// Execute the request
$response = curl_exec($ch);
// Check whether cURL succeeded
if ($response === false) {
die("cURL Error: " . curl_error($ch));
}
// Get HTTP status code
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close the cURL session
curl_close($ch);
// Decode response data
$response_data = json_decode($response, true);
// Handle response
if ($status_code == 200) {
if (isset($response_data['output']['text'])) {
echo "{$response_data['output']['text']}\n";
} else {
echo "No text in response.\n";
}}
else {
if (isset($response_data['request_id'])) {
echo "request_id={$response_data['request_id']}\n";}
echo "code={$status_code}\n";
if (isset($response_data['message'])) {
echo "message={$response_data['message']}\n";}
else {
echo "message=Unknown error\n";}
}
?>
Copy
我是来自阿里云的超大规模语言模型,我叫千问。
Required dependencies:Request exampleResponse example
Copy
npm install axios
Copy
const axios = require('axios');
async function callDashScope() {
// If you have not configured an environment variable, replace the following line with apiKey='sk-xxx' using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'APP_ID';// Replace with the actual application 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();
Copy
我是来自阿里云的大规模语言模型,我叫千问。
Request exampleResponse example
Copy
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
//If you have not configured an environment variable, replace the following line with apiKey="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
string appId = "APP_ID"; // Replace with the actual application ID
string url = $"https://dashscope-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}");
}
}
}
}
Copy
{
"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"
}
Request exampleResponse example
Copy
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// If you have not configured an environment variable, replace the following line with apiKey := "sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "APP_ID" // Replace with the actual application ID
if apiKey == "" {
fmt.Println("请确保设置了DASHSCOPE_API_KEY。")
return
}
url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Create request body
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
}
// Create HTTP POST request
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("Failed to create request: %v\n", err)
return
}
// Set request headers
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// Send request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Failed to send request: %v\n", err)
return
}
defer resp.Body.Close()
// Read response
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// Handle response
if resp.StatusCode == http.StatusOK {
fmt.Println("Request successful:")
fmt.Println(string(body))
} else {
fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
fmt.Println(string(body))
}
}
Copy
{
"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"
}
Multi-turn
Compared with single-turn conversations, multi-turn conversations allow the LLM to reference historical conversation information, better matching everyday communication scenarios.- Python
- Java
- HTTP
Request exampleResponse example
Copy
import os
import dashscope
from dashscope import DashScopeError
# The following is the configuration for the Singapore region. Replace {WorkspaceId} with your workspace ID. The region value varies by region.
client = dashscope.Client(
# If not using an environment variable, set your API key directly (e.g., api_key="sk-xxx"). However, it is not recommended to hardcode your API key in code in production environments, to reduce the risk of API key leakage.
api_key=os.getenv("DASHSCOPE_API_KEY"),
workspace="{WorkspaceId}",
region="ap-southeast-1",
)
def call_with_session():
try:
response = client.apps.completions.create(
app_id='YOUR_APP_ID', # Replace with the actual application ID
prompt='你是谁?')
responseNext = client.apps.completions.create(
app_id='YOUR_APP_ID', # Replace with the actual application ID
prompt='你有什么技能?',
session_id=response.session_id) # The session_id from the previous response
print('%s\n session_id=%s\n' % (responseNext.text, responseNext.session_id))
# print('%s\n' % (response.usage))
except DashScopeError as e:
print(f'request_id={e.request_id}')
print(f'code={e.code}')
print(f'message={e.message}')
print(f'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
if __name__ == '__main__':
call_with_session()
Copy
我具备多种技能,可以协助你完成各种任务。以下是一些主要的技能:
1. **信息查询**:提供天气、新闻、历史事实、科学知识等各种信息。
2. **语言处理**:翻译文本、纠正语法错误、生成文章和故事。
3. **技术问题解答**:解答编程、软件使用、技术故障排除等问题。
4. **学习辅导**:帮助解答数学、物理、化学等学科的问题。
5. **生活建议**:提供健康、饮食、旅行、购物等方面的建议。
6. **娱乐互动**:讲笑话、玩文字游戏、进行简单的聊天互动。
7. **日程管理**:提醒重要日期、安排日程、设置提醒。
8. **数据分析**:解释数据图表、提供数据分析建议。
9. **情感支持**:倾听你的感受、提供安慰和支持。
如果你有具体的需求或问题,可以直接告诉我,我会尽力帮助你!
session_id=98ceb3ca0c4e4b05a20a00f913050b42
Request exampleResponse example
Copy
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()
// If you have not configured an environment variable, replace the following line with .apiKey("sk-xxx") using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// Replace with the actual application 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/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
Copy
我具备多项技能,可以为您提供多种帮助。以下是一些主要的技能:
1. **多语言理解与生成**:我能理解和生成包括中文、英文在内的多种语言文本。
2. **信息检索与综合**:我可以根据您的问题查找相关信息并进行整理和总结。
3. **写作辅助**:无论是撰写文章、报告还是创意写作,我都能提供支持。
4. **编程助手**:对于程序员来说,我可以帮助解答编程相关的问题,提供代码示例等。
5. **教育辅导**:在学习过程中遇到困难时,我可以作为助手提供帮助,涵盖从数学到历史等多个学科领域。
6. **生活建议**:关于健康饮食、旅行规划等方面的问题我也能给出一些建议。
7. **情感交流**:虽然我是AI,但我努力以一种温暖和支持的方式与您交流。
如果您有任何具体需求或想要进一步了解某个方面的内容,请随时告诉我!
, session_id: f2e94a980a34424fa25be45a7048d77c
- curl
- PHP
- Node.js
- C#
- Go
Request example (previous turn)Response exampleRequest example (next turn)Response example
Copy
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": {}
}'
Copy
{
"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"
}
Copy
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": {}
}'
Copy
{
"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"
}
Request example (previous turn)Response exampleRequest example (next turn)Response example
Copy
<?php
# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // Replace with the actual application ID
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
// Construct request data
$data = [
"input" => [
'prompt' => '你是谁?'
]
];
// Encode data as JSON
$dataString = json_encode($data);
// Check if json_encode was successful
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// Initialize the cURL session
$ch = curl_init($url);
// Set cURL options
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
]);
// Execute the request
$response = curl_exec($ch);
// Check whether cURL succeeded
if ($response === false) {
die("cURL Error: " . curl_error($ch));
}
// Get HTTP status code
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close the cURL session
curl_close($ch);
// Decode response data
$response_data = json_decode($response, true);
// Handle response
if ($status_code == 200) {
if (isset($response_data['output']['text'])) {
echo "{$response_data['output']['text']}\n";
} else {
echo "No text in response.\n";
};
if (isset($response_data['output']['session_id'])) {
echo "session_id={$response_data['output']['session_id']}\n";
}
}else {
if (isset($response_data['request_id'])) {
echo "request_id={$response_data['request_id']}\n";}
echo "code={$status_code}\n";
if (isset($response_data['message'])) {
echo "message={$response_data['message']}\n";}
else {
echo "message=Unknown error\n";}
}
?>
Copy
我是来自阿里云的超大规模语言模型,我叫千问。
session_id=2e658bcb514f4d30ab7500b4766a8d43
Copy
<?php
# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // Replace with the actual application ID
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
// Construct request data
$data = [
"input" => [
'prompt' => '你有什么技能?',
// Replace with the actual session_id returned from the previous conversation
'session_id' => '2e658bcb514f4d30ab7500b4766a8d43'
]
];
// Encode data as JSON
$dataString = json_encode($data);
// Check if json_encode was successful
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// Initialize the cURL session
$ch = curl_init($url);
// Set cURL options
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
]);
// Execute the request
$response = curl_exec($ch);
// Check whether cURL succeeded
if ($response === false) {
die("cURL Error: " . curl_error($ch));
}
// Get HTTP status code
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close the cURL session
curl_close($ch);
// Decode response data
$response_data = json_decode($response, true);
// Handle response
if ($status_code == 200) {
if (isset($response_data['output']['text'])) {
echo "{$response_data['output']['text']}\n";
} else {
echo "No text in response.\n";
};
if (isset($response_data['output']['session_id'])) {
echo "session_id={$response_data['output']['session_id']}\n";
}
}else {
if (isset($response_data['request_id'])) {
echo "request_id={$response_data['request_id']}\n";}
echo "code={$status_code}\n";
if (isset($response_data['message'])) {
echo "message={$response_data['message']}\n";}
else {
echo "message=Unknown error\n";}
}
?>
Copy
我具备多项技能,包括但不限于:
1. **多语言能力**:我可以理解和生成多种语言的文字内容。
2. **写作与创作**:帮助撰写文章、故事、诗歌等创意内容。
3. **知识问答**:回答来自各个领域的常识性和专业性问题。
4. **代码编写与理解**:能够编写简单的程序代码,并帮助解释或调试代码。
5. **逻辑推理**:解决需要逻辑思考的问题和谜题。
6. **情感支持**:提供正面的心理支持和鼓励。
7. **游戏娱乐**:参与文字游戏或其他形式的互动娱乐活动。
我的目标是成为您的得力助手,在您需要的时候提供帮助和支持。如果您有任何具体需求或想要尝试的功能,请随时告诉我!
session_id=2e658bcb514f4d30ab7500b4766a8d43
Required dependencies:Request example (previous turn)Response exampleRequest example (next turn)Response example
Copy
npm install axios
Copy
const axios = require('axios');
async function callDashScope() {
// If you have not configured an environment variable, replace the following line with apiKey='sk-xxx' using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';// Replace with the actual application 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();
Copy
我是千问,由阿里云开发的人工智能助手。我可以回答各种问题、提供信息和与用户进行对话。有什么我可以帮助你的吗?
session_id=fe4ce8b093bf46159ea9927a7b22f0d3
Copy
const axios = require('axios');
async function callDashScope() {
// If you have not configured an environment variable, replace the following line with apiKey='sk-xxx' using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';// Replace with the actual application ID
const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`;
// Replace session_id with the actual session_id from the previous conversation
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();
Copy
我具备多种技能,可以帮助你处理不同的任务和问题。以下是一些主要的技能领域:
1. **信息查询与检索**:我可以帮助查找特定的信息、数据或新闻。
2. **写作与创作**:包括撰写文章、故事、诗歌、报告等。
3. **语言翻译**:能够提供不同语言之间的翻译服务。
4. **教育辅导**:解答学术问题,帮助理解复杂的概念。
5. **技术支持**:解决计算机使用中遇到的技术难题。
6. **生活建议**:提供建议关于健康、饮食、旅行等方面。
7. **娱乐互动**:讲笑话、玩文字游戏等轻松活动。
如果你有具体的需求或想了解更详细的某一方面,请告诉我!
session_id=fe4ce8b093bf46159ea9927a7b22f0d3
Request example (previous turn)Response exampleRequest example (next turn)Response example
Copy
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
//If you have not configured an environment variable, replace the following line with apiKey="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
string appId = "YOUR_APP_ID"; // Replace with the actual application 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}");
}
}
}
}
Copy
{
"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"
}
Copy
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
//If you have not configured an environment variable, replace the following line with apiKey="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
string appId = "YOUR_APP_ID"; // Replace with the actual application 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}");
}
}
}
}
Copy
{
"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"
}
Request example (previous turn)Response exampleRequest example (next turn)Response example
Copy
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// If you have not configured an environment variable, replace the following line with apiKey := "sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // Replace with the actual application ID
if apiKey == "" {
fmt.Println("请确保设置了DASHSCOPE_API_KEY。")
return
}
url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Create request body
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
}
// Create HTTP POST request
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("Failed to create request: %v\n", err)
return
}
// Set request headers
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// Send request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Failed to send request: %v\n", err)
return
}
defer resp.Body.Close()
// Read response
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// Handle response
if resp.StatusCode == http.StatusOK {
fmt.Println("Request successful:")
fmt.Println(string(body))
} else {
fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
fmt.Println(string(body))
}
}
Copy
{
"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"
}
Copy
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// If you have not configured an environment variable, replace the following line with apiKey := "sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // Replace with the actual application ID
if apiKey == "" {
fmt.Println("请确保设置了DASHSCOPE_API_KEY。")
return
}
url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Create request body
requestBody := map[string]interface{}{
"input": map[string]string{
"prompt": "你有什么技能?",
"session_id": "f7eea37f0c734c20998a021b688d6de2", // Replace with the actual session_id from the previous conversation
},
"parameters": map[string]interface{}{},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Failed to marshal JSON: %v\n", err)
return
}
// Create HTTP POST request
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("Failed to create request: %v\n", err)
return
}
// Set request headers
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// Send request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Failed to send request: %v\n", err)
return
}
defer resp.Body.Close()
// Read response
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// Handle response
if resp.StatusCode == http.StatusOK {
fmt.Println("Request successful:")
fmt.Println(string(body))
} else {
fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
fmt.Println(string(body))
}
}
Copy
{
"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"
}
Replace YOUR_APP_ID with your actual application ID. For the next turn, set the session_id field in the input parameters to the session_id value returned by the previous turn.
Pass custom parameters
To adapt the same agent or workflow to different business scenarios, you can configure custom prompt variables, custom node parameters, plug-in parameters, and user-level authentication parameters. During application calling, pass the required parameters viabiz_params for flexible adaptation.
-
Custom variable parameters: Add custom variables in an agent application in the console and reference them in the prompt. After you publish the application, pass them via
user_prompt_paramsduring API calls;Make sure the custom variable names added in the application match the names passed during API calls.
-
Parameters of custom plug-ins: passed via the associated agent application.
You can pass the parameter information of custom plug-ins and user-level authentication information:
- The parameter information of a custom plug-in is passed via
user_defined_params. - The user-level authentication information of a custom plug-in is passed via
user_defined_tokens, where the value passed byuser_tokenis the authentication information required by the plug-in, such as the actualDASHSCOPE_API_KEYvalue.
- The parameter information of a custom plug-in is passed via
- Custom plug-in parameter passing
- Custom plug-in user-level authentication
The following example passes the "index" parameter information of the associated plug-in and user-level authentication information to query dormitory convention content.
<YOUR_TOOL_ID>Replace it with the ID of the associated plug-in tool (which can be obtained from the plug-in card), and pass the input parameter key-value pairs configured in the plug-in. In this example, the parameter passed is article_index, and the value is 2.
- Python
- Java
- HTTP
Request exampleResponse example
Copy
import os
# The Dashscope SDK version must be 2.0.1 or later.
import dashscope
from dashscope import DashScopeError
# The following is the configuration for the Singapore region. Replace {WorkspaceId} with your workspace ID. The region value varies by region.
client = dashscope.Client(
# If not using an environment variable, set your API key directly (e.g., api_key="sk-xxx"). However, it is not recommended to hardcode your API key in code in production environments, to reduce the risk of API key leakage.
api_key=os.getenv("DASHSCOPE_API_KEY"),
workspace="{WorkspaceId}",
region="ap-southeast-1",
)
biz_params = {
# Pass the custom plugin input parameters of the agent application. Replace <YOUR_TOOL_ID> with your custom plugin ID
"user_defined_params": {
"<YOUR_TOOL_ID>": {
"article_index": 2}}}
try:
response = client.apps.completions.create(
app_id='YOUR_APP_ID',
prompt='寝室公约内容',
biz_params=biz_params)
print('%s\n' % (response.text)) # Process the text-only output
# print('%s\n' % (response.usage))
except DashScopeError as e:
print(f'request_id={e.request_id}')
print(f'code={e.code}')
print(f'message={e.message}')
print(f'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
Copy
寝室公约的第二条规定如下:
"寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。"
这表明在寝室内,成员之间应该培养一种积极正面的生活和学习氛围,彼此帮助和支持,同时也要学会理解和尊重他人。如果您需要了解公约的其他条款,请告诉我!
Request exampleResponse example
Copy
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 =
// Pass custom plug-in input parameters for the agent application; replace <YOUR_TOOL_ID> with your plug-in ID
"{\"user_defined_params\":{\"<YOUR_TOOL_ID>\":{\"article_index\":2}}}";
ApplicationParam param = ApplicationParam.builder()
// If you have not configured an environment variable, replace the following line with .apiKey("sk-xxx") using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
.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/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
Copy
寝室公约的第二条规定如下:
第二条 寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。
这强调了在共同生活环境中,室友之间应该保持积极正面的关系,通过相互帮助和支持来营造一个和谐的生活和学习氛围。如果有更多具体的条款需要了解,请告知我。
- curl
- PHP
- Node.js
- C#
- Go
Request example
Copy
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_TOOL_ID>":
{
"article_index": 2
}
}
}
},
"parameters": {},
"debug":{}
}'
Replace YOUR_APP_ID with the actual application ID. Replace <YOUR_TOOL_ID> with the plug-in ID.Response example
Copy
{"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"}%
Request exampleResponse example
Copy
<?php
# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // Replace with the actual application ID
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
//Replace <YOUR_TOOL_ID> with your actual plug-in ID
// Construct request data
$data = [
"input" => [
'prompt' => '寝室公约内容',
'biz_params' => [
'user_defined_params' => [
'<YOUR_TOOL_ID>' => [
'article_index' => 2
]
]
]
],
];
// Encode data as JSON
$dataString = json_encode($data);
// Check if json_encode was successful
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// Initialize the cURL session
$ch = curl_init($url);
// Set cURL options
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
]);
// Execute the request
$response = curl_exec($ch);
// Check whether cURL succeeded
if ($response === false) {
die("cURL Error: " . curl_error($ch));
}
// Get HTTP status code
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close the cURL session
curl_close($ch);
// Decode response data
$response_data = json_decode($response, true);
// Handle response
if ($status_code == 200) {
if (isset($response_data['output']['text'])) {
echo "{$response_data['output']['text']}\n";
} else {
echo "No text in response.\n";
}
}else {
if (isset($response_data['request_id'])) {
echo "request_id={$response_data['request_id']}\n";}
echo "code={$status_code}\n";
if (isset($response_data['message'])) {
echo "message={$response_data['message']}\n";}
else {
echo "message=Unknown error\n";}
}
?>
Copy
寝室公约的第二条规定:寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。这是为了保证大家能在一个和谐友爱的环境中生活和学习。如果有更多具体的条款需要了解,或者有其他问题,随时可以问我!
Required dependencies:Request exampleResponse example
Copy
npm install axios
Copy
const axios = require('axios');
async function callDashScope() {
// If you have not configured an environment variable, replace the following line with apiKey='sk-xxx' using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';// Replace with the actual application ID
const pluginCode = 'YOUR_TOOL_ID';// Replace with the actual plug-in 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 is a variable for the custom plug-in, replace with the actual plug-in variable
'article_index': 3
}
}
}
},
parameters: {},
debug: {}
};
try {
console.log("Sending request to DashScope API...");
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
if (response.data.output && response.data.output.text) {
console.log(`${response.data.output.text}`);
}
} else {
console.log("Request failed:");
if (response.data.request_id) {
console.log(`request_id=${response.data.request_id}`);
}
console.log(`code=${response.status}`);
if (response.data.message) {
console.log(`message=${response.data.message}`);
} else {
console.log('message=Unknown error');
}
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();
Copy
寝室公约的第三条规定如下:
注意安全用电,杜绝火灾隐患。寝室内严禁使用明火、违规电器、各种灶具以及其他违规物品,不得存放易爆、易燃物品,私接电源。
如果您需要了解更多的规定,请告诉我。
Request exampleResponse example
Copy
using System.Text;
class Program
{
static async Task Main(string[] args)
{
// If you have not configured an environment variable, replace the following line with apiKey="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");;
string appId = "YOUR_APP_ID";// Replace with the actual application 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_TOOL_ID"; // Replace YOUR_TOOL_ID with your actual plug-in 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}");
}
}
}
}
Copy
{
"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"
}
Request exampleResponse example
Copy
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// If you have not configured an environment variable, replace the following line with apiKey := "sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // Replace with the actual application ID
pluginCode := "YOUR_TOOL_ID" // Replace with the actual plug-in ID
if apiKey == "" {
fmt.Println("请确保设置了DASHSCOPE_API_KEY。")
return
}
url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Create request body
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
}
// Create HTTP POST request
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("Failed to create request: %v\n", err)
return
}
// Set request headers
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// Send request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Failed to send request: %v\n", err)
return
}
defer resp.Body.Close()
// Read response
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// Handle response
if resp.StatusCode == http.StatusOK {
fmt.Println("Request successful:")
fmt.Println(string(body))
} else {
fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
fmt.Println(string(body))
}
}
Copy
{
"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"
}
The following example passes the "index" parameter information of the associated plug-in and user-level authentication information to query dormitory convention content.
<YOUR_TOOL_ID>Replace it with the ID of the associated plug-in tool (which can be obtained from the plug-in card), and pass the input parameter key-value pairs configured in the plug-in. In this example, the parameter passed is article_index, and the value is 2.
- Python
- Java
- HTTP
Request exampleResponse example
Copy
import os
# The Dashscope SDK version must be 2.0.1 or later.
import dashscope
from dashscope import DashScopeError
# The following is the configuration for the Singapore region. Replace {WorkspaceId} with your workspace ID. The region value varies by region.
client = dashscope.Client(
# If not using an environment variable, set your API key directly (e.g., api_key="sk-xxx"). However, it is not recommended to hardcode your API key in code in production environments, to reduce the risk of API key leakage.
api_key=os.getenv("DASHSCOPE_API_KEY"),
workspace="{WorkspaceId}",
region="ap-southeast-1",
)
biz_params = {
# Pass the custom plugin authentication of the agent application. Replace <YOUR_TOOL_ID> with your custom plugin ID and YOUR_TOKEN with the authentication information, such as an API key
"user_defined_params": {
"<YOUR_TOOL_ID>": {
"article_index": 2}},
"user_defined_tokens": {
"<YOUR_TOOL_ID>": {
"user_token": "YOUR_TOKEN"}}}
try:
response = client.apps.completions.create(
app_id='YOUR_APP_ID',
prompt='寝室公约内容',
biz_params=biz_params)
print('%s\n' % (response.text)) # Process the text-only output
# print('%s\n' % (response.usage))
except DashScopeError as e:
print(f'request_id={e.request_id}')
print(f'code={e.code}')
print(f'message={e.message}')
print(f'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
Copy
寝室公约的第二条规定如下:
寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。
如果您需要了解更多的规定内容,请告诉我。
Request exampleResponse example
Copy
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 =
// Replace <YOUR_TOOL_ID> with your actual plug-in ID and YOUR_TOKEN with your token, such as an API key
"{\"user_defined_params\":{\"<YOUR_TOOL_ID>\":{\"article_index\":2}}," +
"\"user_defined_tokens\":{\"<YOUR_TOOL_ID>\":{\"user_token\":\"YOUR_TOKEN\"}}}";
ApplicationParam param = ApplicationParam.builder()
// If you have not configured an environment variable, replace the following line with .apiKey("sk-xxx") using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
.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/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
Copy
寝室公约的第二条规定如下:
寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。
如果您需要查询更多的规定内容,请告诉我。
- curl
- PHP
- Node.js
- C#
- Go
Request example
Copy
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_TOOL_ID>":
{
"article_index": 2
}
},
"user_defined_tokens":
{
"<YOUR_TOOL_ID>":
{
"user_token": "YOUR_TOKEN"
}
}
}
},
"parameters": {},
"debug":{}
}'
Replace YOUR_APP_ID with the actual application ID. Replace <YOUR_TOOL_ID> with the actual plug-in ID.Response example
Copy
{"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"}%
Request exampleResponse example
Copy
<?php
# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // Replace with the actual application ID
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
// Construct request data
$data = [
"input" => [
'prompt' => '寝室公约内容',
'biz_params' => [
'user_defined_params' => [
'<YOUR_TOOL_ID>' => [//Replace <YOUR_TOOL_ID> with your actual plug-in ID
'article_index' => 2
]
],
'user_defined_tokens' => [
'<YOUR_TOOL_ID>' => [//Replace <YOUR_TOOL_ID> with your actual plug-in ID
'user_token' => 'YOUR_TOKEN'//Replace with the actual Token, such as API key
]
]
]
],
];
// Encode data as JSON
$dataString = json_encode($data);
// Check if json_encode was successful
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// Initialize the cURL session
$ch = curl_init($url);
// Set cURL options
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
]);
// Execute the request
$response = curl_exec($ch);
// Check whether cURL succeeded
if ($response === false) {
die("cURL Error: " . curl_error($ch));
}
// Get HTTP status code
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close the cURL session
curl_close($ch);
// Decode response data
$response_data = json_decode($response, true);
// Handle response
if ($status_code == 200) {
if (isset($response_data['output']['text'])) {
echo "{$response_data['output']['text']}\n";
} else {
echo "No text in response.\n";
}
}else {
if (isset($response_data['request_id'])) {
echo "request_id={$response_data['request_id']}\n";}
echo "code={$status_code}\n";
if (isset($response_data['message'])) {
echo "message={$response_data['message']}\n";}
else {
echo "message=Unknown error\n";}
}
?>
Copy
寝室公约的第二条规定如下:
> 寝室成员应当互帮互助、互相关心、互相学习、共同提高;宽容谦让、相互尊重、以诚相待。
如果需要了解更多的公约内容或其他信息,请随时告诉我!
Required dependencies:Request exampleResponse example
Copy
npm install axios
Copy
const axios = require('axios');
async function callDashScope() {
// If you have not configured an environment variable, replace the following line with apiKey='sk-xxx' using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';// Replace with the actual application ID
const pluginCode = 'YOUR_TOOL_ID';// Replace with the actual plug-in 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 is a variable for the custom plug-in, replace with the actual plug-in variable
'article_index': 6
}
},
user_defined_tokens: {
[pluginCode]: {
// Replace YOUR_TOKEN with the actual authentication information, such as 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();
Copy
寝室公约的第六条规定:养成良好的作息习惯,每一位寝室成员都享有休息的权利和承担保证他人休息权利和义务。如果你需要了解更多的规定内容,请进一步说明。
Request exampleResponse example
Copy
using System.Text;
class Program
{
static async Task Main(string[] args)
{
// If you have not configured an environment variable, replace the following line with apiKey="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");;
string appId = "YOUR_APP_ID";// Replace with the actual application 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_TOOL_ID"; // Replace with the actual plug-in ID
// Replace YOUR_TOKEN with the actual Token, such as 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}");
}
}
}
}
Copy
{
"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"
}
Request exampleResponse example
Copy
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// If you have not configured an environment variable, replace the following line with apiKey := "sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // Replace with the actual application ID
pluginCode := "YOUR_TOOL_ID" // Replace with the actual plug-in ID
if apiKey == "" {
fmt.Println("请确保设置了DASHSCOPE_API_KEY。")
return
}
url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId)
// Create request body
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", // Replace with the actual authentication token, such as 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
}
// Create HTTP POST request
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("Failed to create request: %v\n", err)
return
}
// Set request headers
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// Send request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Failed to send request: %v\n", err)
return
}
defer resp.Body.Close()
// Read response
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// Handle response
if resp.StatusCode == http.StatusOK {
fmt.Println("Request successful:")
fmt.Println(string(body))
} else {
fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
fmt.Println(string(body))
}
}
Copy
{
"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"
}
-
Custom node parameters: add them in the start node of a workflow application or an agent orchestration application, and pass them through
biz_params. Refer to the following example of passing a city name parameter in a workflow application: set a String-type variable named city in the start node, insert the variable city and the variable query into the Prompt, and then publish the application.When calling the application, pass city through
biz_paramsand pass query throughprompt.- Python
- Java
- HTTP
Request exampleResponse exampleCopyimport os import dashscope from dashscope import DashScopeError # The following is the configuration for the Singapore region. Replace {WorkspaceId} with your workspace ID. The region value varies by region. client = dashscope.Client( # If not using an environment variable, set your API key directly (e.g., api_key="sk-xxx"). However, it is not recommended to hardcode your API key in code in production environments, to reduce the risk of API key leakage. api_key=os.getenv("DASHSCOPE_API_KEY"), workspace="{WorkspaceId}", region="ap-southeast-1", ) # Pass custom parameters of the workflow or agent orchestration application biz_params = {"city": "杭州"} try: response = client.apps.completions.create( app_id='YOUR_APP_ID', # Replace with the actual application ID prompt='查询这个城市的行政区域划分', biz_params=biz_params # Pass business parameters ) print(f'{response.text}') # Process the text-only output except DashScopeError as e: print(f'request_id={e.request_id}') print(f'code={e.code}') print(f'message={e.message}') print(f'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')Copy杭州市,作为浙江省的省会城市,其行政区域划分包括10个市辖区:上城区、拱墅区、西湖区、滨江区、萧山区、余杭区、临平区、钱塘区、富阳区、临安区。每个区都有其独特的特色和发展重点。 - 上城区:位于杭州市中心地带,是杭州的政治、经济、文化中心之一。 - 拱墅区:以运河文化为特色,拥有众多历史文化遗产。 - 西湖区:著名的西湖风景区就位于此区,是旅游观光的重要目的地。 - 滨江区:高新技术产业聚集地,阿里巴巴等知名企业坐落于此。 - 萧山区:东南部的一个行政区,经济发展迅速,特别是制造业方面。 - 余杭区:近年来发展快速,尤其是互联网经济领域,阿里巴巴总部也设在这里(注:阿里巴巴总部实际位于滨江区)。 - 临平区:新成立的行政区,旨在促进该地区经济社会全面发展。 - 钱塘区:同样是一个较新的行政区划调整结果,强调创新发展和生态保护相结合。 - 富阳区:位于杭州西南方向,以其丰富的自然景观和悠久的历史文化著称。 - 临安区:地处杭州西部,以生态优美闻名,并且有着深厚的文化底蕴。 请注意,随着时间推移,具体的城市规划可能会有所变化,请参考最新的官方信息。Request exampleResponse exampleCopyimport 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() // If you have not configured an environment variable, replace the following line with .apiKey("sk-xxx") using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage. .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/model-studio/developer-reference/error-code"); } System.exit(0); } }Copy杭州市是浙江省的省会城市,其行政区域划分主要包括10个市辖区:上城区、拱墅区、西湖区、滨江区、萧山区、余杭区、临平区、钱塘区、富阳区、临安区。每个区都有自己的特色和发展重点。 - 上城区:位于杭州市中心,拥有许多历史文化遗产。 - 拱墅区:以大运河文化而闻名,同时也是一个重要的商业和居住区。 - 西湖区:以其美丽的自然风光著称,包括著名的西湖风景区。 - 滨江区:高新技术产业集聚地,杭州国家高新技术产业开发区就设在这里。 - 萧山区:经济发展迅速,尤其在制造业方面表现突出。 - 余杭区:近年来随着阿里巴巴等高科技企业的发展而快速崛起。 - 临平区:2021年由原余杭区部分区域调整而来,注重生态建设和科技创新。 - 钱塘区:同样是在2021年成立的新区,定位为杭州东部交通枢纽及产业发展新高地。 - 富阳区:历史悠久的文化名城,也是造纸业的重要基地之一。 - 临安区:位于杭州西部,森林覆盖率高,生态环境良好。 这些区域共同构成了杭州市独特的地理格局和社会经济结构。如果你对某个特定区域感兴趣或需要更详细的信息,请告诉我!- curl
- PHP
- Node.js
- C#
- Go
Request exampleCopycurl -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": {} }'Replace YOUR_APP_ID with the actual application ID.
Response exampleCopy{"output":{"finish_reason":"stop","session_id":"c211219896004b50a1f6f66f2ec5413e", "text":"杭州市下辖10个区、1个县,代管2个县级市,分别为: 上城区、拱墅区、西湖区、滨江区、萧山区、余杭区、临平区、钱塘区、富阳区、临安区、桐庐县、淳安县、建德市、诸暨市。 注意,诸暨市由浙江省直辖、杭州市与绍兴市共同管理。"},"usage":{}, "request_id":"02c3c9e1-7912-9505-91aa-248d04fb1f5d"}Request exampleResponse exampleCopy<?php # 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。 $api_key = getenv("DASHSCOPE_API_KEY"); $application_id = 'YOUR_APP_ID'; // Replace with the actual application ID $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion"; // Construct request data $data = [ "input" => [ 'prompt' => '查询这个城市的行政区域划分', 'biz_params' => [ 'city' => '杭州' ] ], ]; // Encode data as JSON $dataString = json_encode($data); // Check if json_encode was successful if (json_last_error() !== JSON_ERROR_NONE) { die("JSON encoding failed with error: " . json_last_error_msg()); } // Initialize the cURL session $ch = curl_init($url); // Set cURL options curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Authorization: Bearer ' . $api_key ]); // Execute the request $response = curl_exec($ch); // Check whether cURL succeeded if ($response === false) { die("cURL Error: " . curl_error($ch)); } // Get HTTP status code $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Close the cURL session curl_close($ch); // Decode response data $response_data = json_decode($response, true); // Handle response if ($status_code == 200) { if (isset($response_data['output']['text'])) { echo "{$response_data['output']['text']}\n"; } else { echo "No text in response.\n"; } } else { if (isset($response_data['request_id'])) { echo "request_id={$response_data['request_id']}\n"; } echo "code={$status_code}\n"; if (isset($response_data['message'])) { echo "message={$response_data['message']}\n"; } else { echo "message=Unknown error\n"; } }Copy杭州市是浙江省的省会城市,其行政区域划分主要包括10个市辖区:上城区、拱墅区、西湖区、滨江区、萧山区、余杭区、临平区、钱塘区、富阳区、临安区。 每个区都有自己的特色和发展重点,比如: - **上城区**和**拱墅区**位于杭州市中心,商业繁华,历史悠久。 - **西湖区**以美丽的西湖而闻名,同时也是一个重要的科教文化区。 - **滨江区**则以其高新技术产业发展著称。 - **萧山区**、**余杭区**等则是近年来随着城市发展迅速崛起的新城区或经济开发区。 - **临安区**、**富阳区**等地则更多保留了自然风光与乡村风貌。 请注意,中国的行政区划可能会根据国家政策调整有所变化,请通过官方渠道获取最新信息。Required dependencies:Request exampleCopynpm install axiosResponse exampleCopyconst axios = require('axios'); async function callDashScope() { // If you have not configured an environment variable, replace the following line with apiKey='sk-xxx' using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage. const apiKey = process.env.DASHSCOPE_API_KEY; const appId = 'YOUR_APP_ID'; // Replace with the actual application 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();Copy杭州市是浙江省的省会,其行政区域划分包括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ū):从余杭区分设出来的一个新行政区划,主要涵盖原余杭区内的临平街道等地。 以上信息反映了截至我最后更新时的情况,请注意行政区划可能会有所调整,请以官方发布的最新消息为准。Request exampleResponse exampleCopyusing System.Text; class Program { static async Task Main(string[] args) { //If you have not configured an environment variable, replace the following line with apiKey="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage. string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set."); string appId = "YOUR_APP_ID"; // Replace with the actual application 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}"); } } } }Copy{ "output": { "finish_reason": "stop", "session_id": "7a9ff57eec7d475fa5d487de5f5178d2", "text": "杭州市是浙江省的省会,它下辖有10个市辖区:上城区、拱墅区、西湖区、滨江区、萧山区、余杭区、临平区、钱塘区、富阳区和临安区。每个区都有其独特的地理位置和发展特色。例如,西湖区以美丽的自然风光著称,尤其是著名的杭州西湖就位于此;而滨江区则更多地以其高新技术产业发展闻名。此外,随着城市的发展,行政区划也可能会有所调整,请关注官方发布的最新信息。" }, "usage": { }, "request_id": "d2c2fcc9-f821-98c9-9430-8704a2a41225" }Request exampleResponse exampleCopypackage main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" ) func main() { // If you have not configured an environment variable, replace the following line with apiKey := "sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage. apiKey := os.Getenv("DASHSCOPE_API_KEY") appId := "YOUR_APP_ID" // Replace with the actual application ID if apiKey == "" { fmt.Println("请确保设置了DASHSCOPE_API_KEY。") return } url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId) // Create request body 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 } // Create HTTP POST request req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) if err != nil { fmt.Printf("Failed to create request: %v\n", err) return } // Set request headers req.Header.Set("Authorization", "Bearer "+apiKey) req.Header.Set("Content-Type", "application/json") // Send request client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Printf("Failed to send request: %v\n", err) return } defer resp.Body.Close() // Read response body, err := io.ReadAll(resp.Body) if err != nil { fmt.Printf("Failed to read response: %v\n", err) return } // Handle response if resp.StatusCode == http.StatusOK { fmt.Println("Request successful:") fmt.Println(string(body)) } else { fmt.Printf("Request failed with status code: %d\n", resp.StatusCode) fmt.Println(string(body)) } }Copy{ "output": { "finish_reason": "stop", "session_id": "2dc3e1a9dcd248c6bb9ca92bffc3e745", "text": "杭州市,简称“杭”,是浙江省的省会城市。根据最新的行政区划调整,杭州市现辖10个市辖区、2个县级市和1个县,具体如下: - 市辖区(10个):上城区、拱墅区、西湖区、滨江区、萧山区、余杭区、临平区、钱塘区、富阳区、临安区。 - 县级市(2个):建德市、桐庐县(注意这里的桐庐实际上被列为县级市处理,但准确地说它是一个县)。 - 县(1个):淳安县。 请注意,随着时间的变化,行政区域可能会有所调整,请以官方最新发布的消息为准。上述信息基于较新的资料整理而来,对于最新的变动情况,建议访问政府官方网站获取最准确的信息。" }, "usage": { }, "request_id": "d3c8f368-b645-9446-bfe4-20ca51821a02" }
Streaming output
After an LLM receives the input, it generates intermediate results step by step, and the final result is assembled from these intermediate results. This approach of generating and outputting intermediate results as they are produced is called streaming output. With streaming output, you can read the content while the model is generating it, reducing the wait time for the model's response. Depending on the calling method, you can set the corresponding parameter to enable streaming output:- Python SDK: set the
streamparameter to True to enable streaming output. - Java SDK: you need to call through the
streamCallinterface. - HTTP: you need to specify
X-DashScope-SSEasenablein the Header.
By default, streaming output content is non-incremental (that is, each response contains all previously generated content). If you need incremental streaming output, set theRefer to the following examples:incremental_output(theincrementalOutputinterface in Java) parameter totrue. When calling through HTTP, setincremental_outputto true and put it into the parameters object.
-
The following is an example of a streaming output call for an agent application:
- Python
- Java
- HTTP
Request exampleResponse exampleCopyimport os import dashscope from dashscope import DashScopeError # The following is the configuration for the Singapore region. Replace {WorkspaceId} with your workspace ID. The region value varies by region. client = dashscope.Client( # If not using an environment variable, set your API key directly (e.g., api_key="sk-xxx"). However, it is not recommended to hardcode your API key in code in production environments, to reduce the risk of API key leakage. api_key=os.getenv("DASHSCOPE_API_KEY"), workspace="{WorkspaceId}", region="ap-southeast-1", ) try: stream = client.apps.completions.create( app_id='YOUR_APP_ID', prompt='你是谁?', stream=True, # Enable streaming output incremental_output=True) # Enable incremental output for partial in stream: print(f'{partial.text}\n') # Process the text-only output except DashScopeError as e: print(f'request_id={e.request_id}') print(f'code={e.code}') print(f'message={e.message}') print(f'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')Copy我是来自 阿里 云 的大规模语言模型 ,我叫通 义千问。Request exampleResponse exampleCopy// Recommended dashscope SDK version >= 2.15.0 import com.alibaba.dashscope.app.*; import com.alibaba.dashscope.exception.ApiException; import com.alibaba.dashscope.exception.InputRequiredException; import com.alibaba.dashscope.exception.NoApiKeyException; import io.reactivex.Flowable;// Streaming output // Implement streaming output for agent application calls 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() // If you have not configured an environment variable, replace the following line with .apiKey("sk-xxx") using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage. .apiKey(System.getenv("DASHSCOPE_API_KEY")) // Replace with the actual application ID .appId("YOUR_APP_ID") .prompt("你是谁?") // Incremental output .incrementalOutput(true) .build(); Application application = new Application(); // .streamCall(): streaming output content Flowable<ApplicationResult> result = application.streamCall(param); result.blockingForEach(data -> { System.out.printf("%s\n", data.getOutput().getText()); }); } public static void main(String[] args) { try { streamCall(); } catch (ApiException | NoApiKeyException | InputRequiredException e) { System.out.printf("Exception: %s", e.getMessage()); System.out.println("请参考文档:https://www.alibabacloud.com/help/model-studio/developer-reference/error-code"); } System.exit(0); } }Copy我是阿里 云 开发的一款超大规模语言 模型,我叫 千问 。- curl
- PHP
- Node.js
- C#
- Go
Request exampleCopycurl -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": {} }'Replace YOUR_APP_ID with the actual application ID.
Response exampleCopyid: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"}Request exampleResponse exampleCopy<?php // If the environment variable is unset, insert your Model Studio API key: $api_key="sk-xxx". Avoid hardcoding API keys in production to reduce the risk of key exposure. $api_key = getenv("DASHSCOPE_API_KEY"); $application_id = 'YOUR_APP_ID'; // Replace with the actual application ID $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion"; // Construct request data $data = [ "input" => [ 'prompt' => '你是谁?'], "parameters" => [ 'incremental_output' => true]];// Incremental output // Encode data as JSON $dataString = json_encode($data); // Check if json_encode was successful if (json_last_error() !== JSON_ERROR_NONE) { die("JSON encoding failed with error: " . json_last_error_msg()); } // Initialize the cURL session $ch = curl_init($url); // Set cURL options curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString); curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); // Do not return transfer data curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($ch, $string) { echo $string; // Process streaming data return strlen($string); }); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Authorization: Bearer ' . $api_key, 'X-DashScope-SSE: enable' // Streaming output ]); // Execute the request $response = curl_exec($ch); // Check whether cURL succeeded if ($response === false) { die("cURL Error: " . curl_error($ch)); } // Get HTTP status code $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Close the cURL session curl_close($ch); if ($status_code != 200) { echo "HTTP Status Code: $status_code\n"; echo "Request Failed.\n"; } ?>Copyid: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"}Required dependencies:Request exampleCopynpm install axiosYou can expand the collapsible panel to view the details:1. Output the complete response
Copyconst axios = require('axios'); async function callDashScope() { //If you have not configured an environment variable, replace the following line with apiKey='sk-xxx' using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage. const apiKey = process.env.DASHSCOPE_API_KEY; const appId = 'YOUR_APP_ID';// Replace with the actual application ID const url = `https://dashscope-intl.aliyuncs.com/api/v1/apps/${appId}/completion`; const data = { input: { prompt: "你是谁?" }, parameters: { 'incremental_output' : 'true' // Incremental output }, debug: {} }; try { console.log("Sending request to DashScope API..."); const response = await axios.post(url, data, { headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json', 'X-DashScope-SSE': 'enable' // Streaming output }, responseType: 'stream' // For handling streaming responses }); if (response.status === 200) { // Handle streaming response response.data.on('data', (chunk) => { console.log(`Received chunk: ${chunk.toString()}`); }); } else { console.log("Request failed:"); if (response.data.request_id) { console.log(`request_id=${response.data.request_id}`); } console.log(`code=${response.status}`); if (response.data.message) { console.log(`message=${response.data.message}`); } else { console.log('message=Unknown error'); } } } catch (error) { console.error(`Error calling DashScope: ${error.message}`); if (error.response) { console.error(`Response status: ${error.response.status}`); console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`); } } } callDashScope();Response example2. Output only the text field content
Copyconst axios = require('axios'); const { Transform } = require('stream'); async function callDashScope() { //If you have not configured an environment variable, replace the following line with apiKey='sk-xxx' using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage. const apiKey = process.env.DASHSCOPE_API_KEY; const appId = 'YOUR_APP_ID'; // Replace with the actual application ID const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`; const data = { input: { prompt: "你是谁?" }, parameters: { incremental_output: true }, // Incremental output debug: {} }; try { console.log("Sending request to DashScope API..."); const response = await axios.post(url, data, { headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json', 'X-DashScope-SSE': 'enable' // Streaming output }, responseType: 'stream' // For handling streaming responses }); if (response.status === 200) { // // Handle streaming response SSE protocol parsing transform stream const sseTransformer = new Transform({ transform(chunk, encoding, callback) { this.buffer += chunk.toString(); // Split by SSE events (two newlines) const events = this.buffer.split(/\n\n/); this.buffer = events.pop() || ''; // Keep incomplete part events.forEach(eventData => { const lines = eventData.split('\n'); let textContent = ''; // Parse event content lines.forEach(line => { if (line.startsWith('data:')) { try { const jsonData = JSON.parse(line.slice(5).trim()); if (jsonData.output?.text) { textContent = jsonData.output.text; } } catch(e) { console.error('JSON解析错误:', e.message); } } }); if (textContent) { // Add newline and push this.push(textContent + '\n'); } }); callback(); }, flush(callback) { if (this.buffer) { this.push(this.buffer + '\n'); } callback(); } }); sseTransformer.buffer = ''; // Pipe processing response.data .pipe(sseTransformer) .on('data', (textWithNewline) => { process.stdout.write(textWithNewline); // Auto-wrap output }) .on('end', () => console.log("")) .on('error', err => console.error("管道错误:", err)); } else { console.log("请求失败,状态码:", response.status); response.data.on('data', chunk => console.log(chunk.toString())); } } catch (error) { console.error(`API调用失败: ${error.message}`); if (error.response) { console.error(`状态码: ${error.response.status}`); error.response.data.on('data', chunk => console.log(chunk.toString())); } } } callDashScope();Copyid: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"}Request exampleResponse exampleCopyusing System.Net; using System.Text; class Program { static async Task Main(string[] args) { //If you have not configured an environment variable, replace the following line with apiKey="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage. string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set."); string appId = "YOUR_APP_ID"; // Replace with the actual application ID string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion"; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); client.DefaultRequestHeaders.Add("X-DashScope-SSE", "enable"); string jsonContent = @"{ ""input"": { ""prompt"": ""你是谁"" }, ""parameters"": {""incremental_output"": true}, ""debug"": {} }"; HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json"); Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")); try { var request = new HttpRequestMessage(HttpMethod.Post, url); request.Content = content; HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead); if (response.IsSuccessStatusCode) { Console.WriteLine("Request successful:"); Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")); using (var stream = await response.Content.ReadAsStreamAsync()) using (var reader = new StreamReader(stream)) { string? line; // Declare as nullable string while ((line = await reader.ReadLineAsync()) != null) { if (line.StartsWith("data:")) { string data = line.Substring(5).Trim(); Console.WriteLine(data); Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")); } } } } else { Console.WriteLine($"Request failed with status code: {response.StatusCode}"); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } catch (Exception ex) { Console.WriteLine($"Error calling DashScope: {ex.Message}"); } } } }Copy2025-02-14 16:22:08:482 Request successful: 2025-02-14 16:22:09:098 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":"我是"},"usage":{"models":[{"input_tokens":51,"output_tokens":1,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:09:099 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":"来自"},"usage":{"models":[{"input_tokens":51,"output_tokens":2,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:09:172 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":"阿里"},"usage":{"models":[{"input_tokens":51,"output_tokens":3,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:09:172 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":"云的大规模语言"},"usage":{"models":[{"input_tokens":51,"output_tokens":7,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:09:463 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":"模型,我叫"},"usage":{"models":[{"input_tokens":51,"output_tokens":11,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:09:618 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":"千问"},"usage":{"models":[{"input_tokens":51,"output_tokens":15,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:09:777 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":"。我是你的人"},"usage":{"models":[{"input_tokens":51,"output_tokens":19,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:09:932 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":"工智能助手,"},"usage":{"models":[{"input_tokens":51,"output_tokens":23,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:10:091 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":"可以回答问题、"},"usage":{"models":[{"input_tokens":51,"output_tokens":27,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:10:244 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":"创作文字,比如"},"usage":{"models":[{"input_tokens":51,"output_tokens":31,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:10:389 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":"写故事、写"},"usage":{"models":[{"input_tokens":51,"output_tokens":35,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:10:525 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":"公文、写"},"usage":{"models":[{"input_tokens":51,"output_tokens":39,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:10:662 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":"邮件、写剧本"},"usage":{"models":[{"input_tokens":51,"output_tokens":43,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:10:902 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":"等等,还能表达"},"usage":{"models":[{"input_tokens":51,"output_tokens":47,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:11:062 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":"观点,玩游戏等"},"usage":{"models":[{"input_tokens":51,"output_tokens":51,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:11:233 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"null","text":"。"},"usage":{"models":[{"input_tokens":51,"output_tokens":52,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:11:309 {"output":{"session_id":"c2265dd99e4b40e0b5b3638824f21dd9","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":51,"output_tokens":52,"model_id":"qwen-plus"}]},"request_id":"2d40821d-98bb-960e-999d-c456af8bc9e9"} 2025-02-14 16:22:11:388Request exampleResponse exampleCopypackage main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" "strings" "time" ) func main() { // If you have not configured an environment variable, replace the following line with apiKey := "sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage. apiKey := os.Getenv("DASHSCOPE_API_KEY") appId := "YOUR_APP_ID" // Replace with the actual application ID if apiKey == "" { fmt.Println("请确保设置了DASHSCOPE_API_KEY。") return } url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId) // Create request body, where incremental_output enables streaming response 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 } // Create HTTP POST request req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) if err != nil { fmt.Printf("Failed to create request: %v\n", err) return } // Set request headers, where X-DashScope-SSE is set to enable for streaming response req.Header.Set("Authorization", "Bearer "+apiKey) req.Header.Set("Content-Type", "application/json") req.Header.Set("X-DashScope-SSE", "enable") // Send request client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Printf("Failed to send request: %v\n", err) return } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { fmt.Printf("Request failed with status code: %d\n", resp.StatusCode) body, _ := io.ReadAll(resp.Body) fmt.Println(string(body)) return } // Handle streaming response reader := io.Reader(resp.Body) buf := make([]byte, 1024) for { n, err := reader.Read(buf) if n > 0 { data := string(buf[:n]) lines := strings.Split(data, "\n") for _, line := range lines { line = strings.TrimSpace(line) if len(line) >= 5 && line[:5] == "data:" { timestamp := time.Now().Format("2006-01-02 15:04:05.000") fmt.Printf("%s: %s\n", timestamp, line[5:]) } else if len(line) > 0 { fmt.Println(line) } } } if err != nil { if err == io.EOF { break } fmt.Printf("Error reading response: %v\n", err) break } } }Copyid:1 event:result :HTTP_STATUS/200 2025-02-13 18:21:09.050: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":"我是"},"usage":{"models":[{"input_tokens":262,"output_tokens":1,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"} id:2 event:result :HTTP_STATUS/200 2025-02-13 18:21:10.016: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":"通"},"usage":{"models":[{"input_tokens":262,"output_tokens":2,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"} id:3 event:result :HTTP_STATUS/200 2025-02-13 18:21:10.016: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":"义"},"usage":{"models":[{"input_tokens":262,"output_tokens":3,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"} id:4 event:result :HTTP_STATUS/200 2025-02-13 18:21:10.016: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":"千问,由"},"usage":{"models":[{"input_tokens":262,"output_tokens":7,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"} id:5 event:result :HTTP_STATUS/200 2025-02-13 18:21:10.017: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":"阿里云开发的"},"usage":{"models":[{"input_tokens":262,"output_tokens":11,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"} id:6 event:result :HTTP_STATUS/200 2025-02-13 18:21:10.017: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":"AI助手。我"},"usage":{"models":[{"input_tokens":262,"output_tokens":15,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"} id:7 event:result :HTTP_STATUS/200 2025-02-13 18:21:10.017: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":"被设计用来回答"},"usage":{"models":[{"input_tokens":262,"output_tokens":19,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"} id:8 event:result :HTTP_STATUS/200 2025-02-13 18:21:10.018: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":"各种问题、提供"},"usage":{"models":[{"input_tokens":262,"output_tokens":23,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"} id:9 event:result :HTTP_STATUS/200 2025-02-13 18:21:10.102: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":"信息和与用户"},"usage":{"models":[{"input_tokens":262,"output_tokens":27,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"} id:10 event:result :HTTP_STATUS/200 2025-02-13 18:21:10.257: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":"进行对话。需要"},"usage":{"models":[{"input_tokens":262,"output_tokens":31,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"} id:11 event:result :HTTP_STATUS/200 2025-02-13 18:21:10.414: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"null","text":"帮助吗?"},"usage":{"models":[{"input_tokens":262,"output_tokens":34,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"} id:12 event:result :HTTP_STATUS/200 2025-02-13 18:21:10.481: {"output":{"session_id":"830189188149488794708ae012f4c595","finish_reason":"stop","text":""},"usage":{"models":[{"input_tokens":262,"output_tokens":34,"model_id":"qwen-plus"}]},"request_id":"2563953d-914c-9256-ae1a-b62beb957112"}

- Python
- Java
- HTTP
Request exampleResponse example
Copy
import os
import dashscope
from dashscope import DashScopeError
# The following is the configuration for the Singapore region. Replace {WorkspaceId} with your workspace ID. The region value varies by region.
client = dashscope.Client(
# If not using an environment variable, set your API key directly (e.g., api_key="sk-xxx"). However, it is not recommended to hardcode your API key in code in production environments, to reduce the risk of API key leakage.
api_key=os.getenv("DASHSCOPE_API_KEY"),
workspace="{WorkspaceId}",
region="ap-southeast-1",
)
biz_params = {
"city": "杭州"}
try:
stream = client.apps.completions.create(
# Replace with the actual application ID
app_id='YOUR_APP_ID',
prompt='你好',
biz_params=biz_params,
# Enable streaming output
stream=True,
# incremental_output set to true enables incremental output, false disables it, and the default value is false if not specified
incremental_output=True,
# has_thoughts must be set to True
has_thoughts=True)
for response in stream:
print(f'{response.thoughts}\n') # The output only returns thoughts; the process information is returned in the thoughts field
except DashScopeError as e:
print(f'request_id={e.request_id}')
print(f'code={e.code}')
print(f'message={e.message}')
print(f'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')
Copy
[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)]
Request exampleResponse example
Copy
// Recommended dashscope SDK version >= 2.15.0
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import 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()
// If you have not configured an environment variable, replace the following line with .apiKey("sk-xxx") using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("YOUR_APP_ID") //Replace with the actual application ID
.prompt("你好")
.bizParams(JsonUtils.parse(bizParams))
.incrementalOutput(true) // Incremental output
.hasThoughts(true) // For workflow applications to implement streaming output, this parameter must be set to true, and output results can be viewed in the thoughts field
.build();
Application application = new Application();
Flowable<ApplicationResult> result = application.streamCall(param); // Implement streaming output
result.blockingForEach(data -> {
System.out.printf("%s\n",data.getOutput().getThoughts());// Process output to display only the thoughts field
});
}
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/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
Copy
[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)]
- curl
- PHP
- Node.js
- C#
- Go
Request example
Copy
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": {}
}'
Replace YOUR_APP_ID with the actual application ID.Response example
Copy
id:1
event:result
:HTTP_STATUS/200
data:{"output":{"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}
id:2
event:result
:HTTP_STATUS/200
data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"开始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}
id:3
event:result
:HTTP_STATUS/200
data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"开始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_j45e\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}
id:4
event:result
:HTTP_STATUS/200
data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"开始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_1\",\"nodeResult\":\"{\\\"result\\\":\\\"西湖醋鱼,龙\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":5,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}
id:5
event:result
:HTTP_STATUS/200
data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"开始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_1\",\"nodeResult\":\"{\\\"result\\\":\\\"井虾仁,东坡肉,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":13,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}
id:6
event:result
:HTTP_STATUS/200
data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"开始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_1\",\"nodeResult\":\"{\\\"result\\\":\\\"叫花鸡,宋\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":18,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}
id:7
event:result
:HTTP_STATUS/200
data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"开始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_1\",\"nodeResult\":\"{\\\"result\\\":\\\"嫂鱼羹\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1167ms\"}"},{"response":"{\"nodeName\":\"LLM_2Km9\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}
id:8
event:result
:HTTP_STATUS/200
data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"开始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1167ms\"}"},{"response":"{\"nodeName\":\"大模型_2\",\"nodeResult\":\"{\\\"result\\\":\\\"西湖,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}
id:9
event:result
:HTTP_STATUS/200
data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"开始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1167ms\"}"},{"response":"{\"nodeName\":\"大模型_2\",\"nodeResult\":\"{\\\"result\\\":\\\"灵\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":3,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}
id:10
event:result
:HTTP_STATUS/200
data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"开始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1167ms\"}"},{"response":"{\"nodeName\":\"大模型_2\",\"nodeResult\":\"{\\\"result\\\":\\\"隐寺,宋城,西溪\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":11,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}
id:11
event:result
:HTTP_STATUS/200
data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"开始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1167ms\"}"},{"response":"{\"nodeName\":\"大模型_2\",\"nodeResult\":\"{\\\"result\\\":\\\"国家湿地公园,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":15,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}
id:12
event:result
:HTTP_STATUS/200
data:{"output":{"thoughts":[{"response":"{\"nodeName\":\"开始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1167ms\"}"},{"response":"{\"nodeName\":\"大模型_2\",\"nodeResult\":\"{\\\"result\\\":\\\"杭州动物园\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_2Km9\",\"nodeExecTime\":\"1137ms\"}"},{"response":"{\"nodeName\":\"结束\",\"nodeResult\":\"{\\\"result\\\":\\\"亲,对我的介绍还满意吗\\\"}\",\"nodeType\":\"End\",\"nodeStatus\":\"success\",\"nodeId\":\"End_DrQn7F\",\"nodeExecTime\":\"1ms\"}"}],"session_id":"6035ee0814b64a9fb88346ecaf8b44bf","finish_reason":"stop","text":"亲,对我的介绍还满意吗"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":17,"model_id":"qwen-max"}]},"request_id":"64825069-b3aa-93a7-bcf1-c66fe57111fd"}
Request exampleResponse example
Copy
<?php
# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // Replace with the actual application ID
$url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion";
// Construct request data
$data = [
"input" => [
'prompt' => '你好',
'biz_params' => [
'city' => '杭州'
]
],
"parameters" => [
'has_thoughts' => true, // For workflow applications and orchestration applications, this parameter must be set to true, and process information is returned in thoughts
'incremental_output' => true // Incremental output
]
];
// Encode data as JSON
$dataString = json_encode($data);
// Check if json_encode was successful
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// Initialize the cURL session
$ch = curl_init($url);
// Set cURL options
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); // Do not return transfer data
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($ch, $string) {
echo $string; // Process streaming data
return strlen($string);
});
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key,
'X-DashScope-SSE: enable' // Fixed parameter for streaming output
]);
// Execute the request
$response = curl_exec($ch);
// Check whether cURL succeeded
if ($response === false) {
die("cURL Error: " . curl_error($ch));
}
// Get HTTP status code
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close the cURL session
curl_close($ch);
if ($status_code != 200) {
echo "HTTP Status Code: $status_code\n";
echo "Request Failed.\n";
}
?>
Copy
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"}
You need to install the related dependencies:Request exampleResponse example
Copy
npm install axios
Copy
const axios = require('axios');
async function callDashScope() {
// If you have not configured an environment variable, replace the following line with apiKey='sk-xxx' using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';// Replace with the actual application 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'//This parameter needs to be set for workflow applications and agent orchestration applications to implement streaming output
},
debug: {}
};
try {
console.log("Sending request to DashScope API...");
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
'X-DashScope-SSE': 'enable'
},
responseType: 'stream' // For handling streaming responses
});
if (response.status === 200) {
console.log("Request successful:");
// Handle streaming response
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();
Copy
/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.
Request exampleResponse example
Copy
using System.Net;
using System.Text;
class Program
{
static async Task Main(string[] args)
{
//If you have not configured an environment variable, replace the following line with apiKey="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage.
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
string appId = "YOUR_APP_ID"; // Replace with the actual application ID
string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
client.DefaultRequestHeaders.Add("X-DashScope-SSE", "enable");
string jsonContent = @"{
""input"": {
""prompt"": ""你好"",
""biz_params"":{
""city"":""杭州""
}
},
""parameters"": {
""incremental_output"": true,
""has_thoughts"": true
},
""debug"": {}
}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
try
{
var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Content = content;
HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Request successful:");
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
using (var stream = await response.Content.ReadAsStreamAsync())
using (var reader = new StreamReader(stream))
{
string? line; // Declare as nullable string
while ((line = await reader.ReadLineAsync()) != null)
{
if (line.StartsWith("data:"))
{
string data = line.Substring(5).Trim();
Console.WriteLine(data);
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
}
}
}
}
else
{
Console.WriteLine($"Request failed with status code: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error calling DashScope: {ex.Message}");
}
}
}
}
Copy
2025-02-14 16:55:28:670
Request successful:
2025-02-14 16:55:28:980
{"output":{"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"}
2025-02-14 16:55:28:980
{"output":{"thoughts":[{"response":"{\"nodeName\":\"开始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"}
2025-02-14 16:55:28:980
{"output":{"thoughts":[{"response":"{\"nodeName\":\"开始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"LLM_j45e\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"}
2025-02-14 16:55:29:178
{"output":{"thoughts":[{"response":"{\"nodeName\":\"开始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_1\",\"nodeResult\":\"{\\\"result\\\":\\\"西湖醋鱼,龙\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":5,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"}
2025-02-14 16:55:29:780
{"output":{"thoughts":[{"response":"{\"nodeName\":\"开始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_1\",\"nodeResult\":\"{\\\"result\\\":\\\"井虾仁,东坡肉,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":13,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"}
2025-02-14 16:55:29:979
{"output":{"thoughts":[{"response":"{\"nodeName\":\"开始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_1\",\"nodeResult\":\"{\\\"result\\\":\\\"知味小笼,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_j45e\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":18,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"}
2025-02-14 16:55:30:179
{"output":{"thoughts":[{"response":"{\"nodeName\":\"开始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_1\",\"nodeResult\":\"{\\\"result\\\":\\\"叫化鸡\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1315ms\"}"},{"response":"{\"nodeName\":\"LLM_2Km9\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"}
2025-02-14 16:55:30:379
{"output":{"thoughts":[{"response":"{\"nodeName\":\"开始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1315ms\"}"},{"response":"{\"nodeName\":\"大模型_2\",\"nodeResult\":\"{\\\"result\\\":\\\"西湖,\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":2,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"}
2025-02-14 16:55:30:986
{"output":{"thoughts":[{"response":"{\"nodeName\":\"开始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1315ms\"}"},{"response":"{\"nodeName\":\"大模型_2\",\"nodeResult\":\"{\\\"result\\\":\\\"灵隐寺,宋\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"executing\",\"nodeId\":\"LLM_2Km9\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":7,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"}
2025-02-14 16:55:31:180
{"output":{"thoughts":[{"response":"{\"nodeName\":\"开始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1315ms\"}"},{"response":"{\"nodeName\":\"大模型_2\",\"nodeResult\":\"{\\\"result\\\":\\\"城,西溪湿地,千岛湖\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_2Km9\",\"nodeExecTime\":\"1008ms\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"null"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":16,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"}
2025-02-14 16:55:31:382
{"output":{"thoughts":[{"response":"{\"nodeName\":\"开始\",\"nodeType\":\"Start\",\"nodeStatus\":\"success\",\"nodeId\":\"Start_bYxoRU\",\"nodeExecTime\":\"0ms\"}"},{"response":"{\"nodeName\":\"大模型_1\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_j45e\",\"nodeExecTime\":\"1315ms\"}"},{"response":"{\"nodeName\":\"大模型_2\",\"nodeResult\":\"{\\\"result\\\":\\\"\\\"}\",\"nodeType\":\"LLM\",\"nodeStatus\":\"success\",\"nodeId\":\"LLM_2Km9\",\"nodeExecTime\":\"1008ms\"}"},{"response":"{\"nodeName\":\"结束\",\"nodeResult\":\"{\\\"result\\\":\\\"亲,对我的介绍还满意吗\\\"}\",\"nodeType\":\"End\",\"nodeStatus\":\"success\",\"nodeId\":\"End_DrQn7F\",\"nodeExecTime\":\"0ms\"}"}],"session_id":"1a3f45d95e654534bb01bdbf59e9b732","finish_reason":"stop","text":"亲,对我的介绍还满意吗"},"usage":{"models":[{"input_tokens":25,"output_tokens":21,"model_id":"qwen-max"},{"input_tokens":23,"output_tokens":16,"model_id":"qwen-max"}]},"request_id":"520d48fd-d7e8-9632-87e2-1ff866da1151"}
2025-02-14 16:55:31:751
Request exampleResponse example
Copy
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
)
func main() {
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // Replace with the actual application ID
if apiKey == "" {
fmt.Println("请确保设置了DASHSCOPE_API_KEY。")
return
}
url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)
requestBody := map[string]interface{}{
"input": map[string]interface{}{
"prompt": "你好",
"biz_params": map[string]interface{}{
"city": "杭州",
},
},
"parameters": map[string]interface{}{
"incremental_output": true,
"has_thoughts": true,
},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Failed to marshal JSON: %v\n", err)
return
}
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()
scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
line := scanner.Text()
fmt.Println(line)
}
if err := scanner.Err(); err != nil {
fmt.Printf("Error reading response: %v\n", err)
}
if resp.StatusCode != http.StatusOK {
fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
}
}
Copy
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"}
Retrieve knowledge base
As the RAG capability of Model Studio, the knowledge base feature can effectively supplement LLMs with private knowledge and provide up-to-date information. When calling an agent application, you can specify the retrieval scope to improve the accuracy of the LLM's answers. For more information about the knowledge base feature, see Create and use a knowledge base.Prerequisites
In the agent application on the Model Studio console, turn on the knowledge base switch, and then publish the application.Among them, RAG applications can skip this prerequisite.
Specify the retrieval scope
-
To retrieve a specified knowledge base (see Create and use a knowledge base), there are three ways:
- In the application, click Configure to associate the specified knowledge base, and then publish the application;
-
Do not associate a specified knowledge base in the application, and pass the knowledge base ID through
rag_optionswhen calling the API; -
Associate the specified knowledge base in the application, and also pass the knowledge base ID through
rag_optionswhen calling the API.In this case, only the knowledge bases passed in during the call are retrieved. For example, if an agent application on the web console is associated with knowledge base A, but only knowledge base B is specified during the API call, knowledge base A will not be retrieved; only knowledge base B will be retrieved.
Data.Idreturned by the CreateIndex API (only unstructured knowledge bases are supported). Call example: Here, Model Studio series phone product introduction.docx is selected as a file of an unstructured data knowledge base.- Python
- Java
- HTTP
Request exampleResponse exampleCopyimport os # The Dashscope SDK version must be 2.0.1 or later. import dashscope from dashscope import DashScopeError # The following is the configuration for the Singapore region. Replace {WorkspaceId} with your workspace ID. The region value varies by region. client = dashscope.Client( # If not using an environment variable, set your API key directly (e.g., api_key="sk-xxx"). However, it is not recommended to hardcode your API key in code in production environments, to reduce the risk of API key leakage. api_key=os.getenv("DASHSCOPE_API_KEY"), workspace="{WorkspaceId}", region="ap-southeast-1", ) try: response = client.apps.completions.create( app_id='YOUR_APP_ID', # Replace YOUR_APP_ID with the actual application ID prompt='请帮我推荐一款3000元以下的手机', rag_options={ "pipeline_ids": ["YOUR_PIPELINE_ID1,YOUR_PIPELINE_ID2"], # Replace with the actual knowledge base IDs. Use commas to separate multiple IDs } ) print('%s\n' % (response.text)) # Process the text-only output # print('%s\n' % (response.usage)) except DashScopeError as e: print(f'request_id={e.request_id}') print(f'code={e.code}') print(f'message={e.message}') print(f'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')Copy根据您的预算,我推荐您选择**百炼 Zephyr Z9**。这款手机的参考售价在2499-2799元之间,符合您的预算需求。它拥有轻巧的6.4英寸1080 x 2340像素屏幕设计,搭配128GB存储与6GB RAM,适合日常使用。此外,它还配备了4000mAh电池以及支持30倍数字变焦的镜头,能够很好地满足拍照及续航的需求。如果您追求的是轻薄便携且功能全面的手机,那么百炼 Zephyr Z9会是一个不错的选择。Request exampleResponse exampleCopy// Recommended dashscope SDK version >= 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() // If you have not configured an environment variable, replace the following line with .apiKey("sk-xxx") using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage. .apiKey(System.getenv("DASHSCOPE_API_KEY")) .appId("YOUR_APP_ID") // Replace with the actual application ID .prompt("请帮我推荐一款3000元左右的手机") .ragOptions(RagOptions.builder() // Replace with actual specified knowledge base IDs, separate multiple with commas .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());// Process text output only } 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/model-studio/developer-reference/error-code"); } System.exit(0); } }Copy在3000元预算范围内,我推荐您考虑**百炼 Zephyr Z9**。这款手机定价在2499至2799之间,非常符合您的预算要求。它具有以下特点: - **轻巧设计**:6.4英寸屏幕大小适中,便于单手操作。 - **性能均衡**:搭载128GB存储与6GB RAM,对于日常使用来说足够了。 - **续航能力**:配备4000mAh电池,可以满足一天的正常使用需求。 - **拍照功能**:具备30倍数字变焦镜头,适合捕捉远处景物。 如果您更注重游戏体验或对其他方面有特别的需求,请告诉我,以便我能提供更加个性化的建议!- curl
- PHP
- Node.js
- C#
- Go
Request exampleCopycurl -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": {} }'Replace YOUR_APP_ID with the actual application ID, and YOUR_PIPELINE_ID1 with the specified knowledge base ID.
Response exampleCopy{"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"}%Request exampleResponse exampleCopy<?php # 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。 $api_key = getenv("DASHSCOPE_API_KEY"); $application_id = 'YOUR_APP_ID'; // Replace with the actual application ID $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion"; // Construct request data $data = [ "input" => [ 'prompt' => '请帮我推荐一款3000元以下的手机' ], "parameters" => [ 'rag_options' => [ 'pipeline_ids' => ['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2']//Replace with your specified knowledge base IDs, separated by commas for multiple ] ] ]; // Encode data as JSON $dataString = json_encode($data); // Check if json_encode was successful if (json_last_error() !== JSON_ERROR_NONE) { die("JSON encoding failed with error: " . json_last_error_msg()); } // Initialize the cURL session $ch = curl_init($url); // Set cURL options curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Authorization: Bearer ' . $api_key ]); // Execute the request $response = curl_exec($ch); // Check whether cURL succeeded if ($response === false) { die("cURL Error: " . curl_error($ch)); } // Get HTTP status code $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Close the cURL session curl_close($ch); // Decode response data $response_data = json_decode($response, true); // Handle response if ($status_code == 200) { if (isset($response_data['output']['text'])) { echo "{$response_data['output']['text']}\n"; } else { echo "No text in response.\n"; } }else { if (isset($response_data['request_id'])) { echo "request_id={$response_data['request_id']}\n";} echo "code={$status_code}\n"; if (isset($response_data['message'])) { echo "message={$response_data['message']}\n";} else { echo "message=Unknown error\n";} } ?>Copy在3000元以下的预算范围内,我推荐您考虑**百炼 Zephyr Z9**。这款手机定价在2499-2799元之间,非常适合您的预算。它具有轻巧的设计,配备6.4英寸1080 x 2340像素屏幕、128GB存储与6GB RAM,能够很好地满足日常使用需求。此外,其4000mAh电池可以保证一天的正常使用,并且配备了30倍数字变焦镜头来捕捉远处细节,既轻薄又不失强大功能。Required dependencies:Request exampleCopynpm install axiosResponse exampleCopyconst axios = require('axios'); async function callDashScope() { // If you have not configured an environment variable, replace the following line with apiKey='sk-xxx' using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage. const apiKey = process.env.DASHSCOPE_API_KEY; const appId = 'YOUR_APP_ID';//Replace with the actual application 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'] // Replace with your specified knowledge base IDs, separated by commas for multiple } }, 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();Copy在3000元以下的预算内,我推荐您考虑**百炼 Zephyr Z9**。这款手机参考售价为3999-4299元,但如果能赶上促销活动或折扣,可能会降到您的预算范围内。 ### 百炼 Zephyr Z9 ——轻薄便携的艺术 - **屏幕**: 6.4英寸 1080 x 2340像素 - **存储与RAM**: 128GB存储 / 6GB RAM - **电池**: 4000mAh - **相机**: 30倍数字变焦镜头 这款手机的特点是轻薄便携,日常使用非常方便,而且具有不错的续航能力。如果您更关注性价比和日常使用体验,百炼 Zephyr Z9 是一个不错的选择。 如果您的预算非常严格,建议关注电商平台的促销活动,或者考虑其他品牌的同价位手机。希望这些建议对您有所帮助!Request exampleResponse exampleCopyusing System.Text; class Program { static async Task Main(string[] args) { // If you have not configured an environment variable, replace the following line with apiKey="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage. string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");; string appId = "YOUR_APP_ID";// Replace with the actual application ID // Replace YOUR_PIPELINE_ID1 with your specified knowledge base 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}"); } } } }Copy{ "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" }Request exampleResponse exampleCopypackage main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" ) func main() { // If you have not configured an environment variable, replace the following line with apiKey := "sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage. apiKey := os.Getenv("DASHSCOPE_API_KEY") appId := "YOUR_APP_ID" // Replace with the actual application ID if apiKey == "" { fmt.Println("请确保设置了DASHSCOPE_API_KEY。") return } url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId) // Create request body 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"}, // Replace with your specified knowledge base ID }, }, "debug": map[string]interface{}{}, } jsonData, err := json.Marshal(requestBody) if err != nil { fmt.Printf("Failed to marshal JSON: %v\n", err) return } // Create HTTP POST request req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) if err != nil { fmt.Printf("Failed to create request: %v\n", err) return } // Set request headers req.Header.Set("Authorization", "Bearer "+apiKey) req.Header.Set("Content-Type", "application/json") // Send request client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Printf("Failed to send request: %v\n", err) return } defer resp.Body.Close() // Read response body, err := io.ReadAll(resp.Body) if err != nil { fmt.Printf("Failed to read response: %v\n", err) return } // Handle response if resp.StatusCode == http.StatusOK { fmt.Println("Request successful:") fmt.Println(string(body)) } else { fmt.Printf("Request failed with status code: %d\n", resp.StatusCode) fmt.Println(string(body)) } }Copy{ "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" } -
Retrieve the specified unstructured data documents: Pass the knowledge base ID, document ID, document tags, or document metadata (key-value pairs) in
rag_options.Document IDs, document tags, and document metadata only take effect for unstructured data document retrieval.
-
How to obtain:
- Document IDs (file_ids): You can obtain them from the document list on the Application Data page, or use the IDs returned by the AddFile API when importing documents.
- Document tags (tags): You can view the tags of unstructured documents on the Application Data page, or obtain them through the DescribeFile API.
- Document metadata (metadata): On the Knowledge Base page, after entering a knowledge base, you can view the metadata of unstructured documents (Meta information).
- You can pass multiple document IDs; only documents with knowledge indexes established are supported.
- When passing document IDs, you must also pass the ID of the knowledge base to which the documents belong for the retrieval to take effect.
-
Retrieval is performed only in the specified documents. For example: if an agent application on the web console references knowledge base A, but the API call specifies document IDs and the ID of knowledge base B to which they belong, documents in knowledge base A will not be retrieved; only documents in knowledge base B will be retrieved.
This example selects Model Studio series phone product introduction.docx as an unstructured data knowledge base file.
- Python
- Java
- HTTP
Request exampleResponse exampleCopyimport os # The Dashscope SDK version must be 2.0.1 or later. import dashscope from dashscope import DashScopeError # The following is the configuration for the Singapore region. Replace {WorkspaceId} with your workspace ID. The region value varies by region. client = dashscope.Client( # If not using an environment variable, set your API key directly (e.g., api_key="sk-xxx"). However, it is not recommended to hardcode your API key in code in production environments, to reduce the risk of API key leakage. api_key=os.getenv("DASHSCOPE_API_KEY"), workspace="{WorkspaceId}", region="ap-southeast-1", ) try: response = client.apps.completions.create( app_id='YOUR_APP_ID', # Replace YOUR_APP_ID with the actual application ID prompt='请帮我推荐一款3000元以下的手机', rag_options={ "pipeline_ids": ["YOUR_PIPELINE_ID1", "YOUR_PIPELINE_ID2"], # Replace with the actual knowledge base IDs. Use commas to separate multiple IDs "file_ids": ["YOUR_FILE_ID1", "YOUR_FILE_ID2"], # Replace with the actual unstructured document IDs. Use commas to separate multiple IDs "metadata_filter": { # Document metadata key-value pairs. Use commas to separate multiple pairs "key1": "value1", "key2": "value2" }, "tags": ["tag1", "tag2"] # Document tags. Use commas to separate multiple tags } ) print('%s\n' % (response.text)) except DashScopeError as e: print(f'request_id={e.request_id}') print(f'code={e.code}') print(f'message={e.message}') print(f'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')Copy{ "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 }Request exampleResponse exampleCopy// Recommended dashscope SDK version >= 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"); // Metadata key-value pairs metadataFilter.addProperty("key2", "value2"); // For multiple, repeatedly call addProperty ApplicationParam param = ApplicationParam.builder() // If you have not configured an environment variable, replace the following line with .apiKey("sk-xxx") using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage. .apiKey(System.getenv("DASHSCOPE_API_KEY")) .appId("YOUR_APP_ID") // Replace with the actual application ID .prompt("请帮我推荐一款3000元左右的手机") .ragOptions(RagOptions.builder() .pipelineIds(List.of("PIPELINES_ID1","PIPELINES_ID2")) // Replace with actual specified knowledge base IDs, separate multiple with commas .fileIds(List.of("FILE_ID1", "FILE_ID2")) // Replace with actual specified unstructured document IDs, separate multiple with commas .tags(List.of("tags1", "tags2")) // Replace with specified document tag IDs, separate multiple with commas .metadataFilter(metadataFilter) .build()) .build(); Application application = new Application(); ApplicationResult result = application.call(param); System.out.printf("%s\n", result.getOutput().getText());// Process text output only } 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/model-studio/developer-reference/error-code"); } System.exit(0); } }Copy根据您的预算,我为您推荐**百炼 Zephyr Z9**。这款手机的价格在2499-2799元之间,非常适合您3000元左右的预算范围。 ### 百炼 Zephyr Z9 产品亮点: - **屏幕**:6.4英寸、1080 x 2340像素,提供清晰细腻的视觉体验。 - **存储与运行内存**:128GB存储空间和6GB RAM,足以应对日常使用需求。 - **电池**:4000mAh容量电池可以确保一整天的正常使用。 - **摄像头**:支持30倍数字变焦镜头,能够捕捉远处细节。 - **设计**:轻薄便携,适合追求时尚与便捷的用户。 这款手机不仅价格适中,而且配置均衡,在外观设计上也非常出色,是这个价位段非常不错的选择。希望这些建议对您有所帮助!如果还有其他需求或疑问,请随时告诉我。- curl
- PHP
- Node.js
- C#
- Go
Request exampleCopycurl -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": {} }'Replace YOUR_APP_ID with the actual application ID, YOUR_PIPELINE_ID1 with the specified knowledge base ID, YOUR_FILE_ID1 with the specified unstructured document ID, and the key-value pairs in metadata_filter with the actual metadata.
Response exampleCopy{"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"}%Request exampleResponse exampleCopy<?php # 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。 $api_key = getenv("DASHSCOPE_API_KEY"); $application_id = 'YOUR_APP_ID'; // Replace with the actual application ID $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion"; // Construct request data $data = [ "input" => [ 'prompt' => '请帮我推荐一款3000元以下的手机' ], "parameters" => [ 'rag_options' => [ 'pipeline_ids' => ['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2'],// Replace with your specified knowledge base IDs, separated by commas for multiple 'file_ids' => ['YOUR_FILE_ID1','YOUR_FILE_ID2'],// Replace with actual document IDs, separated by commas "metadata_filter" => [ // Metadata key-value pairs "key1" => "value1", "key2" => "value2" ], "tags" => ["标签1", "标签2"] // Document tags ] ] ]; // Encode data as JSON $dataString = json_encode($data); // Check if json_encode was successful if (json_last_error() !== JSON_ERROR_NONE) { die("JSON encoding failed with error: " . json_last_error_msg()); } // Initialize the cURL session $ch = curl_init($url); // Set cURL options curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Authorization: Bearer ' . $api_key ]); // Execute the request $response = curl_exec($ch); // Check whether cURL succeeded if ($response === false) { die("cURL Error: " . curl_error($ch)); } // Get HTTP status code $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Close the cURL session curl_close($ch); // Decode response data $response_data = json_decode($response, true); // Handle response if ($status_code == 200) { if (isset($response_data['output']['text'])) { echo "{$response_data['output']['text']}\n"; } else { echo "No text in response.\n"; } }else { if (isset($response_data['request_id'])) { echo "request_id={$response_data['request_id']}\n";} echo "code={$status_code}\n"; if (isset($response_data['message'])) { echo "message={$response_data['message']}\n";} else { echo "message=Unknown error\n";} } ?>Copy根据您的预算,我为您推荐**百炼 Zephyr Z9**。这款手机的参考售价在2499-2799元之间,非常适合3000元以下的需求。它拥有轻巧的6.4英寸1080 x 2340像素设计,搭配128GB存储与6GB RAM,可以满足日常使用需求。此外,其配备4000mAh电池确保一天无忧,并且还有30倍数字变焦镜头捕捉远处细节,是一款既轻薄又不失强大的选择。Required dependencies:Request exampleCopynpm install axiosResponse exampleCopyconst axios = require('axios'); async function callDashScope() { // If you have not configured an environment variable, replace the following line with apiKey='sk-xxx' using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage. const apiKey = process.env.DASHSCOPE_API_KEY; const appId = 'YOUR_APP_ID';//Replace with the actual application 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'], // Replace with your specified knowledge base IDs, separated by commas for multiple file_ids:['YOUR_FILE_ID1','YOUR_FILE_ID2'], // Replace with the specified file IDs, separate multiple IDs with commas metadata_filter:{ // Metadata key-value pairs, separate multiple pairs with commas 'key1':'value1', 'key2':'value2' }, tags: ['标签1', '标签2'] // Document tags, separate multiple tags with commas } }, debug: {} }; try { const response = await axios.post(url, data, { headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' } }); if (response.status === 200) { console.log(`${response.data.output.text}`); } else { console.log(`request_id=${response.headers['request_id']}`); console.log(`code=${response.status}`); console.log(`message=${response.data.message}`); } } catch (error) { console.error(`Error calling DashScope: ${error.message}`); if (error.response) { console.error(`Response status: ${error.response.status}`); console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`); } } } callDashScope();Copy在3000元以下的预算范围内,我推荐您考虑**百炼 Zephyr Z9**。这款手机的价格区间是2499-2799元,它拥有轻薄便携的设计,配备6.4英寸1080 x 2340像素屏幕、128GB存储与6GB RAM,能够满足日常使用需求。其4000mAh电池保证了一天的使用时间,而30倍数字变焦镜头则可以帮助捕捉到更远距离的细节。总体来说,这是一款性价比较高的选择。Request exampleResponse exampleCopyusing System.Text; class Program { static async Task Main(string[] args) { // If you have not configured an environment variable, replace the following line with apiKey="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage. string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");; string appId = "YOUR_APP_ID";// Replace with the actual application ID // Replace YOUR_PIPELINE_ID1 with your specified knowledge base ID and YOUR_FILE_ID1 with your specified unstructured document 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}"); } } } }Copy{ "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" }Request exampleResponse exampleCopypackage main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" ) func main() { // If you have not configured an environment variable, replace the following line with apiKey := "sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage. apiKey := os.Getenv("DASHSCOPE_API_KEY") appId := "YOUR_APP_ID" // Replace with the actual application ID if apiKey == "" { fmt.Println("请确保设置了DASHSCOPE_API_KEY。") return } url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId) // Create request body 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"}, // Replace with specified unstructured knowledge base ID "file_ids": []string{"YOUR_FILE_ID1"}, // Replace with specified unstructured document ID "metadata_filter": map[string]string{ "name": "张三", // Metadata key-value pairs }, "tags": "手机", // Unstructured data document tags }, }, "debug": map[string]interface{}{}, } jsonData, err := json.Marshal(requestBody) if err != nil { fmt.Printf("Failed to marshal JSON: %v\n", err) return } // Create HTTP POST request req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) if err != nil { fmt.Printf("Failed to create request: %v\n", err) return } // Set request headers req.Header.Set("Authorization", "Bearer "+apiKey) req.Header.Set("Content-Type", "application/json") // Send request client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Printf("Failed to send request: %v\n", err) return } defer resp.Body.Close() // Read response body, err := io.ReadAll(resp.Body) if err != nil { fmt.Printf("Failed to read response: %v\n", err) return } // Handle response if resp.StatusCode == http.StatusOK { fmt.Println("Request successful:") fmt.Println(string(body)) } else { fmt.Printf("Request failed with status code: %d\n", resp.StatusCode) fmt.Println(string(body)) } }Copy{ "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" }
-
How to obtain:
-
Retrieve the specified data in structured data documents: Pass the knowledge base ID and the key-value pairs of the structured data document's "structured data header + value" in
rag_options. Obtain the structured data key-value pairs (structured_filter): On the Knowledge Base page, after entering a knowledge base, you can click View Index to view the index information of structured documents.- Python
- Java
- HTTP
Request exampleResponse exampleCopyimport os # The Dashscope SDK version must be 2.0.1 or later. import dashscope from dashscope import DashScopeError # The following is the configuration for the Singapore region. Replace {WorkspaceId} with your workspace ID. The region value varies by region. client = dashscope.Client( # If not using an environment variable, set your API key directly (e.g., api_key="sk-xxx"). However, it is not recommended to hardcode your API key in code in production environments, to reduce the risk of API key leakage. api_key=os.getenv("DASHSCOPE_API_KEY"), workspace="{WorkspaceId}", region="ap-southeast-1", ) try: response = client.apps.completions.create( app_id='YOUR_APP_ID', # Replace YOUR_APP_ID with the actual application ID prompt='请帮我推荐一款3000元以下的手机', rag_options={ "pipeline_ids": ["YOUR_PIPELINE_ID1", "YOUR_PIPELINE_ID2"], # Replace with the actual knowledge base IDs. Use commas to separate multiple IDs "structured_filter": { # Structured data key-value pairs, corresponding to the structured data. Use commas to separate multiple pairs "key1": "value1", "key2": "value2" } } ) print('%s\n' % (response.text)) except DashScopeError as e: print(f'request_id={e.request_id}') print(f'code={e.code}') print(f'message={e.message}') print(f'Refer to the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code')Copy{ "text": "我为您推荐"百炼"这款手机,它的价格是2999元,符合您的预算要求。如果您需要了解更多信息,比如性能、外观等,请告诉我。", "finish_reason": "stop", "session_id": "80a3b868b5ce42c8a12f01dccf8651e2", "thoughts": null, "doc_references": null }Request exampleResponse exampleCopy// Recommended dashscope SDK version >= 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"); // Structured data key-value pairs structureFilter.addProperty("key2", "value2"); // For multiple, repeatedly call addProperty ApplicationParam param = ApplicationParam.builder() // If you have not configured an environment variable, replace the following line with .apiKey("sk-xxx") using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage. .apiKey(System.getenv("DASHSCOPE_API_KEY")) .appId("YOUR_APP_ID") // Replace with the actual application ID .prompt("请帮我推荐一款3000元左右的手机") .ragOptions(RagOptions.builder() .pipelineIds(List.of("PIPELINE_ID1","PIPELINE_ID2")) // Replace with actual specified knowledge base IDs, separate multiple with commas .structuredFilter(structureFilter) .build()) .build(); Application application = new Application(); ApplicationResult result = application.call(param); System.out.printf("%s\n", result.getOutput().getText());// Process text output only } 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/model-studio/developer-reference/error-code"); } System.exit(0); } }Copy我为您推荐"百炼"这款手机,它的价格是2999.0元,符合您的预算要求。如果您需要了解更多关于这款手机的信息,比如配置、性能等,请告诉我,我会为您提供更详细的资料。- curl
- PHP
- Node.js
- C#
- Go
Request exampleCopycurl -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": {} }'Replace YOUR_APP_ID with the actual application ID, and YOUR_PIPELINE_ID1 with the specified knowledge base ID.
Response exampleCopy{"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"}%Request exampleResponse exampleCopy<?php # 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。 $api_key = getenv("DASHSCOPE_API_KEY"); $application_id = 'YOUR_APP_ID'; // Replace with the actual application ID $url = "https://dashscope-intl.aliyuncs.com/api/v1/apps/$application_id/completion"; // Construct request data $data = [ "input" => [ 'prompt' => '请帮我推荐一款3000元以下的手机' ], "parameters" => [ 'rag_options' => [ 'pipeline_ids' => ['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2'],// Replace with your specified knowledge base IDs, separated by commas for multiple "structured_filter" => [ // Structured data key-value pairs; use commas to separate multiple entries "key1" => "value1", "key2" => "value2" ] ] ] ]; // Encode data as JSON $dataString = json_encode($data); // Check if json_encode was successful if (json_last_error() !== JSON_ERROR_NONE) { die("JSON encoding failed with error: " . json_last_error_msg()); } // Initialize the cURL session $ch = curl_init($url); // Set cURL options curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Authorization: Bearer ' . $api_key ]); // Execute the request $response = curl_exec($ch); // Check whether cURL succeeded if ($response === false) { die("cURL Error: " . curl_error($ch)); } // Get HTTP status code $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Close the cURL session curl_close($ch); // Decode response data $response_data = json_decode($response, true); // Handle response if ($status_code == 200) { if (isset($response_data['output']['text'])) { echo "{$response_data['output']['text']}\n"; } else { echo "No text in response.\n"; } }else { if (isset($response_data['request_id'])) { echo "request_id={$response_data['request_id']}\n";} echo "code={$status_code}\n"; if (isset($response_data['message'])) { echo "message={$response_data['message']}\n";} else { echo "message=Unknown error\n";} } ?>Copy我为您推荐"百炼"这款手机,它的价格是2999元,符合您的预算要求。如果您需要了解更多关于这款手机的信息,请告诉我。Required dependencies:Request exampleCopynpm install axiosResponse exampleCopyconst axios = require('axios'); async function callDashScope() { // If you have not configured an environment variable, replace the following line with apiKey='sk-xxx' using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage. const apiKey = process.env.DASHSCOPE_API_KEY; const appId = 'YOUR_APP_ID'; // Replace with the actual application ID // Replace YOUR_PIPELINE_ID1 with your specified knowledge base IDs, separated by commas 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();Copy我为您推荐"百炼"这款手机,它的价格是2999元,符合您的预算要求。如果您需要了解更多详情或有其他特定需求,请告诉我!Request exampleResponse exampleCopyusing System.Text; class Program { static async Task Main(string[] args) { // If you have not configured an environment variable, replace the following line with apiKey="sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage. string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");; string appId = "YOUR_APP_ID";// Replace with the actual application ID // Replace YOUR_PIPELINE_ID1 with your specified knowledge base 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}"); } } } }Copy{ "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" }Request exampleResponse exampleCopypackage main import ( "bytes" "encoding/json" "fmt" "io" "net/http" "os" ) func main() { // If you have not configured an environment variable, replace the following line with apiKey := "sk-xxx" using your Model Studio API key. However, do not hard code your API key directly in the code for production environments to reduce the risk of API key leakage. apiKey := os.Getenv("DASHSCOPE_API_KEY") appId := "YOUR_APP_ID" // Replace with the actual application ID if apiKey == "" { fmt.Println("请确保设置了DASHSCOPE_API_KEY。") return } url := fmt.Sprintf("https://dashscope-intl.aliyuncs.com/api/v1/apps/%s/completion", appId) // Create request body 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"}, // Replace with specified structured knowledge base ID "structured_filter": map[string]string{ "price": "2999", // Structured data key-value pairs }, }, }, "debug": map[string]interface{}{}, } jsonData, err := json.Marshal(requestBody) if err != nil { fmt.Printf("Failed to marshal JSON: %v\n", err) return } // Create HTTP POST request req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) if err != nil { fmt.Printf("Failed to create request: %v\n", err) return } // Set request headers req.Header.Set("Authorization", "Bearer "+apiKey) req.Header.Set("Content-Type", "application/json") // Send request client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Printf("Failed to send request: %v\n", err) return } defer resp.Body.Close() // Read response body, err := io.ReadAll(resp.Body) if err != nil { fmt.Printf("Failed to read response: %v\n", err) return } // Handle response if resp.StatusCode == http.StatusOK { fmt.Println("Request successful:") fmt.Println(string(body)) } else { fmt.Printf("Request failed with status code: %d\n", resp.StatusCode) fmt.Println(string(body)) } }Copy{ "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" }
View Information
To view retrieval process information: Add has_thoughts in the code and set it to True when calling; the retrieval process information will then be returned in the thoughts field of output.
To view answer source information: Turn on the Show Source switch in the Configure section of the agent application and publish the application; you can then view the answer sources in the response of the call.

API Reference
You can view the complete parameter list in Workflow and legacy agent application API application DashScope API Reference.Error Codes
If the call fails and returns an error message, refer to Error Codes to resolve it.Related Documentation
- For model selection within applications, go to the Model Studio console.
- For building and using applications, refer to Introduction to application types.
- For using Prompt assistance tools in applications, refer to Prompt plug-ins.
FAQ
What should I do if an exception such as java: package com.alibaba.dashscope.app does not exist occurs when running the Java code example?
What should I do if an exception such as java: package com.alibaba.dashscope.app does not exist occurs when running the Java code example?
- Check whether the class names and package names in the import statements are correct.
- Add the dependency library: If you use Maven or Gradle for project management, make sure the DashScope Java SDK dependency library has been added to the
pom.xmlorbuild.gradlefile and is the latest version. You can visit Maven to obtain the latest version number of the DashScope Java SDK.
Copy
<!-- https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dashscope-sdk-java</artifactId>
<version>在此处填写最新版本号,例如2.16.4</version>
</dependency>
Copy
// https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java
implementation group: 'com.alibaba', name: 'dashscope-sdk-java', version: '在此处填写最新版本号,例如2.16.4'
- Upgrade the SDK: Earlier versions of the DashScope Java SDK may not contain the features or classes you are trying to use. If you have already added the DashScope Java SDK dependency library, make sure the DashScope Java SDK you are using is the latest version. If the current version is earlier, upgrade it to the latest version. You can change the DashScope Java SDK version to the latest version in the
pom.xmlorbuild.gradlefile.
Copy
<!-- https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dashscope-sdk-java</artifactId>
<version>请将此处的版本号修改为最新版本</version>
</dependency>
Copy
// https://mvnrepository.com/artifact/com.alibaba/dashscope-sdk-java
implementation group: 'com.alibaba', name: 'dashscope-sdk-java', version: '请将此处的版本号修改为最新版本'
- Reload the project for the changes to take effect.
- Run the code example again. If the problem persists, see the Model Studio FAQ or submit a ticket for further assistance.