百炼支持通过API调用大模型,涵盖OpenAI兼容接口、DashScope SDK等接入方式。
本文以通义千问为例,引导您完成大模型API调用。您将了解到:
如何获取API Key
如何配置本地开发环境
如何调用通义千问API
账号设置
注册账号:如果没有阿里云账号,您需要先注册阿里云账号。
开通百炼:前往百炼控制台,开通百炼的模型服务,以获得免费额度。
获取API Key:在控制台的右上角选择API-KEY,然后创建API Key,用于通过API调用大模型。
配置API Key到环境变量
建议您把API Key配置到环境变量,从而避免在代码里显式地配置API Key,降低泄漏风险。
选择开发语言
选择您熟悉的语言或工具,用于调用大模型API。
Python
步骤 1:配置Python环境
检查您的Python版本
配置虚拟环境(可选)
安装模型调用SDK
步骤 2:调用大模型API
OpenAI Python SDK
如果您安装完成了Python以及OpenAI的Python SDK,可以参考以下代码发送您的API请求。您可以新建一个python文件,命名为hello_qwen.py
,将以下代码复制到hello_qwen.py
中并保存。
import os
from openai import OpenAI
try:
client = OpenAI(
# 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen-plus", # 模型列表:https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
messages=[
{'role': 'system', 'content': 'You are a helpful assistant.'},
{'role': 'user', 'content': '你是谁?'}
]
)
print(completion.choices[0].message.content)
except Exception as e:
print(f"错误信息:{e}")
print("请参考文档:https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code")
复制完成后,您可以通过命令行运行python hello_qwen.py
或python3 hello_qwen.py
。运行后您将会看到输出结果:
我是阿里云开发的一款超大规模语言模型,我叫通义千问。
DashScope Python SDK
如果您安装完成了Python以及DashScope的Python SDK,可以参考以下代码发送您的API请求。您可以新建一个Python文件,命名为hello_qwen.py
,将以下代码复制到hello_qwen.py
中并保存。
import os
from dashscope import Generation
import dashscope
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
messages = [
{'role': 'system', 'content': 'You are a helpful assistant.'},
{'role': 'user', 'content': '你是谁?'}
]
response = Generation.call(
# 若没有配置环境变量,请用百炼API Key将下行替换为:api_key = "sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="qwen-plus", # 模型列表:https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
messages=messages,
result_format="message"
)
if response.status_code == 200:
print(response.output.choices[0].message.content)
else:
print(f"HTTP返回码:{response.status_code}")
print(f"错误码:{response.code}")
print(f"错误信息:{response.message}")
print("请参考文档:https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code")
复制完成后,您可以通过命令python hello_qwen.py
运行。运行成功后您可以看到对应的输出结果:
我是阿里云开发的一款超大规模语言模型,我叫通义千问。
如果运行失败,您可以将python替换成python3再运行。
Node.js
步骤 1:配置Node.js环境
检查Node.js安装状态
安装模型调用SDK
步骤 2:调用大模型API
您可以新建一个hello_qwen.mjs
文件,将以下代码复制到文件中。
import OpenAI from "openai";
try {
const openai = new OpenAI(
{
// 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey: "sk-xxx",
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
}
);
const completion = await openai.chat.completions.create({
model: "qwen-plus", //模型列表:https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
messages: [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "你是谁?" }
],
});
console.log(completion.choices[0].message.content);
} catch (error) {
console.log(`错误信息:${error}`);
console.log("请参考文档:https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code");
}
您可以通过命令行运行以下命令来发送API请求:
node hello_qwen.mjs
运行成功后您将会看到输出结果:
我是阿里云开发的一款超大规模语言模型,我叫通义千问。
Java
步骤 1:配置Java环境
检查您的Java版本
安装模型调用SDK
步骤 2:调用大模型API
您可以运行以下代码来调用大模型API。
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.protocol.Protocol;
public class Main {
public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-intl.aliyuncs.com/api/v1");
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"))
// 模型列表:https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
.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(result.getOutput().getChoices().get(0).getMessage().getContent());
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.err.println("错误信息:"+e.getMessage());
System.out.println("请参考文档:https://www.alibabacloud.com/help/zh/model-studio/developer-reference/error-code");
}
System.exit(0);
}
}
运行后您将会看到对应的输出结果:
我是阿里云开发的一款超大规模语言模型,我叫通义千问。
curl
您可以通过OpenAI兼容的HTTP方式或DashScope的HTTP方式来调用百炼平台上的模型。模型列表请参考:模型列表。
若没有配置环境变量,请用百炼API Key将:-H "Authorization: Bearer $DASHSCOPE_API_KEY" \ 换为:-H "Authorization: Bearer sk-xxx" \ 。
OpenAI兼容-HTTP
您可以运行以下命令发送API请求:
curl -X POST https://dashscope-intl.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": "你是谁?"
}
]
}'
发送API请求后,可以得到以下回复:
{
"choices": [
{
"message": {
"role": "assistant",
"content": "我是来自阿里云的大规模语言模型,我叫通义千问。"
},
"finish_reason": "stop",
"index": 0,
"logprobs": null
}
],
"object": "chat.completion",
"usage": {
"prompt_tokens": 22,
"completion_tokens": 16,
"total_tokens": 38
},
"created": 1728353155,
"system_fingerprint": null,
"model": "qwen-plus",
"id": "chatcmpl-39799876-eda8-9527-9e14-2214d641cf9a"
}
DashScope-HTTP
您可以运行以下命令发送API请求:
curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-plus",
"input":{
"messages":[
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "你是谁?"
}
]
},
"parameters": {
"result_format":"message"
}
}'
发送API请求后,可以得到以下回复:
{
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": "我是来自阿里云的大规模语言模型,我叫通义千问。"
}
}
]
},
"usage": {
"total_tokens": 38,
"output_tokens": 16,
"input_tokens": 22
},
"request_id": "87f776d7-3c82-9d39-b238-d1ad38c9b6a9"
}
其它语言
调用大模型API
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{
// 模型列表:https://www.alibabacloud.com/help/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-intl.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)
}
<?php
$url = 'https://dashscope-intl.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 = [
// 模型列表:https://www.alibabacloud.com/help/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_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;
}
string url = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions";
// 模型列表:https://www.alibabacloud.com/help/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}";
}
}
}
}