本文以通义千问-Plus为例,引导您通过API调用子业务空间(即非默认业务空间)中的模型。
适用场景
调用前准备
如果您尚不清楚主账号与子账号的概念,请先阅读权限管理。
准备子业务空间:了解如何创建子业务空间。若子业务空间已存在,无需操作。如何查看您所有的业务空间。
请注意,如果百炼控制台页面顶部显示以下消息,您需要开通百炼的模型服务(可获得免费调用额度)。如果未显示该消息,则表示您已经开通。
如果开通服务时提示“您尚未进行实名认证”,请先进行实名认证。
模型授权:子业务空间的成员能否调用某个标准模型(例如通义千问-Plus模型)取决于此业务空间是否具有该模型的调用权限。请为此业务空间进行模型授权。
在百炼调优后的模型部署成功后,仅支持在其业务空间内调用,无需模型授权。
添加用户:将需要调用模型的子账号添加至已准备好的子业务空间中(成员角色选择管理员或访客均可)。
若您希望直接使用主账号调用,无需操作。
获取API Key:需要调用模型的用户还需在步骤1准备的子业务空间中自行创建一个API Key并配置API Key到环境变量。
加入子业务空间:请联系主账号持有者,将您的子账号添加至已准备好的子业务空间中(成员角色选择管理员或访客均可)。
若您的子账号已属于该子业务空间,无需操作。如何查看您所有的业务空间。
请注意,如果百炼控制台页面顶部显示以下消息,请联系主账号持有者开通百炼的模型服务(可获得免费调用额度)。如果未显示该消息,则表示您已经开通。
模型授权:子业务空间的成员能否调用某个标准模型(例如通义千问-Plus模型)取决于此业务空间是否具有该模型的调用权限,需要向主账号持有者申请模型授权。如何确认是否需要授权。
在百炼调优后的模型部署成功后,仅支持在其业务空间内调用,无需模型授权。
获取API Key:请您在步骤1加入的子业务空间中自行创建一个API Key并配置API Key到环境变量。
开始调用
OpenAI 兼容
此处以文本输入为例,通过 OpenAI 兼容方式调用子业务空间的通义千问-Plus模型(标准模型,且已完成模型授权)。在调用时,(子业务空间的模型调用)与默认业务空间的模型调用的区别仅在于:必须使用该子业务空间内的 API Key。
在百炼调优后的模型部署成功后,不支持通过OpenAI兼容方式调用,您可以通过DashScope方式调用。
使用SDK调用时需配置的base_url:https://dashscope.aliyuncs.com/compatible-mode/v1
使用HTTP方式调用时需配置的endpoint:POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
使用SDK调用时需配置的base_url:https://dashscope-finance.aliyuncs.com/compatible-mode/v1
使用HTTP方式调用时需配置的endpoint:POST https://dashscope-finance.aliyuncs.com/compatible-mode/v1/chat/completions
请注意,在运行下面的示例之前:
请选择您熟悉的语言,并准备好本地开发环境,用于运行示例,详见选择开发语言。
如果您通过OpenAI SDK进行调用,还需要安装OpenAI SDK。
import os
from openai import OpenAI
client = OpenAI(
# 若没有配置环境变量,请用您子业务空间的百炼API Key将下行替换为:api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen-plus", # 此处以qwen-plus为例,可按需更换模型名称(须完成模型授权,且是标准模型)。支持模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
messages=[
{'role': 'system', 'content': 'You are a helpful assistant.'},
{'role': 'user', 'content': '你是谁?'}],
)
print(completion.model_dump_json())
import OpenAI from "openai";
const openai = new OpenAI(
{
// 若没有配置环境变量,请用您子业务空间的百炼API Key将下行替换为:apiKey: "sk-xxx",
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1"
}
);
async function main() {
const completion = await openai.chat.completions.create({
model: "qwen-plus", //此处以qwen-plus为例,可按需更换模型名称(须完成模型授权,且是标准模型)。支持模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
messages: [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "你是谁?" }
],
});
console.log(JSON.stringify(completion))
}
main();
若没有配置环境变量,请用您子业务空间的百炼API Key将代码中$DASHSCOPE_API_KEY
替换为:sk-xxx
。
此处以qwen-plus为例,可按需更换模型名称(须完成模型授权,且是标准模型)。支持模型列表。
curl -X POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-plus",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "你是谁?"
}
]
}'
<?php
// 设置请求的URL
$url = 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions';
// 若没有配置环境变量,请用您子业务空间的百炼API Key将下行替换为:$apiKey = "sk-xxx";
$apiKey = getenv('DASHSCOPE_API_KEY');
// 设置请求头
$headers = [
'Authorization: Bearer '.$apiKey,
'Content-Type: application/json'
];
// 设置请求体
$data = [
// 此处以qwen-plus为例,可按需更换模型名称(须完成模型授权,且是标准模型)。支持模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
"model" => "qwen-plus",
"messages" => [
[
"role" => "system",
"content" => "You are a helpful assistant."
],
[
"role" => "user",
"content" => "你是谁?"
]
]
];
// 初始化cURL会话
$ch = curl_init();
// 设置cURL选项
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// 执行cURL会话
$response = curl_exec($ch);
// 检查是否有错误发生
if (curl_errno($ch)) {
echo 'Curl error: ' . curl_error($ch);
}
// 关闭cURL资源
curl_close($ch);
// 输出响应结果
echo $response;
?>
using System.Net.Http.Headers;
using System.Text;
class Program
{
private static readonly HttpClient httpClient = new HttpClient();
static async Task Main(string[] args)
{
// 若没有配置环境变量,请用您子业务空间的百炼API Key将下行替换为:string? apiKey = "sk-xxx";
string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("API Key 未设置。请确保环境变量 'DASHSCOPE_API_KEY' 已设置。");
return;
}
// 设置请求 URL 和内容
string url = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";
// 此处以qwen-plus为例,可按需更换模型名称(须完成模型授权,且是标准模型)。支持模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
string jsonContent = @"{
""model"": ""qwen-plus"",
""messages"": [
{
""role"": ""system"",
""content"": ""You are a helpful assistant.""
},
{
""role"": ""user"",
""content"": ""你是谁?""
}
]
}";
// 发送请求并获取响应
string result = await SendPostRequestAsync(url, jsonContent, apiKey);
// 输出结果
Console.WriteLine(result);
}
private static async Task<string> SendPostRequestAsync(string url, string jsonContent, string apiKey)
{
using (var content = new StringContent(jsonContent, Encoding.UTF8, "application/json"))
{
// 设置请求头
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// 发送请求并获取响应
HttpResponseMessage response = await httpClient.PostAsync(url, content);
// 处理响应
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
else
{
return $"请求失败: {response.StatusCode}";
}
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
)
type Message struct {
Role string `json:"role"`
Content string `json:"content"`
}
type RequestBody struct {
Model string `json:"model"`
Messages []Message `json:"messages"`
}
func main() {
// 创建 HTTP 客户端
client := &http.Client{}
// 构建请求体
requestBody := RequestBody{
// 此处以qwen-plus为例,可按需更换模型名称(须完成模型授权,且是标准模型)。支持模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
Model: "qwen-plus",
Messages: []Message{
{
Role: "system",
Content: "You are a helpful assistant.",
},
{
Role: "user",
Content: "你是谁?",
},
},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
log.Fatal(err)
}
// 创建 POST 请求
req, err := http.NewRequest("POST", "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions", bytes.NewBuffer(jsonData))
if err != nil {
log.Fatal(err)
}
// 设置请求头
// 若没有配置环境变量,请用您子业务空间的百炼API Key将下行替换为:apiKey := "sk-xxx"
apiKey := os.Getenv("DASHSCOPE_API_KEY")
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// 发送请求
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
// 读取响应体
bodyText, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
// 打印响应内容
fmt.Printf("%s\n", bodyText)
}
OpenAI未提供Java SDK。如需通过Java SDK调用,请参考本文的DashScope章节。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import com.google.gson.Gson;
public class Main {
static class Message {
String role;
String content;
public Message(String role, String content) {
this.role = role;
this.content = content;
}
}
static class RequestBody {
String model;
Message[] messages;
public RequestBody(String model, Message[] messages) {
this.model = model;
this.messages = messages;
}
}
public static void main(String[] args) {
try {
// 创建请求体
RequestBody requestBody = new RequestBody(
//此处以qwen-plus为例,可按需更换模型名称(须完成模型授权,且是标准模型)。支持模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
"qwen-plus",
new Message[] {
new Message("system", "You are a helpful assistant."),
new Message("user", "你是谁?")
}
);
// 将请求体转换为 JSON
Gson gson = new Gson();
String jsonInputString = gson.toJson(requestBody);
// 创建 URL 对象
URL url = new URL("https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
// 设置请求方法为 POST
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/json; utf-8");
httpURLConnection.setRequestProperty("Accept", "application/json");
// 若没有配置环境变量,请用您子业务空间的百炼API Key将下行替换为:String apiKey = "sk-xxx";
String apiKey = System.getenv("DASHSCOPE_API_KEY");
String auth = "Bearer " + apiKey;
httpURLConnection.setRequestProperty("Authorization", auth);
// 启用输入输出流
httpURLConnection.setDoOutput(true);
// 写入请求体
try (OutputStream os = httpURLConnection.getOutputStream()) {
byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
// 获取响应码
int responseCode = httpURLConnection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 读取响应体
try (BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder response = new StringBuilder();
String responseLine;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println("Response Body: " + response);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
System.exit(0);
}
}
}
DashScope
此处以文本输入为例,通过 DashScope 方式调用子业务空间的通义千问-Plus模型(标准模型,且已完成模型授权)。在调用时,(子业务空间的模型调用)与默认业务空间的模型调用的区别仅在于:必须使用该子业务空间内的 API Key。
通过HTTP调用时需配置的endpoint:
使用通义千问大语言模型:POST https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
使用通义千问VL或通义千问Audio模型:POST https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
通过HTTP调用时需配置的endpoint:
使用通义千问大语言模型:
POST https://dashscope-finance.aliyuncs.com/api/v1/services/aigc/text-generation/generation
通过SDK调用时需配置的base_url:
https://dashscope-finance.aliyuncs.com/api/v1
Python:在导入模块之后,添加以下代码:
dashscope.base_http_api_url = 'https://dashscope-finance.aliyuncs.com/api/v1'
Java :将
Generation gen = new Generation();
修改为Generation gen = new Generation("http", "https://dashscope-finance.aliyuncs.com/api/v1");
请注意,在运行下面的示例之前:
请选择您熟悉的语言,并准备好本地开发环境,用于运行示例,详见选择开发语言。
如果您通过DashScope SDK进行调用,还需要安装DashScope SDK。
import os
import dashscope
messages = [
{'role': 'system', 'content': 'You are a helpful assistant.'},
{'role': 'user', 'content': '你是谁?'}
]
response = dashscope.Generation.call(
# 若没有配置环境变量,请用您子业务空间的百炼API Key将下行替换为:api_key="sk-xxx",
api_key=os.getenv('DASHSCOPE_API_KEY'),
# 下方模型以qwen-plus为例,可按需更换模型名称(标准模型须完成模型授权)。标准模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
# 在百炼调优后的模型,无需模型授权,请更换为部署成功后的model名称。如何获取,详见模型部署:https://help.aliyun.com/zh/model-studio/user-guide/model-deployment
model="qwen-plus",
messages=messages,
result_format='message'
)
print(response)
// 建议dashscope SDK的版本 >= 2.12.0
import java.util.Arrays;
import java.lang.System;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
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 GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
Generation gen = new Generation();
Message systemMsg = Message.builder()
.role(Role.SYSTEM.getValue())
.content("You are a helpful assistant.")
.build();
Message userMsg = Message.builder()
.role(Role.USER.getValue())
.content("你是谁?")
.build();
GenerationParam param = GenerationParam.builder()
// 若没有配置环境变量,请用您子业务空间的百炼API Key将下行替换为:.apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// 下方模型以qwen-plus为例,可按需更换模型名称(标准模型须完成模型授权)。标准模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
// 在百炼调优后的模型,无需模型授权,请更换为部署成功后的model名称。如何获取,详见模型部署:https://help.aliyun.com/zh/model-studio/user-guide/model-deployment
.model("qwen-plus")
.messages(Arrays.asList(systemMsg, userMsg))
.resultFormat(GenerationParam.ResultFormat.MESSAGE)
.build();
return gen.call(param);
}
public static void main(String[] args) {
try {
GenerationResult result = callWithMessage();
System.out.println(JsonUtils.toJson(result));
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
// 使用日志框架记录异常信息
System.err.println("An error occurred while calling the generation service: " + e.getMessage());
}
System.exit(0);
}
}
若没有配置环境变量,请用您子业务空间的百炼API Key将代码中$DASHSCOPE_API_KEY
替换为:sk-xxx
。
此处以qwen-plus为例,可按需更换模型名称(标准模型须完成模型授权)。标准模型列表:模型列表。
在百炼调优后的模型,无需模型授权,请更换为部署成功后的model名称。如何获取,详见模型部署。
curl --location "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"model": "qwen-plus",
"input":{
"messages":[
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "你是谁?"
}
]
},
"parameters": {
"result_format": "message"
}
}'
<?php
$url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
// 若没有配置环境变量,请用您子业务空间的百炼API Key将下行替换为:$apiKey = "sk-xxx";
$apiKey = getenv('DASHSCOPE_API_KEY');
$data = [
// 下方模型以qwen-plus为例,可按需更换模型名称(标准模型须完成模型授权)。标准模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
// 在百炼调优后的模型,无需模型授权,请更换为部署成功后的model名称。如何获取,详见模型部署:https://help.aliyun.com/zh/model-studio/user-guide/model-deployment
"model" => "qwen-plus",
"input" => [
"messages" => [
[
"role" => "system",
"content" => "You are a helpful assistant."
],
[
"role" => "user",
"content" => "你是谁?"
]
]
],
"parameters" => [
"result_format" => "message"
]
];
$jsonData = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer $apiKey",
"Content-Type: application/json"
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode == 200) {
echo "Response: " . $response;
} else {
echo "Error: " . $httpCode . " - " . $response;
}
curl_close($ch);
?>
DashScope 未提供 Node.js 环境的 SDK。如需通过 OpenAI Node.js SDK调用,请参考本文的OpenAI 兼容章节。
import fetch from 'node-fetch';
// 若没有配置环境变量,请用您子业务空间的百炼API Key将下行替换为:apiKey = "sk-xxx";
const apiKey = process.env.DASHSCOPE_API_KEY;
const data = {
// 下方模型以qwen-plus为例,可按需更换模型名称(标准模型须完成模型授权)。标准模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
// 在百炼调优后的模型,无需模型授权,请更换为部署成功后的model名称。如何获取,详见模型部署:https://help.aliyun.com/zh/model-studio/user-guide/model-deployment
model: "qwen-plus",
input: {
messages: [
{
role: "system",
content: "You are a helpful assistant."
},
{
role: "user",
content: "你是谁?"
}
]
},
parameters: {
result_format: "message"
}
};
fetch('https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => {
console.log(JSON.stringify(data));
})
.catch(error => {
console.error('Error:', error);
});
using System.Net.Http.Headers;
using System.Text;
class Program
{
private static readonly HttpClient httpClient = new HttpClient();
static async Task Main(string[] args)
{
// 若没有配置环境变量,请用您子业务空间的百炼API Key将下行替换为:string? apiKey = "sk-xxx";
string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("API Key 未设置。请确保环境变量 'DASHSCOPE_API_KEY' 已设置。");
return;
}
// 设置请求 URL 和内容
string url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
// 下方模型以qwen-plus为例,可按需更换模型名称(标准模型须完成模型授权)。标准模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
// 在百炼调优后的模型,无需模型授权,请更换为部署成功后的model名称。如何获取,详见模型部署:https://help.aliyun.com/zh/model-studio/user-guide/model-deployment
string jsonContent = @"{
""model"": ""qwen-plus"",
""input"": {
""messages"": [
{
""role"": ""system"",
""content"": ""You are a helpful assistant.""
},
{
""role"": ""user"",
""content"": ""你是谁?""
}
]
},
""parameters"": {
""result_format"": ""message""
}
}";
// 发送请求并获取响应
string result = await SendPostRequestAsync(url, jsonContent, apiKey);
// 输出结果
Console.WriteLine(result);
}
private static async Task<string> SendPostRequestAsync(string url, string jsonContent, string apiKey)
{
using (var content = new StringContent(jsonContent, Encoding.UTF8, "application/json"))
{
// 设置请求头
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// 发送请求并获取响应
HttpResponseMessage response = await httpClient.PostAsync(url, content);
// 处理响应
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
else
{
return $"请求失败: {response.StatusCode}";
}
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
)
type Message struct {
Role string `json:"role"`
Content string `json:"content"`
}
type Input struct {
Messages []Message `json:"messages"`
}
type Parameters struct {
ResultFormat string `json:"result_format"`
}
type RequestBody struct {
Model string `json:"model"`
Input Input `json:"input"`
Parameters Parameters `json:"parameters"`
}
func main() {
// 创建 HTTP 客户端
client := &http.Client{}
// 构建请求体
requestBody := RequestBody{
// 下方模型以qwen-plus为例,可按需更换模型名称(标准模型须完成模型授权)。标准模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
// 在百炼调优后的模型,无需模型授权,请更换为部署成功后的model名称。如何获取,详见模型部署:https://help.aliyun.com/zh/model-studio/user-guide/model-deployment
Model: "qwen-plus",
Input: Input{
Messages: []Message{
{
Role: "system",
Content: "You are a helpful assistant.",
},
{
Role: "user",
Content: "你是谁?",
},
},
},
Parameters: Parameters{
ResultFormat: "message",
},
}
jsonData, err := json.Marshal(requestBody)
if err != nil {
log.Fatal(err)
}
// 创建 POST 请求
req, err := http.NewRequest("POST", "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation", bytes.NewBuffer(jsonData))
if err != nil {
log.Fatal(err)
}
// 设置请求头
// 若没有配置环境变量,请用您子业务空间的百炼API Key将下行替换为:apiKey := "sk-xxx"
apiKey := os.Getenv("DASHSCOPE_API_KEY")
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// 发送请求
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
// 读取响应体
bodyText, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
// 打印响应内容
fmt.Printf("%s\n", bodyText)
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import com.google.gson.Gson;
public class Main {
static class Message {
String role;
String content;
public Message(String role, String content) {
this.role = role;
this.content = content;
}
}
static class Input {
Message[] messages;
public Input(Message[] messages) {
this.messages = messages;
}
}
static class Parameters {
String result_format;
public Parameters(String result_format) {
this.result_format = result_format;
}
}
static class RequestBody {
String model;
Input input;
Parameters parameters;
public RequestBody(String model, Input input, Parameters parameters) {
this.model = model;
this.input = input;
this.parameters = parameters;
}
}
public static void main(String[] args) {
try {
// 创建请求体
RequestBody requestBody = new RequestBody(
// 下方模型以qwen-plus为例,可按需更换模型名称(标准模型须完成模型授权)。标准模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
// 在百炼调优后的模型,无需模型授权,请更换为部署成功后的model名称。如何获取,详见模型部署:https://help.aliyun.com/zh/model-studio/user-guide/model-deployment
"qwen-plus",
new Input(new Message[] {
new Message("system", "You are a helpful assistant."),
new Message("user", "你是谁?")
}),
new Parameters("message")
);
// 将请求体转换为 JSON
Gson gson = new Gson();
String jsonInputString = gson.toJson(requestBody);
// 创建 URL 对象
URL url = new URL("https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
// 设置请求方法为 POST
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/json; utf-8");
httpURLConnection.setRequestProperty("Accept", "application/json");
// 若没有配置环境变量,请用您子业务空间的百炼API Key将下行替换为:String apiKey = "sk-xxx";
String apiKey = System.getenv("DASHSCOPE_API_KEY");
String auth = "Bearer " + apiKey;
httpURLConnection.setRequestProperty("Authorization", auth);
// 启用输入输出流
httpURLConnection.setDoOutput(true);
// 写入请求体
try (OutputStream os = httpURLConnection.getOutputStream()) {
byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
// 读取响应体
try (BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder response = new StringBuilder();
String responseLine;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
System.exit(0);
}
}
}
错误码
HTTP 返回码 | 错误代码 Code | 错误信息 Message | 说明 |
HTTP 返回码 | 错误代码 Code | 错误信息 Message | 说明 |
400 | InvalidParameter | Model not exist. | 您传入的模型名称不正确。 |
401 | InvalidApiKey | Invalid API-key provided. Incorrect API key provided. | 您传入的API Key不正确。 |
invalid_api_key | |||
403 | Model.AccessDenied | Model access denied. | 无权限调用对应的模型。 子业务空间的API Key能否调用某个模型(例如本文示例使用通义千问-Plus模型)取决于该业务空间是否具有此模型的调用权限。授权方法请参见调用前准备:模型授权。 |
404 | ModelNotFound | Model can not be found. The model xx does not exist or you do not have access to it. | 您传入的模型名称不正确。 |
model_not_found | |||
- | NoPermission | You are not authorized to do this operation. Action: sfm:CreateSession;Resource: acs:sfm::xxx:* (1-1). | 请使用主账号在RAM控制台中为您的子账号配置 |
- | - | openai.OpenAIError: The api_key client option must be set either by passing api_key to the client or by setting the OPENAI_API_KEY environment variable. | 您未传入API Key。您可以参考配置API Key到环境变量将 API Key 正确配置到环境变量,或将 API Key 作为明文写入代码中(不建议)。 |
- | - | AuthenticationError: No api key provided. You can set by dashscope.api_key = your_api_key in code, or you can set it via environment variable DASHSCOPE_API_KEY= your_api_key. |
常见问题
如何查看您所有的业务空间?
您可在百炼控制台左上角查看和切换已授权的业务空间。了解业务空间的授权步骤。
如果您同时是“默认业务空间”和“子业务空间”的成员
如果您是“子业务空间”的成员,而非“默认业务空间”的成员
如果您同时是“默认业务空间”和“子业务空间”的成员
如果您是“子业务空间”的成员,而非“默认业务空间”的成员
下一步
查看更多模型 | 示例代码以通义千问-Plus模型为例,百炼还支持其他通义千问模型与 DeepSeek、Llama 等第三方模型,支持的模型以及对应的API参考文档请参见模型列表。 |
了解进阶用法 | 示例代码仅完成了简单问答,如果您想了解通义千问 API 的更多用法,如流式输出(Stream)、结构化输出(JSON Mode)、工具调用(Function Call)等,请参见文本生成目录。 |
- 本页导读 (1)
- 适用场景
- 调用前准备
- 开始调用
- OpenAI 兼容
- DashScope
- 错误码
- 常见问题
- 下一步