请求体 | 单轮对话Python请求示例 import os
from http import HTTPStatus
from dashscope import Application
response = Application.call(
# 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='YOUR_APP_ID',
prompt='你是谁?')
if response.status_code != HTTPStatus.OK:
print(f'request_id={response.request_id}')
print(f'code={response.status_code}')
print(f'message={response.message}')
print(f'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
else:
print(response.output.text)
Java请求示例 // 建议dashscope SDK的版本 >= 2.12.0
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
public class Main {
public static void appCall()
throws ApiException, NoApiKeyException, InputRequiredException {
ApplicationParam param = ApplicationParam.builder()
// 若没有配置环境变量,可用百炼API Key将下行替换为:.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("YOUR_APP_ID")
.prompt("你是谁?")
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
System.out.printf("text: %s\n",
result.getOutput().getText());
}
public static void main(String[] args) {
try {
appCall();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.err.println("message:"+e.getMessage());
System.out.println("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPcurl请求示例 curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "你是谁?"
},
"parameters": {},
"debug": {}
}'
YOUR_APP_ID替换为实际的应用 ID。 PHP请求示例 <?php
# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // 替换为实际的应用 ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";
// 构造请求数据
$data = [
"input" => [
'prompt' => '你是谁?'
]
];
// 将数据编码为 JSON
$dataString = json_encode($data);
// 检查 json_encode 是否成功
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// 初始化 cURL 对话
$ch = curl_init($url);
// 设置 cURL 选项
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
]);
// 执行请求
$response = curl_exec($ch);
// 检查 cURL 执行是否成功
if ($response === false) {
die("cURL Error: " . curl_error($ch));
}
// 获取 HTTP 状态码
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 关闭 cURL 对话
curl_close($ch);
// 解码响应数据
$response_data = json_decode($response, true);
// 处理响应
if ($status_code == 200) {
if (isset($response_data['output']['text'])) {
echo "{$response_data['output']['text']}\n";
} else {
echo "No text in response.\n";
}}
else {
if (isset($response_data['request_id'])) {
echo "request_id={$response_data['request_id']}\n";}
echo "code={$status_code}\n";
if (isset($response_data['message'])) {
echo "message={$response_data['message']}\n";}
else {
echo "message=Unknown error\n";}
}
?>
Node.js需安装相关依赖: npm install axios
请求示例 const axios = require('axios');
async function callDashScope() {
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';// 替换为实际的应用 ID
const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "你是谁?"
},
parameters: {},
debug: {}
};
try {
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
console.log(`${response.data.output.text}`);
} else {
console.log(`request_id=${response.headers['request_id']}`);
console.log(`code=${response.status}`);
console.log(`message=${response.data.message}`);
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();
C#请求示例 using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
//若没有配置环境变量,可用百炼API Key将下行替换为:apiKey="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
string appId = "YOUR_APP_ID"; // 替换为实际的应用ID
string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
string jsonContent = @"{
""input"": {
""prompt"": ""你是谁?""
},
""parameters"": {},
""debug"": {}
}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("Request successful:");
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Request failed with status code: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error calling DashScope: {ex.Message}");
}
}
}
}
Go请求示例 package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // 替换为实际的应用 ID
if apiKey == "" {
fmt.Println("请确保设置了DASHSCOPE_API_KEY。")
return
}
url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)
// 创建请求体
requestBody := map[string]interface{}{
"input": map[string]string{
"prompt": "你是谁?",
},
"parameters": map[string]interface{}{},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Failed to marshal JSON: %v\n", err)
return
}
// 创建 HTTP POST 请求
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("Failed to create request: %v\n", err)
return
}
// 设置请求头
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// 发送请求
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Failed to send request: %v\n", err)
return
}
defer resp.Body.Close()
// 读取响应
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// 处理响应
if resp.StatusCode == http.StatusOK {
fmt.Println("Request successful:")
fmt.Println(string(body))
} else {
fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
fmt.Println(string(body))
}
}
调用智能体应用实现Prompt样例库功能时,还需要在上述代码的parameters对象中添加并设置has_thoughts 参数为True,检索的过程信息在thoughts 字段中返回。 多轮对话多轮对话通过传递session_id 实现。关于调用应用多轮对话功能的更多用法请参考:多轮对话。 Python请求示例 import os
from http import HTTPStatus
from dashscope import Application
def call_with_session():
response = Application.call(
# 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='YOUR_APP_ID', # 替换为实际的应用 ID
prompt='你是谁?')
if response.status_code != HTTPStatus.OK:
print(f'request_id={response.request_id}')
print(f'code={response.status_code}')
print(f'message={response.message}')
print(f'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
return response
responseNext = Application.call(
# 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='YOUR_APP_ID', # 替换为实际的应用 ID
prompt='你有什么技能?',
session_id=response.output.session_id) # 上一轮response的session_id
if responseNext.status_code != HTTPStatus.OK:
print(f'request_id={responseNext.request_id}')
print(f'code={responseNext.status_code}')
print(f'message={responseNext.message}')
print(f'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
else:
print('%s\n session_id=%s\n' % (responseNext.output.text, responseNext.output.session_id))
# print('%s\n' % (response.usage))
if __name__ == '__main__':
call_with_session()
Java请求示例 import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void callWithSession()
throws ApiException, NoApiKeyException, InputRequiredException {
ApplicationParam param = ApplicationParam.builder()
// 若没有配置环境变量,可用百炼API Key将下行替换为:.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// 替换为实际的应用 ID
.appId("YOUR_APP_ID")
.prompt("你是谁?")
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
param.setSessionId(result.getOutput().getSessionId());
param.setPrompt("你有什么技能?");
result = application.call(param);
System.out.printf("%s\n, session_id: %s\n",
result.getOutput().getText(), result.getOutput().getSessionId());
}
public static void main(String[] args) {
try {
callWithSession();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.printf("Exception: %s", e.getMessage());
System.out.println("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPcurl请求示例(上一轮对话) curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "你是谁?"
},
"parameters": {},
"debug": {}
}'
请求示例(下一轮对话) curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "你有什么技能?",
"session_id":"4f8ef7233dc641aba496cb201fa59f8c"
},
"parameters": {},
"debug": {}
}'
PHP请求示例(上一轮对话) <?php
# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // 替换为实际的应用 ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";
// 构造请求数据
$data = [
"input" => [
'prompt' => '你是谁?'
]
];
// 将数据编码为 JSON
$dataString = json_encode($data);
// 检查 json_encode 是否成功
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// 初始化 cURL 对话
$ch = curl_init($url);
// 设置 cURL 选项
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
]);
// 执行请求
$response = curl_exec($ch);
// 检查 cURL 执行是否成功
if ($response === false) {
die("cURL Error: " . curl_error($ch));
}
// 获取 HTTP 状态码
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 关闭 cURL 对话
curl_close($ch);
// 解码响应数据
$response_data = json_decode($response, true);
// 处理响应
if ($status_code == 200) {
if (isset($response_data['output']['text'])) {
echo "{$response_data['output']['text']}\n";
} else {
echo "No text in response.\n";
};
if (isset($response_data['output']['session_id'])) {
echo "session_id={$response_data['output']['session_id']}\n";
}
}else {
if (isset($response_data['request_id'])) {
echo "request_id={$response_data['request_id']}\n";}
echo "code={$status_code}\n";
if (isset($response_data['message'])) {
echo "message={$response_data['message']}\n";}
else {
echo "message=Unknown error\n";}
}
?>
请求示例(下一轮对话) <?php
# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // 替换为实际的应用 ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";
// 构造请求数据
$data = [
"input" => [
'prompt' => '你有什么技能?',
// 替换为实际上一轮对话返回的session_id
'session_id' => '2e658bcb514f4d30ab7500b4766a8d43'
]
];
// 将数据编码为 JSON
$dataString = json_encode($data);
// 检查 json_encode 是否成功
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// 初始化 cURL 对话
$ch = curl_init($url);
// 设置 cURL 选项
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
]);
// 执行请求
$response = curl_exec($ch);
// 检查 cURL 执行是否成功
if ($response === false) {
die("cURL Error: " . curl_error($ch));
}
// 获取 HTTP 状态码
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 关闭 cURL 对话
curl_close($ch);
// 解码响应数据
$response_data = json_decode($response, true);
// 处理响应
if ($status_code == 200) {
if (isset($response_data['output']['text'])) {
echo "{$response_data['output']['text']}\n";
} else {
echo "No text in response.\n";
};
if (isset($response_data['output']['session_id'])) {
echo "session_id={$response_data['output']['session_id']}\n";
}
}else {
if (isset($response_data['request_id'])) {
echo "request_id={$response_data['request_id']}\n";}
echo "code={$status_code}\n";
if (isset($response_data['message'])) {
echo "message={$response_data['message']}\n";}
else {
echo "message=Unknown error\n";}
}
?>
Node.js需安装相关依赖: npm install axios
请求示例(上一轮对话) const axios = require('axios');
async function callDashScope() {
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';// 替换为实际的应用 ID
const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "你是谁?"
},
parameters: {},
debug: {}
};
try {
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
console.log(`${response.data.output.text}`);
console.log(`session_id=${response.data.output.session_id}`);
} else {
console.log(`request_id=${response.headers['request_id']}`);
console.log(`code=${response.status}`);
console.log(`message=${response.data.message}`);
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();
请求示例(下一轮对话) const axios = require('axios');
async function callDashScope() {
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';// 替换为实际的应用 ID
const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
// session_id替换为实际上一轮对话的session_id
const data = {
input: {
prompt: "你有什么技能?",
session_id: 'fe4ce8b093bf46159ea9927a7b22f0d3',
},
parameters: {},
debug: {}
};
try {
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
console.log(`${response.data.output.text}`);
console.log(`session_id=${response.data.output.session_id}`);
} else {
console.log(`request_id=${response.headers['request_id']}`);
console.log(`code=${response.status}`);
console.log(`message=${response.data.message}`);
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();
C#请求示例(上一轮对话) using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
//若没有配置环境变量,可用百炼API Key将下行替换为:apiKey="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
string appId = "YOUR_APP_ID"; // 替换为实际的应用ID
string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
string jsonContent = @"{
""input"": {
""prompt"": ""你是谁?""
},
""parameters"": {},
""debug"": {}
}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("Request successful:");
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Request failed with status code: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error calling DashScope: {ex.Message}");
}
}
}
}
请求示例(下一轮对话) using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
//若没有配置环境变量,可用百炼API Key将下行替换为:apiKey="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
string appId = "YOUR_APP_ID"; // 替换为实际的应用ID
string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
string jsonContent = @"{
""input"": {
""prompt"": ""你有什么技能?"",
""session_id"": ""7b830e4cc8fe44faad0e648f9b71435f""
},
""parameters"": {},
""debug"": {}
}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("Request successful:");
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Request failed with status code: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error calling DashScope: {ex.Message}");
}
}
}
}
Go请求示例(上一轮对话) package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // 替换为实际的应用 ID
if apiKey == "" {
fmt.Println("请确保设置了DASHSCOPE_API_KEY。")
return
}
url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)
// 创建请求体
requestBody := map[string]interface{}{
"input": map[string]string{
"prompt": "你是谁?",
},
"parameters": map[string]interface{}{},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Failed to marshal JSON: %v\n", err)
return
}
// 创建 HTTP POST 请求
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("Failed to create request: %v\n", err)
return
}
// 设置请求头
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// 发送请求
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Failed to send request: %v\n", err)
return
}
defer resp.Body.Close()
// 读取响应
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// 处理响应
if resp.StatusCode == http.StatusOK {
fmt.Println("Request successful:")
fmt.Println(string(body))
} else {
fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
fmt.Println(string(body))
}
}
请求示例(下一轮对话) package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // 替换为实际的应用 ID
if apiKey == "" {
fmt.Println("请确保设置了DASHSCOPE_API_KEY。")
return
}
url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)
// 创建请求体
requestBody := map[string]interface{}{
"input": map[string]string{
"prompt": "你有什么技能?",
"session_id": "f7eea37f0c734c20998a021b688d6de2", // 替换为实际上一轮对话的session_id
},
"parameters": map[string]interface{}{},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Failed to marshal JSON: %v\n", err)
return
}
// 创建 HTTP POST 请求
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("Failed to create request: %v\n", err)
return
}
// 设置请求头
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// 发送请求
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Failed to send request: %v\n", err)
return
}
defer resp.Body.Close()
// 读取响应
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// 处理响应
if resp.StatusCode == http.StatusOK {
fmt.Println("Request successful:")
fmt.Println(string(body))
} else {
fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
fmt.Println(string(body))
}
}
YOUR_APP_ID替换为实际的应用 ID。下一轮对话的输入参数session_id 字段值替换为实际上一轮对话返回的session_id值。 目前仅智能体应用和对话型工作流应用支持多轮对话功能。 自定义参数透传关于调用应用自定义参数透传功能的更多用法请参考:自定义参数透传。 Python请求示例 import os
from http import HTTPStatus
# 建议dashscope SDK 的版本 >= 1.14.0
from dashscope import Application
biz_params = {
# 智能体应用的自定义插件输入参数透传,自定义的插件ID替换{your_plugin_code}
"user_defined_params": {
"{your_plugin_code}": {
"article_index": 2}}}
response = Application.call(
# 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='YOUR_APP_ID',
prompt='寝室公约内容',
biz_params=biz_params)
if response.status_code != HTTPStatus.OK:
print(f'request_id={response.request_id}')
print(f'code={response.status_code}')
print(f'message={response.message}')
print(f'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
else:
print('%s\n' % (response.output.text)) # 处理只输出文本text
# print('%s\n' % (response.usage))
Java请求示例 import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
public class Main {
public static void appCall() throws NoApiKeyException, InputRequiredException {
String bizParams =
// 智能体应用的自定义插件输入参数透传,自定义的插件ID替换{your_plugin_code}
"{\"user_defined_params\":{\"{your_plugin_code}\":{\"article_index\":2}}}";
ApplicationParam param = ApplicationParam.builder()
// 若没有配置环境变量,可用百炼API Key将下行替换为:.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("YOUR_APP_ID")
.prompt("寝室公约内容")
.bizParams(JsonUtils.parse(bizParams))
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
System.out.printf("%s\n",
result.getOutput().getText());
}
public static void main(String[] args) {
try {
appCall();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.printf("Exception: %s", e.getMessage());
System.out.println("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPcurl请求示例 curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "寝室公约内容",
"biz_params":
{
"user_defined_params":
{
"{your_plugin_code}":
{
"article_index": 2
}
}
}
},
"parameters": {},
"debug":{}
}'
YOUR_APP_ID替换为实际的应用 ID。 PHP请求示例 <?php
# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // 替换为实际的应用 ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";
//{your_plugin_code}替换为实际的插件ID
// 构造请求数据
$data = [
"input" => [
'prompt' => '寝室公约内容',
'biz_params' => [
'user_defined_params' => [
'{your_plugin_code}' => [
'article_index' => 2
]
]
]
],
];
// 将数据编码为 JSON
$dataString = json_encode($data);
// 检查 json_encode 是否成功
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// 初始化 cURL 对话
$ch = curl_init($url);
// 设置 cURL 选项
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
]);
// 执行请求
$response = curl_exec($ch);
// 检查 cURL 执行是否成功
if ($response === false) {
die("cURL Error: " . curl_error($ch));
}
// 获取 HTTP 状态码
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 关闭 cURL 对话
curl_close($ch);
// 解码响应数据
$response_data = json_decode($response, true);
// 处理响应
if ($status_code == 200) {
if (isset($response_data['output']['text'])) {
echo "{$response_data['output']['text']}\n";
} else {
echo "No text in response.\n";
}
}else {
if (isset($response_data['request_id'])) {
echo "request_id={$response_data['request_id']}\n";}
echo "code={$status_code}\n";
if (isset($response_data['message'])) {
echo "message={$response_data['message']}\n";}
else {
echo "message=Unknown error\n";}
}
?>
Node.js需安装相关依赖: npm install axios
请求示例 const axios = require('axios');
async function callDashScope() {
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';// 替换为实际的应用 ID
const pluginCode = 'YOUR_PLUGIN_CODE';// 替换为实际的插件ID
const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "寝室公约内容",
biz_params: {
user_defined_params: {
[pluginCode]: {
// article_index为自定义插件的变量,替换为实际的插件变量
'article_index': 3
}
}
}
},
parameters: {},
debug: {}
};
try {
console.log("Sending request to DashScope API...");
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
if (response.data.output && response.data.output.text) {
console.log(`${response.data.output.text}`);
}
} else {
console.log("Request failed:");
if (response.data.request_id) {
console.log(`request_id=${response.data.request_id}`);
}
console.log(`code=${response.status}`);
if (response.data.message) {
console.log(`message=${response.data.message}`);
} else {
console.log('message=Unknown error');
}
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();
C#请求示例 using System.Text;
class Program
{
static async Task Main(string[] args)
{
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");;
string appId = "YOUR_APP_ID";// 替换为实际的应用ID
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("请确保设置了 DASHSCOPE_API_KEY。");
return;
}
string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
string pluginCode = "{your_plugin_code}"; // {your_plugin_code}替换为实际的插件 ID
string jsonContent = $@"{{
""input"": {{
""prompt"": ""寝室公约内容"",
""biz_params"": {{
""user_defined_params"": {{
""{pluginCode}"": {{
""article_index"": 2
}}
}}
}}
}},
""parameters"": {{}},
""debug"": {{}}
}}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("Request successful:");
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Request failed with status code: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error calling DashScope: {ex.Message}");
}
}
}
}
Go请求示例 package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // 替换为实际的应用 ID
pluginCode := "YOUR_PLUGIN_CODE" // 替换为实际的插件 ID
if apiKey == "" {
fmt.Println("请确保设置了DASHSCOPE_API_KEY。")
return
}
url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)
// 创建请求体
requestBody := map[string]interface{}{
"input": map[string]interface{}{
"prompt": "寝室公约内容",
"biz_params": map[string]interface{}{
"user_defined_params": map[string]interface{}{
pluginCode: map[string]interface{}{
"article_index": 2,
},
},
},
},
"parameters": map[string]interface{}{},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Failed to marshal JSON: %v\n", err)
return
}
// 创建 HTTP POST 请求
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("Failed to create request: %v\n", err)
return
}
// 设置请求头
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// 发送请求
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Failed to send request: %v\n", err)
return
}
defer resp.Body.Close()
// 读取响应
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// 处理响应
if resp.StatusCode == http.StatusOK {
fmt.Println("Request successful:")
fmt.Println(string(body))
} else {
fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
fmt.Println(string(body))
}
}
流式输出关于调用应用流式输出功能的更多用法请参考:流式输出。 Python请求示例 import os
from http import HTTPStatus
from dashscope import Application
responses = Application.call(
# 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='YOUR_APP_ID',
prompt='你是谁?',
stream=True, # 流式输出
incremental_output=True) # 增量输出
for response in responses:
if response.status_code != HTTPStatus.OK:
print(f'request_id={response.request_id}')
print(f'code={response.status_code}')
print(f'message={response.message}')
print(f'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
else:
print(f'{response.output.text}\n') # 处理只输出文本text
Java请求示例 // 建议dashscope SDK的版本 >= 2.15.0
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import io.reactivex.Flowable;// 流式输出
// 智能体应用调用实现流式输出结果
public class Main {
public static void streamCall() throws NoApiKeyException, InputRequiredException {
ApplicationParam param = ApplicationParam.builder()
// 若没有配置环境变量,可用百炼API Key将下行替换为:.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// 替换为实际的应用 ID
.appId("YOUR_APP_ID")
.prompt("你是谁?")
// 增量输出
.incrementalOutput(true)
.build();
Application application = new Application();
// .streamCall():流式输出内容
Flowable<ApplicationResult> result = application.streamCall(param);
result.blockingForEach(data -> {
System.out.printf("%s\n",
data.getOutput().getText());
});
}
public static void main(String[] args) {
try {
streamCall();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.printf("Exception: %s", e.getMessage());
System.out.println("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPcurl请求示例 curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--header 'X-DashScope-SSE: enable' \
--data '{
"input": {
"prompt": "你是谁?"
},
"parameters": {
"incremental_output":true
},
"debug": {}
}'
YOUR_APP_ID替换为实际的应用 ID。 PHP请求示例 <?php
// 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // 替换为实际的应用 ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";
// 构造请求数据
$data = [
"input" => [
'prompt' => '你是谁?'],
"parameters" => [
'incremental_output' => true]];// 增量输出
// 将数据编码为 JSON
$dataString = json_encode($data);
// 检查 json_encode 是否成功
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// 初始化 cURL 对话
$ch = curl_init($url);
// 设置 cURL 选项
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); // 不返回传输的数据
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($ch, $string) {
echo $string; // 处理流式数据
return strlen($string);
});
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key,
'X-DashScope-SSE: enable' // 流式输出
]);
// 执行请求
$response = curl_exec($ch);
// 检查 cURL 执行是否成功
if ($response === false) {
die("cURL Error: " . curl_error($ch));
}
// 获取 HTTP 状态码
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 关闭 cURL 对话
curl_close($ch);
if ($status_code != 200) {
echo "HTTP Status Code: $status_code\n";
echo "Request Failed.\n";
}
?>
Node.js需安装相关依赖: npm install axios
请求示例 const axios = require('axios');
async function callDashScope() {
//若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';// 替换为实际的应用 ID
const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "你是谁?"
},
parameters: {
'incremental_output' : 'true' // 增量输出
},
debug: {}
};
try {
console.log("Sending request to DashScope API...");
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
'X-DashScope-SSE': 'enable' // 流式输出
},
responseType: 'stream' // 用于处理流式响应
});
if (response.status === 200) {
// 处理流式响应
response.data.on('data', (chunk) => {
console.log(`Received chunk: ${chunk.toString()}`);
});
} else {
console.log("Request failed:");
if (response.data.request_id) {
console.log(`request_id=${response.data.request_id}`);
}
console.log(`code=${response.status}`);
if (response.data.message) {
console.log(`message=${response.data.message}`);
} else {
console.log('message=Unknown error');
}
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();
C#请求示例 using System.Text;
class Program
{
static async Task Main(string[] args)
{
//若没有配置环境变量,可用百炼API Key将下行替换为:apiKey="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");
string appId = "YOUR_APP_ID"; // 替换为实际的应用ID
string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
client.DefaultRequestHeaders.Add("X-DashScope-SSE", "enable");
string jsonContent = @"{
""input"": {
""prompt"": ""你是谁?""
},
""parameters"": {""incremental_output"": true},
""debug"": {}
}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("Request successful:");
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Request failed with status code: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error calling DashScope: {ex.Message}");
}
}
}
}
Go请求示例 package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // 替换为实际的应用 ID
if apiKey == "" {
fmt.Println("请确保设置了DASHSCOPE_API_KEY。")
return
}
url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)
// 创建请求体
requestBody := map[string]interface{}{
"input": map[string]string{
"prompt": "你是谁?",
},
"parameters": map[string]interface{}{
"incremental_output": true,
},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Failed to marshal JSON: %v\n", err)
return
}
// 创建 HTTP POST 请求
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("Failed to create request: %v\n", err)
return
}
// 设置请求头
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-DashScope-SSE", "enable")
// 发送请求
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Failed to send request: %v\n", err)
return
}
defer resp.Body.Close()
// 读取响应
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// 处理响应
if resp.StatusCode == http.StatusOK {
fmt.Println("Request successful:")
fmt.Println(string(body))
} else {
fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
fmt.Println(string(body))
}
}
调用工作流应用与智能体编排应用实现流式输出功能,需将has_thoughts 设置为True。 长期记忆关于调用应用长期记忆功能的更多用法请参考:长期记忆。 Python请求示例(创建记忆体内容) from http import HTTPStatus
import os
from dashscope import Application
response = Application.call(
# 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='YOUR_APP_ID', # 请输入实际的应用 ID
prompt='用户饮食偏好:面食',
memory_id='YOUR_MEMORY_ID') # 请输入实际的记忆体 ID
if response.status_code != HTTPStatus.OK:
print(f'request_id={response.request_id}')
print(f'code={response.status_code}')
print(f'message={response.message}')
print(f'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
else:
print('%s\n' % (response.output.text)) # 处理只输出text
# print('%s\n' % (response.usage))
请求示例(再次调用) from http import HTTPStatus
import os
from dashscope import Application
response = Application.call(
# 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='YOUR_APP_ID', # 请输入实际的应用 ID
prompt='美食推荐',
memory_id='YOUR_MEMORY_ID') # 请输入实际的记忆体 ID
if response.status_code != HTTPStatus.OK:
print(f'request_id={response.request_id}')
print(f'code={response.status_code}')
print(f'message={response.message}')
print(f'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
else:
print('%s\n' % (response.output.text)) # 处理只输出text
# print('%s\n' % (response.usage))
Java请求示例(创建记忆体内容) import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
public class Main {
public static void callWithMemory() throws NoApiKeyException, InputRequiredException {
ApplicationParam param = ApplicationParam.builder()
// 若没有配置环境变量,可用百炼API Key将下行替换为:.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("YOUR_APP_ID") // 替换为实际的应用 ID
.prompt("用户饮食偏好:面食")
.memoryId("YOUR_MEMORY_ID") // 替换为实际的记忆体 ID
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
System.out.printf("%s\n",
result.getOutput().getText()); // 处理只输出文本text
}
public static void main(String[] args) {
try {
callWithMemory();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.printf("Exception: %s", e.getMessage());
System.out.println("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
请求示例(再次调用) import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
public class Main {
public static void callWithMemory() throws NoApiKeyException, InputRequiredException {
ApplicationParam param = ApplicationParam.builder()
// 若没有配置环境变量,可用百炼API Key将下行替换为:.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("YOUR_APP_ID") // 替换为实际的应用 ID
.prompt("美食推荐")
.memoryId("YOUR_MEMORY_ID") // 替换为实际的记忆体 ID
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
System.out.printf("text: %s\n",
result.getOutput().getText()); // 处理只输出文本text
}
public static void main(String[] args) {
try {
callWithMemory();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.printf("Exception: %s", e.getMessage());
System.out.println("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPcurl请求示例(创建记忆体内容) curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "用户饮食偏好:面食",
"memory_id": "YOUR_MEMORY_ID"
},
"parameters": {},
"debug": {}
}'
请求示例(再次调用) curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/YOUR_APP_ID/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "美食推荐",
"memory_id": "YOUR_MEMORY_ID"
},
"parameters": {},
"debug": {}
}'
YOUR_APP_ID替换为实际的应用 ID。 PHP请求示例(生成记忆体内容) <?php
# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // 替换为实际的应用 ID
$memory_id = 'YOUR_MEMORY_ID'; // 替换为实际的记忆体 ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/{$application_id}/completion";
// 构造请求数据
$data = [
"input" => [
'prompt' => '用户饮食偏好:面食',
'memory_id' => $memory_id
]
];
// 将数据编码为 JSON
$dataString = json_encode($data);
// 检查 json_encode 是否成功
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// 初始化 cURL 对话
$ch = curl_init($url);
// 设置 cURL 选项
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
]);
// 执行请求
$response = curl_exec($ch);
// 检查 cURL 执行是否成功
if ($response === false) {
die("cURL Error: " . curl_error($ch));
}
// 获取 HTTP 状态码
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 关闭 cURL 对话
curl_close($ch);
// 解码响应数据
$response_data = json_decode($response, true);
// 处理响应
if ($status_code == 200) {
if (isset($response_data['output']['text'])) {
echo "{$response_data['output']['text']}\n";
} else {
echo "No text in response.\n";
}
}else {
if (isset($response_data['request_id'])) {
echo "request_id={$response_data['request_id']}\n";}
echo "code={$status_code}\n";
if (isset($response_data['message'])) {
echo "message={$response_data['message']}\n";}
else {
echo "message=Unknown error\n";}
}
?>
请求示例(再次调用) <?php
# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // 替换为实际的应用 ID
$memory_id = 'YOUR_MEMORY_ID'; // 替换为实际的记忆体 ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/{$application_id}/completion";
// 构造请求数据
$data = [
"input" => [
'prompt' => '美食推荐',
'memory_id' => $memory_id
]
];
// 将数据编码为 JSON
$dataString = json_encode($data);
// 检查 json_encode 是否成功
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// 初始化 cURL 对话
$ch = curl_init($url);
// 设置 cURL 选项
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
]);
// 执行请求
$response = curl_exec($ch);
// 检查 cURL 执行是否成功
if ($response === false) {
die("cURL Error: " . curl_error($ch));
}
// 获取 HTTP 状态码
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 关闭 cURL 对话
curl_close($ch);
// 解码响应数据
$response_data = json_decode($response, true);
// 处理响应
if ($status_code == 200) {
if (isset($response_data['output']['text'])) {
echo "{$response_data['output']['text']}\n";
} else {
echo "No text in response.\n";
}
}else {
if (isset($response_data['request_id'])) {
echo "request_id={$response_data['request_id']}\n";}
echo "code={$status_code}\n";
if (isset($response_data['message'])) {
echo "message={$response_data['message']}\n";}
else {
echo "message=Unknown error\n";}
}
?>
Node.js需安装相关依赖: npm install axios
请求示例(创建记忆体内容) const axios = require('axios');
async function callDashScope() {
//若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';// 替换为实际的应用 ID
const memoryId = 'YOUR_MEMORY_ID';// 替换为实际的memory_id
const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "用户饮食偏好:面食",
memory_id: memoryId
},
parameters: {},
debug: {}
};
try {
console.log("Sending request to DashScope API...");
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
if (response.data.output && response.data.output.text) {
console.log(`${response.data.output.text}`);
}
} else {
console.log("Request failed:");
if (response.data.request_id) {
console.log(`request_id=${response.data.request_id}`);
}
console.log(`code=${response.status}`);
if (response.data.message) {
console.log(`message=${response.data.message}`);
} else {
console.log('message=Unknown error');
}
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();
请求示例(再次调用) const axios = require('axios');
async function callDashScope() {
//若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';// 替换为实际的应用 ID
const memoryId = 'YOUR_MEMORY_ID';// 替换为实际的memory_id
const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "美食推荐",
memory_id: memoryId
},
parameters: {},
debug: {}
};
try {
console.log("Sending request to DashScope API...");
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
if (response.data.output && response.data.output.text) {
console.log(`${response.data.output.text}`);
}
} else {
console.log("Request failed:");
if (response.data.request_id) {
console.log(`request_id=${response.data.request_id}`);
}
console.log(`code=${response.status}`);
if (response.data.message) {
console.log(`message=${response.data.message}`);
} else {
console.log('message=Unknown error');
}
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();
C#请求示例(创建记忆体内容) using System.Text;
class Program
{
static async Task Main(string[] args)
{
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");;
string appId = "YOUR_APP_ID";// 替换为实际的应用ID
string memoryId = "YOUR_MEMORY_ID";//替换为实际的memory_id
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("请确保设置了 DASHSCOPE_API_KEY。");
return;
}
string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
string jsonContent = $@"{{
""input"": {{
""prompt"": ""用户饮食偏好:面食"",
""memory_id"":""{memoryId}""
}},
""parameters"": {{}},
""debug"": {{}}
}}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Request failed with status code: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error calling DashScope: {ex.Message}");
}
}
}
}
请求示例(再次调用) using System.Text;
class Program
{
static async Task Main(string[] args)
{
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");;
string appId = "YOUR_APP_ID";// 替换为实际的应用ID
string memoryId = "YOUR_MEMORY_ID";//替换为实际的memory_id
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("请确保设置了 DASHSCOPE_API_KEY。");
return;
}
string url = $"https://dashscope.aliyuncs.com/api/v1/apps/{appId}/completion";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
string jsonContent = $@"{{
""input"": {{
""prompt"": ""美食推荐"",
""memory_id"":""{memoryId}""
}},
""parameters"": {{}},
""debug"": {{}}
}}";
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Request failed with status code: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error calling DashScope: {ex.Message}");
}
}
}
}
Go请求示例(创建记忆体内容) package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // 替换为实际的应用 ID
if apiKey == "" {
fmt.Println("请确保设置了DASHSCOPE_API_KEY。")
return
}
url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)
// 创建请求体
requestBody := map[string]interface{}{
"input": map[string]string{
"prompt": "用户饮食偏好:面食",
"memory_id": "YOUR_MEMORY_ID", // 替换为实际的记忆体 ID
},
"parameters": map[string]interface{}{},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Failed to marshal JSON: %v\n", err)
return
}
// 创建 HTTP POST 请求
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("Failed to create request: %v\n", err)
return
}
// 设置请求头
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// 发送请求
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Failed to send request: %v\n", err)
return
}
defer resp.Body.Close()
// 读取响应
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// 处理响应
if resp.StatusCode == http.StatusOK {
fmt.Println("Request successful:")
fmt.Println(string(body))
} else {
fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
fmt.Println(string(body))
}
}
请求示例(再次调用) package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // 替换为实际的应用 ID
if apiKey == "" {
fmt.Println("请确保设置了DASHSCOPE_API_KEY。")
return
}
url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)
// 创建请求体
requestBody := map[string]interface{}{
"input": map[string]string{
"prompt": "美食推荐",
"memory_id": "YOUR_MEMORY_ID", // 替换为实际的记忆体 ID
},
"parameters": map[string]interface{}{},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Failed to marshal JSON: %v\n", err)
return
}
// 创建 HTTP POST 请求
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("Failed to create request: %v\n", err)
return
}
// 设置请求头
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// 发送请求
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Failed to send request: %v\n", err)
return
}
defer resp.Body.Close()
// 读取响应
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// 处理响应
if resp.StatusCode == http.StatusOK {
fmt.Println("Request successful:")
fmt.Println(string(body))
} else {
fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
fmt.Println(string(body))
}
}
目前仅智能体应用支持长期记忆功能。 指定知识库关于调用应用指定知识库功能的更多用法请参考:指定知识库。 Python请求示例 import os
from http import HTTPStatus
# 建议dashscope SDK 的版本 >= 1.20.11
from dashscope import Application
response = Application.call(
# 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
api_key=os.getenv("DASHSCOPE_API_KEY"),
app_id='YOUR_APP_ID', # 应用ID替换YOUR_APP_ID
prompt='请帮我推荐一款3000元以下的手机',
rag_options={
"pipeline_ids": ["YOUR_PIPELINE_ID1,YOUR_PIPELINE_ID2"], # 替换为实际的知识库 ID,逗号隔开多个
}
)
if response.status_code != HTTPStatus.OK:
print(f'request_id={response.request_id}')
print(f'code={response.status_code}')
print(f'message={response.message}')
print(f'请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
else:
print('%s\n' % (response.output.text)) # 处理只输出文本text
# print('%s\n' % (response.usage))
Java请求示例 // 建议dashscope SDK 的版本 >= 2.16.8;
import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import java.util.Collections;
import java.util.List;
public class Main {
public static void streamCall() throws NoApiKeyException, InputRequiredException {
ApplicationParam param = ApplicationParam.builder()
// 若没有配置环境变量,可用百炼API Key将下行替换为:.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.appId("YOUR_APP_ID") // 替换为实际的应用ID
.prompt("请帮我推荐一款3000元左右的手机")
.ragOptions(RagOptions.builder()
// 替换为实际指定的知识库 ID,逗号隔开多个
.pipelineIds(List.of("PIPELINES_ID1", "PIPELINES_ID2"))
.build())
.build();
Application application = new Application();
ApplicationResult result = application.call(param);
System.out.printf("%s\n",
result.getOutput().getText());// 处理只输出文本text
}
public static void main(String[] args) {
try {
streamCall();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.printf("Exception: %s", e.getMessage());
System.out.println("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
HTTPcurl请求示例 curl -X POST https://dashscope.aliyuncs.com/api/v1/apps/{YOUR_APP_ID}/completion \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"input": {
"prompt": "请帮我推荐一款3000元以下的手机"
},
"parameters": {
"rag_options" : {
"pipeline_ids":["YOUR_PIPELINE_ID1"]}
},
"debug": {}
}'
YOUR_APP_ID替换为实际的应用 ID,YOUR_PIPELINE_ID1替换为指定的知识库ID。 PHP请求示例 <?php
# 若没有配置环境变量,可用百炼API Key将下行替换为:$api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
$api_key = getenv("DASHSCOPE_API_KEY");
$application_id = 'YOUR_APP_ID'; // 替换为实际的应用 ID
$url = "https://dashscope.aliyuncs.com/api/v1/apps/$application_id/completion";
// 构造请求数据
$data = [
"input" => [
'prompt' => '请帮我推荐一款3000元以下的手机'
],
"parameters" => [
'rag_options' => [
'pipeline_ids' => ['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2']//替换为指定的知识库 ID,逗号隔开多个
]
]
];
// 将数据编码为 JSON
$dataString = json_encode($data);
// 检查 json_encode 是否成功
if (json_last_error() !== JSON_ERROR_NONE) {
die("JSON encoding failed with error: " . json_last_error_msg());
}
// 初始化 cURL 对话
$ch = curl_init($url);
// 设置 cURL 选项
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
]);
// 执行请求
$response = curl_exec($ch);
// 检查 cURL 执行是否成功
if ($response === false) {
die("cURL Error: " . curl_error($ch));
}
// 获取 HTTP 状态码
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// 关闭 cURL 对话
curl_close($ch);
// 解码响应数据
$response_data = json_decode($response, true);
// 处理响应
if ($status_code == 200) {
if (isset($response_data['output']['text'])) {
echo "{$response_data['output']['text']}\n";
} else {
echo "No text in response.\n";
}
}else {
if (isset($response_data['request_id'])) {
echo "request_id={$response_data['request_id']}\n";}
echo "code={$status_code}\n";
if (isset($response_data['message'])) {
echo "message={$response_data['message']}\n";}
else {
echo "message=Unknown error\n";}
}
?>
Node.js需安装相关依赖: npm install axios
请求示例 const axios = require('axios');
async function callDashScope() {
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
const apiKey = process.env.DASHSCOPE_API_KEY;
const appId = 'YOUR_APP_ID';//替换为实际的应用 ID
const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
const data = {
input: {
prompt: "请帮我推荐一款3000元以下的手机"
},
parameters: {
rag_options:{
pipeline_ids:['YOUR_PIPELINE_ID1','YOUR_PIPELINE_ID2'] // 替换为指定的知识库 ID,多个请用逗号隔开
}
},
debug: {}
};
try {
const response = await axios.post(url, data, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
if (response.status === 200) {
console.log(`${response.data.output.text}`);
} else {
console.log(`request_id=${response.headers['request_id']}`);
console.log(`code=${response.status}`);
console.log(`message=${response.data.message}`);
}
} catch (error) {
console.error(`Error calling DashScope: ${error.message}`);
if (error.response) {
console.error(`Response status: ${error.response.status}`);
console.error(`Response data: ${JSON.stringify(error.response.data, null, 2)}`);
}
}
}
callDashScope();
C#请求示例 using System.Text;
class Program
{
static async Task Main(string[] args)
{
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
string apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY")?? throw new InvalidOperationException("DASHSCOPE_API_KEY environment variable is not set.");;
string appId = "YOUR_APP_ID";// 替换为实际的应用ID
// YOUR_PIPELINE_ID1替换为指定的知识库ID
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("请确保设置了 DASHSCOPE_API_KEY。");
return;
}
string url = $"https://dashscope.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}");
}
}
}
}
Go请求示例 package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
// 若没有配置环境变量,可用百炼API Key将下行替换为:apiKey := "sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
apiKey := os.Getenv("DASHSCOPE_API_KEY")
appId := "YOUR_APP_ID" // 替换为实际的应用 ID
if apiKey == "" {
fmt.Println("请确保设置了DASHSCOPE_API_KEY。")
return
}
url := fmt.Sprintf("https://dashscope.aliyuncs.com/api/v1/apps/%s/completion", appId)
// 创建请求体
requestBody := map[string]interface{}{
"input": map[string]string{
"prompt": "请帮我推荐一款3000元以下的手机",
},
"parameters": map[string]interface{}{
"rag_options": map[string]interface{}{
"pipeline_ids": []string{"YOUR_PIPELINE_ID1"}, // 替换为指定的知识库ID
},
},
"debug": map[string]interface{}{},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
fmt.Printf("Failed to marshal JSON: %v\n", err)
return
}
// 创建 HTTP POST 请求
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Printf("Failed to create request: %v\n", err)
return
}
// 设置请求头
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// 发送请求
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Failed to send request: %v\n", err)
return
}
defer resp.Body.Close()
// 读取响应
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("Failed to read response: %v\n", err)
return
}
// 处理响应
if resp.StatusCode == http.StatusOK {
fmt.Println("Request successful:")
fmt.Println(string(body))
} else {
fmt.Printf("Request failed with status code: %d\n", resp.StatusCode)
fmt.Println(string(body))
}
}
可以在上述代码的parameters对象中添加并设置has_thoughts 参数为True,处理代码输出完整响应结果,参与检索的知识库信息会在output 中的thoughts 字段中返回。 |