文本產生模型能夠基於輸入的提示詞(Prompt)創作出邏輯清晰、連貫的文本。
文本產生模型所需的輸入可以是簡單的關鍵詞、一句話概述或是更複雜的指令和上下文資訊。模型通過分析海量資料學習語言模式,廣泛應用於:
內容創作:產生新聞報道、商品介紹及短視頻指令碼。
客戶服務:驅動聊天機器人提供全天候支援,解答常見問題。
文本翻譯:實現跨語言的快速精準轉換。
摘要產生:提煉長文、報告及郵件的核心內容。
法律文檔編寫:產生合約範本、法律意見書的基礎架構。
模型選型建議
服務地區
阿里雲百鍊提供新加坡、維吉尼亞、北京、中國香港、法蘭克福地區的模型服務,各地區的API Key不同,選擇鄰近地區調用可降低網路延遲,詳情請參見選擇地區和部署模式。
通用模型
千問文本產生模型相容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。
OpenAI相容-Responses API
Responses API 是 Chat Completions API 的演化版本,關於使用說明、程式碼範例和遷移指南,請參見 OpenAI相容-Responses。
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"),
# 各地區配置不同,請根據實際地區修改
base_url="https://dashscope-intl.aliyuncs.com/api/v2/apps/protocols/compatible-mode/v1",
)
response = client.responses.create(
model="qwen3.5-plus",
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.5 系列預設開啟)。usage:Token 用量統計。
回複內容樣本如下,完整響應請參考curl。
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!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,
// 各地區配置不同,請根據實際地區修改
baseURL: "https://dashscope-intl.aliyuncs.com/api/v2/apps/protocols/compatible-mode/v1"
});
async function main() {
try {
const response = await openai.responses.create({
model: "qwen3.5-plus",
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.5 系列預設開啟)。usage:Token 用量統計。
回複內容樣本如下,完整響應請參考curl。
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!curl
# 各地區配置不同,請根據實際地區修改
curl -X POST https://dashscope-intl.aliyuncs.com/api/v2/apps/protocols/compatible-mode/v1/responses \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen3.5-plus",
"input": "Briefly introduce what you can do?",
"enable_thinking": true
}'返回結果
{
"created_at": 1772249518,
"id": "7ad48c6b-3cc4-904f-9284-5f419c6c5xxx",
"model": "qwen3.5-plus",
"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. I need to make sure I cover the main points without getting too detailed.\n\nFirst, I should mention my enhanced language foundation and architecture efficiency. Then, the upgraded logical reasoning and mathematical capabilities. Visual analysis is another key point, including charts and formulas. Autonomous agent planning and code generation are important too. Human alignment optimization for better interaction, long-context handling up to 256K, and multilingual support with OCR.\n\nWait, the user said \"briefly,\" so I need to keep it concise. Maybe group some points together. Let me check the examples given in the system message. They have sections like Enhanced Language Foundation, Advanced Logical Reasoning, etc. But since it's a brief intro, I should summarize each capability in a sentence or two.\n\nAlso, the user might be looking for practical applications. Maybe highlight how these features help in real tasks. For example, handling long documents, solving math problems, analyzing images, writing code, etc.\n\nI should avoid technical jargon where possible. Make it clear and straightforward. Let me structure it as a list of key capabilities with short explanations. Start with a greeting, then list the main points, and end with an offer to help with specific tasks.\n\nWait, the system message says \"You are Qwen3.5,\" so I need to introduce myself as such. But the user just asked what I can do, so maybe start with \"I'm Qwen3.5...\" and then list the capabilities.\n\nCheck if all the upgraded features from Qwen3 to Qwen3.5 are covered. The main upgrades are in language foundation, reasoning, visual analysis, agent planning, code, alignment, context length, and multilingual OCR.\n\nMake sure not to mention the knowledge cutoff unless relevant. The user's current time is 2026, but since my knowledge is up to 2026, that's covered.\n\nOkay, let me draft a concise response highlighting each capability briefly. Keep it friendly and inviting for the user to ask for specific help.\n",
"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"
}
]
}
}OpenAI相容-Chat Completions API
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"),
# 各地區的base_url不同
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen3.5-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"))
// 各地區的base_url不同
.baseUrl("https://dashscope-intl.aliyuncs.com/compatible-mode/v1")
.build();
// 建立 ChatCompletion 參數
ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
.model("qwen3.5-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,
// 各地區的base_url不同
baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
}
);
const completion = await openai.chat.completions.create({
model: "qwen3.5-plus",
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
// 各地區的base_url不同
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: "qwen3.5-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不同
string url = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions";
string jsonContent = @"{
""model"": ""qwen3.5-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
// 各地區的base_url不同
$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" => "qwen3.5-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和API Key不同,詳情請參見OpenAI Chat和 擷取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.5-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": "qwen3.5-plus",
"id": "chatcmpl-81951b98-28b8-9659-ab07-xxxxxx"
}DashScope
Qwen3.5系列的DashScope API採用多模態介面,以下樣本會報錯url error,調用方式請參見映像、視頻資料處理。
Python
import json
import os
from dashscope import Generation
import dashscope
# 各地區的base_url不同
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"),
# 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")返回結果
我是千問,阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我可以協助你回答問題、創作文字,比如寫故事、寫公文、寫郵件、寫劇本、邏輯推理、編程等等,還能表達觀點,玩遊戲等。如果你有任何問題或需要協助,歡迎隨時告訴我!Java
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 {
// 各地區的base_url不同
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"))
// 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");
}
}
}返回結果
我是千問,阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我可以協助你回答問題、創作文字,比如寫故事、寫公文、寫郵件、寫劇本、邏輯推理、編程等等,還能表達觀點,玩遊戲等。如果你有任何問題或需要協助,歡迎隨時告訴我!Node.js(HTTP)
// 需要 Node.js v18+
// 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:const apiKey = "sk-xxx";
const apiKey = process.env.DASHSCOPE_API_KEY;
const data = {
// 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 {
// 各地區的base_url不同
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{}{
// 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{}
// 各地區的base_url不同
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 和內容
// 各地區的base_url不同
string url = "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
// 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}";
}
}
}
}返回結果
{
"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
// 各地區的base_url不同
$url = "https://dashscope-intl.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.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);
?>返回結果
我是千問,阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我可以協助你回答問題、創作文字,比如寫故事、寫公文、寫郵件、寫劇本、邏輯推理、編程等等,還能表達觀點,玩遊戲等。如果你有任何問題或需要協助,歡迎隨時告訴我!curl
# 各地區配置不同,請根據實際地區修改
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相容-Chat Completions API
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-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.5-plus",
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不同
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.5-plus",
messages: messages
});
console.log(response.choices[0].message.content);
}
main()curl
各地區的base_url和API Key不同,詳情請參見OpenAI Chat和 擷取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.5-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不同
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.5-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不同
Constants.baseHttpApiUrl = "https://dashscope-intl.aliyuncs.com/api/v1";
}
private static final String modelName = "qwen3.5-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
# 各地區配置不同,請根據實際地區修改
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.5-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
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"),
# 各地區的base_url不同
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不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為.apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// 各地區的base_url不同
.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
# 各地區的base_url不同
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):為模型建立長短期記憶,使其能夠理解連續對話的歷史資訊。
控制回複多樣性
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:不能。阿里雲百鍊的文本產生模型僅輸出純文字內容。您需要通過代碼或使用第三方庫將文本轉換為所需格式。