文本產生模型能夠基於輸入的提示詞(Prompt)創作出邏輯清晰、連貫的文本。
文本產生模型所需的輸入可以是簡單的關鍵詞、一句話概述或是更複雜的指令和上下文資訊。模型通過分析海量資料學習語言模式,廣泛應用於:
內容創作:產生新聞報道、商品介紹及短視頻指令碼。
客戶服務:驅動聊天機器人提供全天候支援,解答常見問題。
文本翻譯:實現跨語言的快速精準轉換。
摘要產生:提煉長文、報告及郵件的核心內容。
法律文檔編寫:產生合約範本、法律意見書的基礎架構。
模型選型建議
服務地區
通用模型
通義千問Max、通義千問Plus 和通義千問Flash 均已升級至Qwen3系列,併兼容OpenAI調用方式,適用於智能客服、文本創作、內容潤色以及摘要總結等多種情境。
特定情境模型
針對明確的業務需求,阿里雲百鍊提供多種專用最佳化模型,覆蓋代碼能力、長上下文、翻譯、資料採礦、意圖理解、角色扮演、深入研究等領域。
多模態模型
第三方模型
阿里雲百鍊提供了包括 DeepSeek、Kimi等知名第三方大語言模型,完整模型列表請參考 文本產生-第三方模型。
核心概念
文本產生模型的輸入為提示詞(Prompt),它由一個或多個訊息(Message)對象構成。每條訊息由角色(Role)和內容(Content)組成,具體為:
系統訊息(System Message):設定模型扮演的角色或遵循的指令。若不指定,預設為"You are a helpful assistant"。
使用者訊息(User Message):使用者向模型提出的問題或輸入的指令。
助手訊息(Assistant Message):模型的回複內容。
調用模型時,需構造一個由上述訊息對象構成的數組messages。一個典型的請求通常由一條定義管理辦法的 system 訊息和一條使用者提指令的 user 訊息組成。
system訊息是可選的,但建議使用它來設定模型的角色和管理辦法,以獲得更穩定、一致的輸出。[
{"role": "system", "content": "你是一個有協助的助手,需要提供精準、高效且富有洞察力的回應,隨時準備協助使用者處理各種任務與問題。"},
{"role": "user", "content": "你是誰?"}
]輸出的響應對象中會包含模型回複的assistant訊息。
{
"role": "assistant",
"content": "你好!我是Qwen,是阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我可以協助你回答問題、創作文字、進行邏輯推理、編程等。我能夠理解並產生多種語言,支援多輪對話和複雜任務處理。如果你有任何需要協助的地方,儘管告訴我!"
}快速開始
API 使用前提:已擷取與配置 API Key並完成配置API Key到環境變數(準備下線,併入配置 API Key)。如果通過SDK調用,需要安裝 OpenAI 或 DashScope SDK。
運行下方代碼,開始與 qwen-plus 模型對話。如需獲得更高品質的產生結果,可參考深度思考。
OpenAI相容
Python
import os
from openai import OpenAI
try:
client = OpenAI(
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
# 模型列表:https://www.alibabacloud.com/help/zh/model-studio/models
model="qwen-plus",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "你是誰?"},
],
)
print(completion.choices[0].message.content)
# 如需查看完整響應,請取消下列注釋
# print(completion.model_dump_json())
except Exception as e:
print(f"錯誤資訊:{e}")
print("請參考文檔:https://www.alibabacloud.com/help/zh/model-studio/error-code")返回結果
我是通義千問,阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我可以協助你回答問題、創作文字,比如寫故事、寫公文、寫郵件、寫劇本、邏輯推理、編程等等,還能表達觀點,玩遊戲等。如果你有任何問題或需要協助,歡迎隨時告訴我!Java
// 建議 OpenAI Java SDK版本 >= 3.5.0
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.ChatCompletion;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
public class Main {
public static void main(String[] args) {
try {
OpenAIClient client = OpenAIOkHttpClient.builder()
// 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為.apiKey("sk-xxx")
// 新加坡地區和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// 以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
.baseUrl("https://dashscope-intl.aliyuncs.com/compatible-mode/v1")
.build();
// 建立 ChatCompletion 參數
ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
.model("qwen-plus") // 指定模型
.addSystemMessage("You are a helpful assistant.")
.addUserMessage("你是誰?")
.build();
// 發送請求並擷取響應
ChatCompletion chatCompletion = client.chat().completions().create(params);
String content = chatCompletion.choices().get(0).message().content().orElse("未返回有效內容");
System.out.println(content);
} catch (Exception e) {
System.err.println("錯誤資訊:" + e.getMessage());
System.out.println("請參考文檔:https://www.alibabacloud.com/help/zh/model-studio/error-code");
}
}
}返回結果
我是通義千問,阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我可以協助你回答問題、創作文字,比如寫故事、寫公文、寫郵件、寫劇本、邏輯推理、編程等等,還能表達觀點,玩遊戲等。如果你有任何問題或需要協助,歡迎隨時告訴我!Node.js
// 需要 Node.js v18+,需在 ES Module 環境下運行
import OpenAI from "openai";
const openai = new OpenAI(
{
// 新加坡地區和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:apiKey: "sk-xxx",
apiKey: process.env.DASHSCOPE_API_KEY,
// 以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
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/models
messages: [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "你是誰?" }
],
});
console.log(completion.choices[0].message.content);
// 如需查看完整響應,請取消下列注釋
// console.log(JSON.stringify(completion, null, 4));返回結果
我是通義千問,阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我可以協助你回答問題、創作文字,比如寫故事、寫公文、寫郵件、寫劇本、邏輯推理、編程等等,還能表達觀點,玩遊戲等。如果你有任何問題或需要協助,歡迎隨時告訴我!Go
// OpenAI Go SDK版本不低於 v2.4.0
package main
import (
"context"
// 如需查看完整響應,請取消下方及代碼末尾的注釋
// "encoding/json"
"fmt"
"os"
"github.com/openai/openai-go/v2"
"github.com/openai/openai-go/v2/option"
)
func main() {
// 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:apiKey := "sk-xxx"
apiKey := os.Getenv("DASHSCOPE_API_KEY")
client := openai.NewClient(
option.WithAPIKey(apiKey),
// 新加坡地區和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// 以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
option.WithBaseURL("https://dashscope-intl.aliyuncs.com/compatible-mode/v1"),
)
chatCompletion, err := client.Chat.Completions.New(
context.TODO(), openai.ChatCompletionNewParams{
Messages: []openai.ChatCompletionMessageParamUnion{
openai.SystemMessage("You are a helpful assistant."),
openai.UserMessage("你是誰?"),
},
Model: "qwen-plus",
},
)
if err != nil {
fmt.Fprintf(os.Stderr, "請求失敗: %v\n", err)
// 更多錯誤資訊,請參考文檔:https://www.alibabacloud.com/help/zh/model-studio/error-code
os.Exit(1)
}
if len(chatCompletion.Choices) > 0 {
fmt.Println(chatCompletion.Choices[0].Message.Content)
}
// 如需查看完整響應,請取消下列注釋
// jsonData, _ := json.MarshalIndent(chatCompletion, "", " ")
// fmt.Println(string(jsonData))
}
返回結果
我是通義千問,阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我可以協助你回答問題、創作文字,比如寫故事、寫公文、寫郵件、寫劇本、邏輯推理、編程等等,還能表達觀點,玩遊戲等。如果你有任何問題或需要協助,歡迎隨時告訴我!C#(HTTP)
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
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");
// 以下為新加坡地區base_url,如果使用北京地區的模型,需要將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
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);
// 解析JSON並只輸出content部分
using JsonDocument doc = JsonDocument.Parse(result);
JsonElement root = doc.RootElement;
if (root.TryGetProperty("choices", out JsonElement choices) &&
choices.GetArrayLength() > 0)
{
JsonElement firstChoice = choices[0];
if (firstChoice.TryGetProperty("message", out JsonElement message) &&
message.TryGetProperty("content", out JsonElement content))
{
Console.WriteLine(content.GetString());
}
}
}
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
{
// 更多錯誤資訊,請參考文檔:https://www.alibabacloud.com/help/zh/model-studio/error-code
return $"請求失敗: {response.StatusCode}";
}
}
}
}返回結果
我是通義千問,阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我可以協助你回答問題、創作文字,比如寫故事、寫公文、寫郵件、寫劇本、邏輯推理、編程等等,還能表達觀點,玩遊戲等。如果你有任何問題或需要協助,歡迎隨時告訴我!PHP(HTTP)
<?php
// 佈建要求的URL
// 以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
$url = 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions';
// 新加坡地區和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:$apiKey = "sk-xxx";
$apiKey = getenv('DASHSCOPE_API_KEY');
// 佈建要求頭
$headers = [
'Authorization: Bearer '.$apiKey,
'Content-Type: application/json'
];
// 佈建要求體
$data = [
"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);
// 檢查是否有錯誤發生
// 更多錯誤資訊,請參考文檔:https://www.alibabacloud.com/help/zh/model-studio/error-code
if (curl_errno($ch)) {
echo 'Curl error: ' . curl_error($ch);
}
// 關閉cURL資源
curl_close($ch);
// 輸出響應結果
$dataObject = json_decode($response);
$content = $dataObject->choices[0]->message->content;
echo $content;
// 如需查看完整響應,請取消下列注釋
//echo $response;
?>返回結果
我是通義千問,阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我可以協助你回答問題、創作文字,比如寫故事、寫公文、寫郵件、寫劇本、邏輯推理、編程等等,還能表達觀點,玩遊戲等。如果你有任何問題或需要協助,歡迎隨時告訴我!curl
以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
新加坡地區和北京地區的API Key不同,請參見 擷取與配置 API Key。
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": "你是誰?"
}
]
}'返回結果
{
"choices": [
{
"message": {
"role": "assistant",
"content": "我是通義千問,阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我可以協助你回答問題、創作文字,比如寫故事、寫公文、寫郵件、寫劇本、邏輯推理、編程等等,還能表達觀點,玩遊戲等。如果你有任何問題或需要協助,歡迎隨時告訴我!"
},
"finish_reason": "stop",
"index": 0,
"logprobs": null
}
],
"object": "chat.completion",
"usage": {
"prompt_tokens": 26,
"completion_tokens": 66,
"total_tokens": 92
},
"created": 1726127645,
"system_fingerprint": null,
"model": "qwen-plus",
"id": "chatcmpl-81951b98-28b8-9659-ab07-xxxxxx"
}DashScope
Python
import json
import os
from dashscope import Generation
import dashscope
# 以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/api/v1
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:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:api_key = "sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="qwen-plus",
messages=messages,
result_format="message",
)
if response.status_code == 200:
print(response.output.choices[0].message.content)
# 如需查看完整響應,請取消下列注釋
# print(json.dumps(response, default=lambda o: o.__dict__, indent=4))
else:
print(f"HTTP返回碼:{response.status_code}")
print(f"錯誤碼:{response.code}")
print(f"錯誤資訊:{response.message}")
print("請參考文檔:https://www.alibabacloud.com/help/zh/model-studio/error-code")返回結果
我是通義千問,阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我可以協助你回答問題、創作文字,比如寫故事、寫公文、寫郵件、寫劇本、邏輯推理、編程等等,還能表達觀點,玩遊戲等。如果你有任何問題或需要協助,歡迎隨時告訴我!Java
// 建議 DashScope Java SDK版本 >= 2.20.6
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;
import com.alibaba.dashscope.utils.JsonUtils;
public class Main {
public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
// 以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/api/v1
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不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:.apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.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());
// 如需查看完整響應,請取消下列注釋
// System.out.println(JsonUtils.toJson(result));
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.err.println("錯誤資訊:"+e.getMessage());
System.out.println("請參考文檔:https://www.alibabacloud.com/help/zh/model-studio/error-code");
}
}
}返回結果
我是通義千問,阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我可以協助你回答問題、創作文字,比如寫故事、寫公文、寫郵件、寫劇本、邏輯推理、編程等等,還能表達觀點,玩遊戲等。如果你有任何問題或需要協助,歡迎隨時告訴我!Node.js(HTTP)
// 需要 Node.js v18+
// 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:const apiKey = "sk-xxx";
const apiKey = process.env.DASHSCOPE_API_KEY;
const data = {
model: "qwen-plus",
input: {
messages: [
{
role: "system",
content: "You are a helpful assistant."
},
{
role: "user",
content: "你是誰?"
}
]
},
parameters: {
result_format: "message"
}
};
async function callApi() {
try {
// 以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
const response = await fetch('https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
const result = await response.json();
console.log(result.output.choices[0].message.content);
// 如需查看完整響應,請取消下列注釋
// console.log(JSON.stringify(result));
} catch (error) {
// 更多錯誤資訊,請參考文檔:https://www.alibabacloud.com/help/zh/model-studio/error-code
console.error('調用失敗:', error.message);
}
}
callApi();返回結果
我是通義千問,阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我可以協助你回答問題、創作文字,比如寫故事、寫公文、寫郵件、寫劇本、邏輯推理、編程等等,還能表達觀點,玩遊戲等。如果你有任何問題或需要協助,歡迎隨時告訴我!Go(HTTP)
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
)
func main() {
requestBody := map[string]interface{}{
"model": "qwen-plus",
"input": map[string]interface{}{
"messages": []map[string]string{
{
"role": "system",
"content": "You are a helpful assistant.",
},
{
"role": "user",
"content": "你是誰?",
},
},
},
"parameters": map[string]string{
"result_format": "message",
},
}
// 序列化為 JSON
jsonData, _ := json.Marshal(requestBody)
// 建立 HTTP 用戶端和請求
client := &http.Client{}
// 以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
req, _ := http.NewRequest("POST", "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation", bytes.NewBuffer(jsonData))
// 佈建要求頭
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, _ := io.ReadAll(resp.Body)
// 解析JSON並輸出content內容
var result map[string]interface{}
json.Unmarshal(bodyText, &result)
content := result["output"].(map[string]interface{})["choices"].([]interface{})[0].(map[string]interface{})["message"].(map[string]interface{})["content"].(string)
fmt.Println(content)
// 如需查看完整響應,請取消下列注釋
// fmt.Printf("%s\n", bodyText)
}
返回結果
我是通義千問,阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我可以協助你回答問題、創作文字,比如寫故事、寫公文、寫郵件、寫劇本、邏輯推理、編程等等,還能表達觀點,玩遊戲等。如果你有任何問題或需要協助,歡迎隨時告訴我!C#(HTTP)
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不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:string? apiKey = "sk-xxx";
string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
// 佈建要求 URL 和內容
// 以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
string url = "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
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);
var jsonResult = System.Text.Json.JsonDocument.Parse(result);
var content = jsonResult.RootElement.GetProperty("output").GetProperty("choices")[0].GetProperty("message").GetProperty("content").GetString();
Console.WriteLine(content);
// 如需查看完整響應,請取消下列注釋
// 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}";
}
}
}
}返回結果
{
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": "我是通義千問,阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我可以協助你回答問題、創作文字,比如寫故事、寫公文、寫郵件、寫劇本、邏輯推理、編程等等,還能表達觀點,玩遊戲等。如果你有任何問題或需要協助,歡迎隨時告訴我!"
}
}
]
},
"usage": {
"total_tokens": 92,
"output_tokens": 66,
"input_tokens": 26
},
"request_id": "09dceb20-ae2e-999b-85f9-xxxxxx"
}PHP(HTTP)
<?php
// 以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
$url = "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
// 新加坡地區和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
$apiKey = getenv('DASHSCOPE_API_KEY');
$data = [
"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_HTTPHEADER, [
"Authorization: Bearer $apiKey",
"Content-Type: application/json"
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode == 200) {
$jsonResult = json_decode($response, true);
$content = $jsonResult['output']['choices'][0]['message']['content'];
echo $content;
// 如需查看完整響應,請取消下列注釋
// echo "模型響應: " . $response;
} else {
echo "請求錯誤: " . $httpCode . " - " . $response;
}
curl_close($ch);
?>返回結果
我是通義千問,阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我可以協助你回答問題、創作文字,比如寫故事、寫公文、寫郵件、寫劇本、邏輯推理、編程等等,還能表達觀點,玩遊戲等。如果你有任何問題或需要協助,歡迎隨時告訴我!curl
以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
新加坡地區和北京地區的API Key不同,請參見 擷取與配置 API Key。
curl --location "https://dashscope-intl.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"
}
}'返回結果
{
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": "我是通義千問,阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我可以協助你回答問題、創作文字,比如寫故事、寫公文、寫郵件、寫劇本、邏輯推理、編程等等,還能表達觀點,玩遊戲等。如果你有任何問題或需要協助,歡迎隨時告訴我!"
}
}
]
},
"usage": {
"total_tokens": 92,
"output_tokens": 66,
"input_tokens": 26
},
"request_id": "09dceb20-ae2e-999b-85f9-xxxxxx"
}映像、視頻資料處理
多模態模型支援處理映像、視頻等非文本資料,可用於視覺問答、事件檢測等任務。其調用方式與純文字模型主要有以下不同:
使用者訊息(user message)的構造方式:多模態模型的使用者訊息不僅包含文本,還包含圖片、音頻等多模態資訊。
DashScope SDK介面:使用 DashScope Python SDK 時,需調用
MultiModalConversation介面;使用DashScope Java SDK 時,需調用MultiModalConversation類。
圖片、視頻檔案限制請參見視覺理解。
OpenAI相容
Python
from openai import OpenAI
import os
client = OpenAI(
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
)
messages = [
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251031/ownrof/f26d201b1e3f4e62ab4a1fc82dd5c9bb.png"
},
},
{"type": "text", "text": "請問圖片展現了有哪些商品?"},
],
}
]
completion = client.chat.completions.create(
model="qwen3-vl-plus", # 可按需更換為其它多模態模型,並修改相應的 messages
messages=messages,
)
print(completion.choices[0].message.content)
Node.js
import OpenAI from "openai";
const openai = new OpenAI(
{
// 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// 若沒有配置環境變數,請用百鍊API Key將下行替換為:apiKey: "sk-xxx",
apiKey: process.env.DASHSCOPE_API_KEY,
// 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
}
);
let messages = [
{
role: "user",
content: [
{ type: "image_url", image_url: { "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251031/ownrof/f26d201b1e3f4e62ab4a1fc82dd5c9bb.png" } },
{ type: "text", text: "請問圖片展現了有哪些商品?" },
]
}]
async function main() {
let response = await openai.chat.completions.create({
model: "qwen3-vl-plus", // 可按需更換為其它多模態模型,並修改相應的 messages
messages: messages
});
console.log(response.choices[0].message.content);
}
main()curl
以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
新加坡地區和北京地區的API Key不同,請參見 擷取與配置 API Key。
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": "qwen3-vl-plus",
"messages": [
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251031/ownrof/f26d201b1e3f4e62ab4a1fc82dd5c9bb.png"
}
},
{
"type": "text",
"text": "請問圖片展現了有哪些商品?"
}
]
}
]
}'DashScope
Python
import os
from dashscope import MultiModalConversation
import dashscope
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
messages = [
{
"role": "user",
"content": [
{
"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251031/ownrof/f26d201b1e3f4e62ab4a1fc82dd5c9bb.png"
},
{"text": "請問圖片展現了有哪些商品?"},
],
}
]
response = MultiModalConversation.call(
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx",
api_key=os.getenv('DASHSCOPE_API_KEY'),
model='qwen3-vl-plus', # 可按需更換為其它多模態模型,並修改相應的 messages
messages=messages
)
print(response.output.choices[0].message.content[0]['text'])
Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
// 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1
Constants.baseHttpApiUrl = "https://dashscope-intl.aliyuncs.com/api/v1";
}
private static final String modelName = "qwen3-vl-plus"; // 可按需更換為其它多模態模型,並修改相應的 messages
public static void MultiRoundConversationCall() throws ApiException, NoApiKeyException, UploadFileException {
MultiModalConversation conv = new MultiModalConversation();
MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
.content(Arrays.asList(Collections.singletonMap("image", "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251031/ownrof/f26d201b1e3f4e62ab4a1fc82dd5c9bb.png"),
Collections.singletonMap("text", "請問圖片展現了有哪些商品?"))).build();
List<MultiModalMessage> messages = new ArrayList<>();
messages.add(userMessage);
MultiModalConversationParam param = MultiModalConversationParam.builder()
// 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// 若沒有配置環境變數,請用百鍊API Key將下行替換為:.apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model(modelName)
.messages(messages)
.build();
MultiModalConversationResult result = conv.call(param);
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text")); // add the result to conversation
}
public static void main(String[] args) {
try {
MultiRoundConversationCall();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}curl
以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
新加坡地區和北京地區的API Key不同,請參見 擷取與配置 API Key。
curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen3-vl-plus",
"input":{
"messages":[
{
"role": "user",
"content": [
{"image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251031/ownrof/f26d201b1e3f4e62ab4a1fc82dd5c9bb.png"},
{"text": "請問圖片展現了有哪些商品?"}
]
}
]
}
}'非同步呼叫模型
調用非同步介面,可有效提升高並發請求的處理效率。
OpenAI相容
Python
import os
import asyncio
from openai import AsyncOpenAI
import platform
# 建立非同步用戶端執行個體
client = AsyncOpenAI(
# 新加坡地區和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
)
# 定義非同步工作清單
async def task(question):
print(f"發送問題: {question}")
response = await client.chat.completions.create(
messages=[
{"role": "user", "content": question}
],
model="qwen-plus", # 模型列表:https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
)
print(f"模型回複: {response.choices[0].message.content}")
# 主非同步函數
async def main():
questions = ["你是誰?", "你會什嗎?", "天氣怎麼樣?"]
tasks = [task(q) for q in questions]
await asyncio.gather(*tasks)
if __name__ == '__main__':
# 設定事件迴圈策略
if platform.system() == 'Windows':
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
# 運行主協程
asyncio.run(main(), debug=False)
Java
import com.openai.client.OpenAIClientAsync;
import com.openai.client.okhttp.OpenAIOkHttpClientAsync;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) {
// 建立 OpenAI 用戶端,串連 DashScope 的相容介面
OpenAIClientAsync client = OpenAIOkHttpClientAsync.builder()
// 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為.apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// 以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
.baseUrl("https://dashscope-intl.aliyuncs.com/compatible-mode/v1")
.build();
// 定義問題列表
List<String> questions = Arrays.asList("你是誰?", "你會什嗎?", "天氣怎麼樣?");
// 建立非同步工作清單
CompletableFuture<?>[] futures = questions.stream()
.map(question -> CompletableFuture.supplyAsync(() -> {
System.out.println("發送問題: " + question);
// 建立 ChatCompletion 參數
ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
.model("qwen-plus") // 指定模型
.addSystemMessage("You are a helpful assistant.")
.addUserMessage(question)
.build();
// 發送非同步請求並處理響應
return client.chat().completions().create(params)
.thenAccept(chatCompletion -> {
String content = chatCompletion.choices().get(0).message().content().orElse("無響應內容");
System.out.println("模型回複: " + content);
})
.exceptionally(e -> {
System.err.println("錯誤資訊:" + e.getMessage());
System.out.println("請參考文檔:https://www.alibabacloud.com/help/zh/model-studio/error-code");
return null;
});
}).thenCompose(future -> future))
.toArray(CompletableFuture[]::new);
// 等待所有非同步作業完成
CompletableFuture.allOf(futures).join();
}
}DashScope
DashScope SDK的文本產生非同步呼叫,目前僅支援Python。
# DashScope Python SDK版本需要不低於 1.19.0
import asyncio
import platform
from dashscope.aigc.generation import AioGeneration
import os
import dashscope
# 以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
# 定義非同步工作清單
async def task(question):
print(f"發送問題: {question}")
response = await AioGeneration.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/models
messages=[{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": question}],
result_format="message",
)
print(f"模型回複: {response.output.choices[0].message.content}")
# 主非同步函數
async def main():
questions = ["你是誰?", "你會什嗎?", "天氣怎麼樣?"]
tasks = [task(q) for q in questions]
await asyncio.gather(*tasks)
if __name__ == '__main__':
# 設定事件迴圈策略
if platform.system() == 'Windows':
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
# 運行主協程
asyncio.run(main(), debug=False)
返回結果
由於調用是非同步,響應的返回順序可能與樣本不同。
發送問題: 你是誰?
發送問題: 你會什嗎?
發送問題: 天氣怎麼樣?
模型回複: 你好!我是通義千問,阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我可以協助你回答問題、創作文字,比如寫故事、寫公文、寫郵件、寫劇本、邏輯推理、編程等等,還能表達觀點,玩遊戲等。如果你有任何問題或需要協助,歡迎隨時告訴我!
模型回複: 您好!我目前無法即時擷取天氣資訊。您可以告訴我您所在的城市或地區,我會儘力為您提供一些通用的天氣建議或資訊。或者您也可以使用天氣應用查看即時天氣情況。
模型回複: 我會很多技能,比如:
1. **回答問題**:無論是學術問題、生活常識還是專業知識,我都可以嘗試幫你解答。
2. **創作文字**:我可以寫故事、公文、郵件、劇本等各類文本。
3. **邏輯推理**:我可以協助你解決一些邏輯推理問題,比如數學題、謎語等。
4. **編程**:我可以提供編程協助,包括代碼編寫、調試和最佳化。
5. **多語言支援**:我支援多種語言,包括但不限於中文、英文、法語、西班牙語等。
6. **觀點表達**:我可以為你提供一些觀點和建議,協助你做出決策。
7. **玩遊戲**:我們可以一起玩文字遊戲,比如猜謎語、成語接龍等。
如果你有任何具體的需求或問題,歡迎告訴我,我會儘力協助你!應用於生產環境
構建高品質的上下文
向大模型直接輸入大量未經處理資料,會因上下文容量的限制導致成本增加與效果下降。上下文工程(Context Engineering)通過動態載入精準知識,顯著提升產生品質與效率。核心技術包括:
提示詞工程(Prompt Engineering):通過設計和最佳化文本指令(Prompt),可以更精確地引導模型,使其輸出更符合預期的結果。若想瞭解更多,可參考文生文Prompt指南、阿里雲百鍊 提示詞模板頁面。
檢索增強產生(RAG):適用於需要模型依據外部知識庫(例如產品文檔或技術手冊)來回答問題的情境。
工具調用(Tool):允許模型擷取即時資訊(如查詢天氣、路況)或完成特定操作(如調用API、發送郵件)。
記憶機制(Memory):為模型建立長短期記憶,使其能夠理解連續對話的歷史資訊。
若想系統瞭解,可參考阿里雲大模型進階工程師ACP認證課程。
控制回複多樣性
temperature 和 top_p用於控制產生文本的多樣性。數值越高,內容越多樣,數值越低,內容越確定。為準確評估參數效果,建議每次只調整一個。
temperature:範圍 [0, 2)。側重調整隨機性。top_p:範圍 [0, 1]。通過機率閾值過濾回複。
以下樣本將展示不同參數設定對產生內容的影響。輸入提示詞為:“寫一個三句話的短故事,主角是一隻貓和一束陽光。”
高多樣性(樣本
temperature=0.9):適用於需要創意、想象力和新穎表達的情境,如創意寫作、頭腦風暴或市場營銷文案。陽光斜斜地切進窗檯,橘貓躡手躡腳走近那塊發光的方磚,絨毛瞬間被染成熔化的蜜糖。 它伸出前爪輕拍光斑,卻像踩進溫熱的池水般陷了進去,整片陽光順著肉墊汩汩漫上脊背。 午後忽然變得很重——貓兒蜷在流動的金砂裡,聽見時光在呼嚕聲中輕輕融化。高確定性(樣本
temperature=0.1):適用於要求內容準確、嚴謹和可預測的情境,如事實問答、代碼產生或法律文本。午後,一隻老貓蜷在窗檯,數著光斑打盹。 陽光輕輕躍過它斑駁的脊背,像在翻閱一本舊相簿。 塵埃浮起又落下,彷彿時光低語:你曾年輕,我也熾熱。
更多功能
上文介紹了基礎的互動方式。針對更複雜的情境,可參考:
API 參考
模型調用的完整參數列表,請參考 OpenAI 相容 API 參考和DashScope API 參考。
常見問題
Q:通義千問 API 為何無法分析網頁連結?
A:通義千問 API 本身不具備直接存取和解析網頁連結的能力,可以通過Function Calling功能,或結合 Python 的 Beautiful Soup 等網頁抓取工具讀取網頁資訊。
Q:網頁端通義千問和通義千問 API 的回複為什麼不一致?
A:網頁端通義千問在通義千問 API 的基礎上做了額外的工程最佳化,因此可以達到解析網頁、連網搜尋、畫圖、製作 PPT等功能,這些本身並不屬於大模型 API 的能力,可以通過Function Calling功能最佳化模型的效果。
Q:模型能直接產生 Word、Excel、PDF 或 PPT 格式的檔案嗎?
A:不能。阿里雲百鍊的文本產生模型僅輸出純文字內容。您需要通過代碼或使用第三方庫將文本轉換為所需格式。