百鍊支援通過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}";
}
}
}
}