文本產生模型根據自然語言提示詞(Prompt)產生連貫、上下文相關的文本,支援聊天機器人、內容創作、文檔摘要和代碼產生等情境。
文本產生模型所需的輸入可以是簡單的關鍵詞、一句話概述或更複雜的多步驟指令和上下文資訊。常見應用情境:
輸出的響應對象中會包含模型回複的
返回結果
- 內容創作:產生新聞文章、商品介紹及短視頻指令碼。
- 客戶服務:構建全天候自動應答的聊天機器人,解答常見問題。
- 文本翻譯:支援多語言之間的快速精準翻譯。
- 摘要提煉:從長文、報告及郵件中提取關鍵資訊。
- 法律文檔編寫:產生合約範本、法律意見書的基礎架構。
核心概念
文本產生模型的輸入為提示詞(Prompt),它由一個或多個訊息(Message)對象構成。每條訊息由角色(Role)和內容(Content)組成,具體為:- 系統訊息(System Message):設定模型的角色定位、管理辦法或特定任務指令。若不指定,預設為"You are a helpful assistant"。
- 使用者訊息(User Message):使用者向模型提出的問題、指令或輸入內容。
- 助手訊息(Assistant Message):模型的回複內容。在多輪對話中,傳入歷史助手訊息以維持上下文。
messages。一個典型的請求通常由一條定義管理辦法的 system 訊息和一條使用者提出的 user 訊息組成。
system 訊息是可選的,但建議設定。明確模型的角色定位和行為約束,有助於獲得更一致、可預測的輸出。
Copy
[
{"role": "system", "content": "你是一個有協助的助手,需要提供精準、高效且富有洞察力的回應,隨時準備協助使用者處理各種任務與問題。"},
{"role": "user", "content": "你是誰?"}
]
assistant訊息。
Copy
{
"role": "assistant",
"content": "你好!我是Qwen,是阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我可以協助你回答問題、創作文字、進行邏輯推理、編程等。我能夠理解並產生多種語言,支援多輪對話和複雜任務處理。如果你有任何需要協助的地方,儘管告訴我!"
}
快速開始
API 使用前提:已擷取與配置 API Key並完成配置API Key到環境變數。如果通過SDK調用,需要安裝 OpenAI 或 DashScope SDK。樣本接入地址中的{WorkspaceId} 為業務空間 ID,擷取方式請參見選擇地區、服務部署範圍和接入網域名稱。
- OpenAI相容-Chat Completions API
- OpenAI相容-Responses API
- DashScope
- Python
- Java
- Node.js
- Go
- C#(HTTP)
- PHP(HTTP)
- curl
Copy
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,調用時請將{WorkspaceId}替換為真實的業務空間ID,各地區的URL不同。
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen3.8-max",
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")
返回結果
Copy
我是千問,阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我可以協助你回答問題、創作文字,比如寫故事、寫公文、寫郵件、寫劇本、邏輯推理、編程等等,還能表達觀點,玩遊戲等。如果你有任何問題或需要協助,歡迎隨時告訴我!
Copy
// 建議 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,調用時請將{WorkspaceId}替換為真實的業務空間ID,各地區的URL不同。
.baseUrl("https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1")
.build();
// 建立 ChatCompletion 參數
ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
.model("qwen3.8-max")
.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");
}
}
}
返回結果
Copy
我是千問,阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我可以協助你回答問題、創作文字,比如寫故事、寫公文、寫郵件、寫劇本、邏輯推理、編程等等,還能表達觀點,玩遊戲等。如果你有任何問題或需要協助,歡迎隨時告訴我!
Copy
// 需要 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,調用時請將{WorkspaceId}替換為真實的業務空間ID,各地區的URL不同。
baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
}
);
const completion = await openai.chat.completions.create({
model: "qwen3.8-max",
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));
返回結果
Copy
我是千問,阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我可以協助你回答問題、創作文字,比如寫故事、寫公文、寫郵件、寫劇本、邏輯推理、編程等等,還能表達觀點,玩遊戲等。如果你有任何問題或需要協助,歡迎隨時告訴我!
Copy
// 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,調用時請將{WorkspaceId}替換為真實的業務空間ID,各地區的URL不同。
option.WithBaseURL("https://{WorkspaceId}.ap-southeast-1.maas.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: "qwen3.8-max",
},
)
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))
}
返回結果
Copy
我是千問,阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我可以協助你回答問題、創作文字,比如寫故事、寫公文、寫郵件、寫劇本、邏輯推理、編程等等,還能表達觀點,玩遊戲等。如果你有任何問題或需要協助,歡迎隨時告訴我!
Copy
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");
// 以下為新加坡地區URL,調用時請將{WorkspaceId}替換為真實的業務空間ID,各地區的URL不同。
string url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions";
string jsonContent = @"{
""model"": ""qwen3.8-max"",
""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}";
}
}
}
}
返回結果
Copy
我是千問,阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我可以協助你回答問題、創作文字,比如寫故事、寫公文、寫郵件、寫劇本、邏輯推理、編程等等,還能表達觀點,玩遊戲等。如果你有任何問題或需要協助,歡迎隨時告訴我!
Copy
<?php
// 佈建要求的URL
// 以下為新加坡地區URL,調用時請將{WorkspaceId}替換為真實的業務空間ID,各地區的URL不同。
$url = 'https://{WorkspaceId}.ap-southeast-1.maas.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" => "qwen3.8-max",
"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;
?>
返回結果
Copy
我是千問,阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我可以協助你回答問題、創作文字,比如寫故事、寫公文、寫郵件、寫劇本、邏輯推理、編程等等,還能表達觀點,玩遊戲等。如果你有任何問題或需要協助,歡迎隨時告訴我!
各地區的base_url和API Key不同,詳情請參見OpenAI相容-Chat和 擷取與配置 API Key。
Copy
# 各地區配置不同,請根據實際地區修改
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3.8-max",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "你是誰?"
}
]
}'
返回結果
Copy
{
"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": "qwen3.8-max",
"id": "chatcmpl-81951b98-28b8-9659-ab07-xxxxxx"
}
Responses API是 Chat Completions API的演化版本,關於使用說明、程式碼範例和遷移指南,請參見 OpenAI相容-Responses。
- Python
- Node.js
- curl
Copy
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"),
# 各地區配置不同,請根據實際地區修改
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
response = client.responses.create(
model="qwen3.8-max",
input="Briefly introduce what you can do?"
)
print(response)
except Exception as e:
print(f"錯誤資訊:{e}")
print("請參考文檔:https://www.alibabacloud.com/help/zh/model-studio/error-code")
返回結果
返回結果主要包含以下欄位:-
id:響應 ID。 -
output:輸出資料行表。包含reasoning(思考過程)和message(回複內容)。reasoning僅在開啟 深度思考 時返回(如 Qwen3.6 系列預設開啟)。 -
usage:Token 用量統計。
Copy
Hello! I'm an AI assistant with knowledge current up to 2026. Here's a brief overview of what I can do:
* **Content Creation:** Write emails, articles, stories, scripts, and more.
* **Coding & Tech:** Generate, debug, and explain code across various programming languages.
* **Analysis & Summarization:** Process documents, interpret data, and extract key insights.
* **Problem Solving:** Assist with math, logic, reasoning, and strategic planning.
* **Learning & Translation:** Explain complex topics simply or translate between multiple languages.
Feel free to ask me anything or give me a task to get started!
Copy
// 需要 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,
// 各地區配置不同,請根據實際地區修改
baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
});
async function main() {
try {
const response = await openai.responses.create({
model: "qwen3.8-max",
input: "Briefly introduce what you can do?"
});
// Get model response
console.log(response);
} catch (error) {
console.error("Error:", error);
}
}
main();
返回結果
返回結果主要包含以下欄位:-
id:響應 ID。 -
output:輸出資料行表。包含reasoning(思考過程)和message(回複內容)。reasoning僅在開啟 深度思考 時返回(如 Qwen3.6 系列預設開啟)。 -
usage:Token 用量統計。
Copy
Hello! I'm an AI assistant with knowledge current up to 2026. Here's a brief overview of what I can do:
* **Content Creation:** Write emails, articles, stories, scripts, and more.
* **Coding & Tech:** Generate, debug, and explain code across various programming languages.
* **Analysis & Summarization:** Process documents, interpret data, and extract key insights.
* **Problem Solving:** Assist with math, logic, reasoning, and strategic planning.
* **Learning & Translation:** Explain complex topics simply or translate between multiple languages.
Feel free to ask me anything or give me a task to get started!
Copy
# 各地區配置不同,請根據實際地區修改
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/responses \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3.8-max",
"input": "Briefly introduce what you can do?",
"enable_thinking": true
}'
返回結果
Copy
{
"created_at": 1772249518,
"id": "7ad48c6b-3cc4-904f-9284-5f419c6c5xxx",
"model": "qwen3.8-max",
"object": "response",
"output": [
{
"id": "msg_94805179-2801-45da-ac1c-a87e8ea20xxx",
"summary": [
{
"text": "Okay, the user is asking me to briefly introduce what I can do. Let me start by recalling the capabilities listed in the system message. ...(篇幅原因,此處省略完整思考過程)",
"type": "summary_text"
}
],
"type": "reasoning"
},
{
"content": [
{
"annotations": [],
"text": "I'm **Qwen3.5**, a large language model designed to assist with a wide range of tasks. Here's what I can do: \n\n- **Understand & Generate Text**: Handle complex instructions, creative writing, and multi-step tasks with improved accuracy. \n- **Solve Problems**: Tackle advanced math, logic puzzles, and scientific reasoning with step-by-step clarity. \n- **Analyze Visuals**: Interpret charts, diagrams, formulas, and even extract text from images (OCR). \n- **Plan & Execute**: Break down goals into actionable steps, run code, or interact with tools autonomously. \n- **Code & Debug**: Write, explain, or fix code in multiple programming languages. \n- **Long-Context Mastery**: Process documents, books, or videos up to **256K tokens** without losing key details. \n- **Multilingual Support**: Communicate fluently in **100+ languages**, including low-resource ones. \n\nNeed help with something specific? Just ask!",
"type": "output_text"
}
],
"id": "msg_35be06c6-ca4d-4f2b-9677-7897e488dxxx",
"role": "assistant",
"status": "completed",
"type": "message"
}
],
"parallel_tool_calls": false,
"status": "completed",
"tool_choice": "auto",
"tools": [],
"usage": {
"input_tokens": 54,
"input_tokens_details": {
"cached_tokens": 0
},
"output_tokens": 662,
"output_tokens_details": {
"reasoning_tokens": 447
},
"total_tokens": 716,
"x_details": [
{
"input_tokens": 54,
"output_tokens": 662,
"output_tokens_details": {
"reasoning_tokens": 447
},
"total_tokens": 716,
"x_billing_type": "response_api"
}
]
}
}
qwen3.8-2.4t-a95b、qwen3.7-max、qwen3.7-max-2026-05-20 和 qwen3.6-max-preview 僅支援文本介面,qwen3.8-max、qwen3.8-flash、qwen3.8-27b、qwen3.7-max-2026-06-08、Qwen3.6 和 Qwen3.5 系列的 DashScope API均需使用多模態介面。以下樣本使用 qwen-plus(文本介面),可直接運行;若將模型替換為上述需使用多模態介面的模型,會提示
url error 錯誤。多模態介面的正確調用方法,請參見映像、視頻資料處理。- Python
- Java
- Node.js(HTTP)
- Go(HTTP)
- C#(HTTP)
- PHP(HTTP)
- curl
Copy
import json
import os
from dashscope import Generation
import dashscope
# 以下為新加坡地區URL,調用時請將{WorkspaceId}替換為真實的業務空間ID,各地區的URL不同。
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.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"),
# qwen3.7-max、qwen3.7-max-2026-05-20和qwen3.6-max-preview僅支援文本介面,qwen3.8-max、qwen3.7-max-2026-06-08、Qwen3.6、Qwen3.5系列需要使用多模態介面,直接替換模型會導致報錯
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")
返回結果
Copy
我是千問,阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我可以協助你回答問題、創作文字,比如寫故事、寫公文、寫郵件、寫劇本、邏輯推理、編程等等,還能表達觀點,玩遊戲等。如果你有任何問題或需要協助,歡迎隨時告訴我!
Copy
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,調用時請將{WorkspaceId}替換為真實的業務空間ID,各地區的URL不同。
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.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"))
// qwen3.7-max、qwen3.7-max-2026-05-20和qwen3.6-max-preview僅支援文本介面,qwen3.8-max、qwen3.7-max-2026-06-08支援多模態介面,Qwen3.6、Qwen3.5系列需要使用多模態介面,直接替換模型會導致報錯
.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");
}
}
}
返回結果
Copy
我是千問,阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我可以協助你回答問題、創作文字,比如寫故事、寫公文、寫郵件、寫劇本、邏輯推理、編程等等,還能表達觀點,玩遊戲等。如果你有任何問題或需要協助,歡迎隨時告訴我!
Copy
// 需要 Node.js v18+
// 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:const apiKey = "sk-xxx";
const apiKey = process.env.DASHSCOPE_API_KEY;
const data = {
// qwen3.7-max、qwen3.7-max-2026-05-20和qwen3.6-max-preview僅支援文本介面,qwen3.8-max、qwen3.7-max-2026-06-08支援多模態介面,Qwen3.6、Qwen3.5系列需要使用多模態介面,直接替換模型會導致報錯
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,調用時請將{WorkspaceId}替換為真實的業務空間ID,各地區的URL不同。
const response = await fetch('https://{WorkspaceId}.ap-southeast-1.maas.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();
返回結果
Copy
我是千問,阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我可以協助你回答問題、創作文字,比如寫故事、寫公文、寫郵件、寫劇本、邏輯推理、編程等等,還能表達觀點,玩遊戲等。如果你有任何問題或需要協助,歡迎隨時告訴我!
Copy
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
)
func main() {
requestBody := map[string]interface{}{
// qwen3.7-max、qwen3.7-max-2026-05-20和qwen3.6-max-preview僅支援文本介面,qwen3.8-max、qwen3.7-max-2026-06-08支援多模態介面,Qwen3.6、Qwen3.5系列需要使用多模態介面,直接替換模型會導致報錯
"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,調用時請將{WorkspaceId}替換為真實的業務空間ID,各地區的URL不同。
req, _ := http.NewRequest("POST", "https://{WorkspaceId}.ap-southeast-1.maas.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)
}
返回結果
Copy
我是千問,阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我可以協助你回答問題、創作文字,比如寫故事、寫公文、寫郵件、寫劇本、邏輯推理、編程等等,還能表達觀點,玩遊戲等。如果你有任何問題或需要協助,歡迎隨時告訴我!
Copy
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,調用時請將{WorkspaceId}替換為真實的業務空間ID,各地區的URL不同。
string url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
// qwen3.7-max、qwen3.7-max-2026-05-20和qwen3.6-max-preview僅支援文本介面,qwen3.8-max、qwen3.7-max-2026-06-08支援多模態介面,Qwen3.6、Qwen3.5系列需要使用多模態介面,直接替換模型會導致報錯
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}";
}
}
}
}
返回結果
Copy
{
"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"
}
Copy
<?php
// 以下為新加坡地區URL,調用時請將{WorkspaceId}替換為真實的業務空間ID,各地區的URL不同。
$url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
// 擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
$apiKey = getenv('DASHSCOPE_API_KEY');
$data = [
// qwen3.7-max、qwen3.7-max-2026-05-20和qwen3.6-max-preview僅支援文本介面,qwen3.8-max、qwen3.7-max-2026-06-08支援多模態介面,Qwen3.6、Qwen3.5系列需要使用多模態介面,直接替換模型會導致報錯
"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);
?>
返回結果
Copy
我是千問,阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我可以協助你回答問題、創作文字,比如寫故事、寫公文、寫郵件、寫劇本、邏輯推理、編程等等,還能表達觀點,玩遊戲等。如果你有任何問題或需要協助,歡迎隨時告訴我!
各地區的base_url和API Key不同,詳情請參見DashScope和 擷取與配置 API Key。
Copy
# 各地區配置不同,請根據實際地區修改
curl --location "https://{WorkspaceId}.ap-southeast-1.maas.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"
}
}'
返回結果
Copy
{
"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相容-Chat Completions API
- DashScope
- Python
- Node.js
- curl
Copy
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"),
# 以下為新加坡地區URL,調用時請將{WorkspaceId}替換為真實的業務空間ID,各地區的URL不同。
base_url="https://{WorkspaceId}.ap-southeast-1.maas.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.6-plus",
messages=messages,
)
print(completion.choices[0].message.content)
Copy
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,調用時請將{WorkspaceId}替換為真實的業務空間ID,各地區的URL不同。
baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.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.6-plus",
messages: messages
});
console.log(response.choices[0].message.content);
}
main()
各地區的base_url和API Key不同,詳情請參見OpenAI相容-Chat和 擷取與配置 API Key。
Copy
# 以下為新加坡地區URL,調用時請將{WorkspaceId}替換為真實的業務空間ID,各地區的URL不同。
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen3.6-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": "請問圖片展現了有哪些商品?"
}
]
}
]
}'
- Python
- Java
- curl
Copy
import os
from dashscope import MultiModalConversation
import dashscope
# 以下為新加坡地區URL,調用時請將{WorkspaceId}替換為真實的業務空間ID,各地區的URL不同。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.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.6-plus', # 可按需更換為其它多模態模型,並修改相應的 messages
messages=messages
)
print(response.output.choices[0].message.content[0]['text'])
Copy
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 {
// 以下為新加坡地區URL,調用時請將{WorkspaceId}替換為真實的業務空間ID,各地區的URL不同。
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
private static final String modelName = "qwen3.6-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);
}
}
各地區的base_url和API Key不同,詳情請參見DashScope和 擷取與配置 API Key。
Copy
# 以下為新加坡地區URL,調用時請將{WorkspaceId}替換為真實的業務空間ID,各地區的URL不同。
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen3.6-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相容-Chat Completions API
- DashScope
Python
Copy
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,調用時請將{WorkspaceId}替換為真實的業務空間ID,各地區的URL不同。
base_url="https://{WorkspaceId}.ap-southeast-1.maas.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)
DashScope SDK的文本產生非同步呼叫,目前僅支援Python。
Copy
# DashScope Python SDK版本需要不低於 1.19.0
import asyncio
import platform
from dashscope.aigc.generation import AioGeneration
import os
import dashscope
# 以下為新加坡地區URL,調用時請將{WorkspaceId}替換為真實的業務空間ID,各地區的URL不同。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.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)
由於調用是非同步,響應的返回順序可能與樣本不同。
Copy
發送問題: 你是誰?
發送問題: 你會什嗎?
發送問題: 天氣怎麼樣?
模型回複: 你好!我是千問,阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我可以協助你回答問題、創作文字,比如寫故事、寫公文、寫郵件、寫劇本、邏輯推理、編程等等,還能表達觀點,玩遊戲等。如果你有任何問題或需要協助,歡迎隨時告訴我!
模型回複: 您好!我目前無法即時擷取天氣資訊。您可以告訴我您所在的城市或地區,我會儘力為您提供一些通用的天氣建議或資訊。或者您也可以使用天氣應用查看即時天氣情況。
模型回複: 我會很多技能,比如:
1. **回答問題**:無論是學術問題、生活常識還是專業知識,我都可以嘗試幫你解答。
2. **創作文字**:我可以寫故事、公文、郵件、劇本等各類文本。
3. **邏輯推理**:我可以協助你解決一些邏輯推理問題,比如數學題、謎語等。
4. **編程**:我可以提供編程協助,包括代碼編寫、調試和最佳化。
5. **多語言支援**:我支援多種語言,包括但不限於中文、英文、法語、西班牙語等。
6. **觀點表達**:我可以為你提供一些觀點和建議,協助你做出決策。
7. **玩遊戲**:我們可以一起玩文字遊戲,比如猜謎語、成語接龍等。
如果你有任何具體的需求或問題,歡迎告訴我,我會儘力協助你!
應用於生產環境
構建高品質的上下文
向大模型直接輸入大量未經處理資料,會因上下文容量的限制導致成本增加與效果下降。上下文工程(Context Engineering)通過動態載入精準知識,顯著提升產生品質與效率。核心技術包括:- 提示詞工程(Prompt Engineering):通過設計和最佳化文本指令(Prompt),可以更精確地引導模型,使其輸出更符合預期的結果。若想瞭解更多,可參考文生文Prompt指南頁面。
- 檢索增強產生(RAG):適用於需要模型依據外部知識庫(例如產品文檔或技術手冊)來回答問題的情境。
- 工具調用(Tool):允許模型擷取即時資訊(如查詢天氣、路況)或完成特定操作(如調用API、發送郵件)。
- 記憶機制(Memory):為模型建立長短期記憶,使其能夠理解連續對話的歷史資訊。
控制回複多樣性
temperature和 top_p用於控制產生文本的多樣性。數值越高,內容越多樣,數值越低,內容越確定。為準確評估參數效果,建議每次只調整一個。
- temperature:範圍 [0, 2)。側重調整隨機性。
- top_p:範圍 (0, 1]。通過機率閾值過濾回複。
- 高多樣性(樣本
temperature=0.9):適用於需要創意、想象力和新穎表達的情境,如創意寫作、頭腦風暴或市場營銷文案。
Copy
陽光斜斜地切進窗檯,橘貓躡手躡腳走近那塊發光的方磚,絨毛瞬間被染成熔化的蜜糖。
它伸出前爪輕拍光斑,卻像踩進溫熱的池水般陷了進去,整片陽光順著肉墊汩汩漫上脊背。
午後忽然變得很重——貓兒蜷在流動的金砂裡,聽見時光在呼嚕聲中輕輕融化。
- 高確定性(樣本
temperature=0.1):適用於要求內容準確、嚴謹和可預測的情境,如事實問答、代碼產生或法律文本。
Copy
午後,一隻老貓蜷在窗檯,數著光斑打盹。
陽光輕輕躍過它斑駁的脊背,像在翻閱一本舊相簿。
塵埃浮起又落下,彷彿時光低語:你曾年輕,我也熾熱。
原理介紹
原理介紹
temperature:
- temperature 越高,Token 機率分布變得更平坦(即高機率 Token 的機率降低,低機率 Token 的機率上升),使得模型在選擇下一個 Token 時更加隨機。
- temperature 越低,Token 機率分布變得更陡峭(即高機率 Token 被選取的機率更高,低機率 Token 的機率更低),使得模型更傾向於選擇高機率的少數 Token。
- top_p 越高,考慮的 Token 越多,因此產生的文本更多樣。
- top_p 越低,考慮的 Token 越少,因此產生的文本更集中和確定。
不同情境的參數配置樣本
不同情境的參數配置樣本
Copy
# 不同情境的推薦參數配置
SCENARIO_CONFIGS = {
# 創造性寫作
"creative_writing": {
"temperature": 0.9,
"top_p": 0.95
},
# 代碼產生
"code_generation": {
"temperature": 0.2,
"top_p": 0.8
},
# 事實性問答
"factual_qa": {
"temperature": 0.1,
"top_p": 0.7
},
# 翻譯
"translation": {
"temperature": 0.3,
"top_p": 0.8
}
}
# OpenAI使用樣本
# completion = client.chat.completions.create(
# model="qwen-plus",
# messages=[{"role": "user", "content": "寫一首關於月亮的詩"}],
# **SCENARIO_CONFIGS["creative_writing"]
# )
# DashScope使用樣本
# response = Generation.call(
# # 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:api_key = "sk-xxx",
# api_key=os.getenv("DASHSCOPE_API_KEY"),
# model="qwen-plus",
# messages=[{"role": "user", "content": "寫一個判斷輸入n是否是質數的python函數,不要輸出非代碼內容"}],
# result_format="message",
# **SCENARIO_CONFIGS["code_generation"]
# )
更多功能
上文介紹了基礎的互動方式。針對更複雜的情境,可參考:- 多輪對話:適用於追問、資訊採集等需要連續交流的情境。
- 流式輸出:適用於聊天機器人、即時代碼產生等需要即時響應的情境,可以提升使用者體驗,並避免因回應時間過長導致的逾時。
- 深度思考:適用於複雜推理、策略分析等需要更高品質、更具條理的深度回答的情境。
- 結構化輸出:當需要模型按穩定的JSON格式回複,以便於程式調用或資料解析時使用。
- 首碼續寫:適用於代碼補全、長文寫作等需要模型接續已有文本的情境。
API 參考
模型調用的完整參數列表,請參考 OpenAI 相容API參考和DashScope API參考。常見問題
Q:為什麼輸入Token數比我發送的文本Token數多?
A:在處理對話時,系統會使用對話模板(Chat Template)對輸入的原始文本進行封裝,添加角色標識、訊息邊界等控制標記。這些由系統添加的標記同樣會計入Token。 例如,向qwen3.8-max發送訊息{"role": "user", "content": "你好"},“你好” 在分詞(Tokenize)後僅對應 1 個 Token,但系統處理時,實際輸入完整文本為<|im_start|>user\n你好<|im_end|>\n<|im_start|>assistant\n<think>,分詞後總Token數會增加到11個。