全部產品
Search
文件中心

Alibaba Cloud Model Studio:長上下文(Qwen-Long)

更新時間:Jan 01, 2026

處理超長文字文件時,標準大型語言模型會因上下文視窗限制而失敗。Qwen-Long 模型提供 1000 萬 Token 的上下文長度,通過檔案上傳和引用機制處理大規模資料。

說明

本文檔僅適用於“中國內地(北京)”地區。如需使用模型,需使用“中國內地(北京)”地區的API Key

使用方式

Qwen-Long 處理長文檔分為以下兩個步驟:檔案上傳與 API 呼叫。

  1. 檔案上傳與解析:

    • 通過 API 上傳檔案,檔案格式與大小限制請參考支援格式

    • 上傳並成功後,系統返回一個當前帳號下的唯一 file-id並開始解析。檔案上傳、儲存以及解析本身不產生費用。

  2. API 呼叫與計費:

    • 在調用模型時,通過在 system 訊息中引用一個或多個 file-id

    • 模型根據 file-id 關聯的常值內容進行推理。

    • 每次API 呼叫都會將所引用檔案內容 Token 數計入該次請求的輸入Token

此機制避免了在每次請求中傳輸龐大的檔案內容,但需留意其計費方式。

快速開始

前提條件

文檔上傳

阿里雲百鍊系列手機產品介紹.docx為例,通過OpenAI相容介面上傳到阿里雲百鍊平台的安全儲存空間,擷取返回的file-id。有關文檔上傳介面的詳細參數解釋及調用方式,請參考API文檔頁面進行瞭解。

Python

import os
from pathlib import Path
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),  # 如果您沒有配置環境變數,請在此處替換您的API-KEY
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",  # 填寫DashScope服務base_url
)

file_object = client.files.create(file=Path("阿里雲百鍊系列手機產品介紹.docx"), purpose="file-extract")
print(file_object.id)

Java

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.files.*;

import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {
    public static void main(String[] args) {
        // 建立用戶端,使用環境變數中的API密鑰
        OpenAIClient client = OpenAIOkHttpClient.builder()
                // 若沒有配置環境變數,請用百鍊API Key將下行替換為:.apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .baseUrl("https://dashscope.aliyuncs.com/compatible-mode/v1")
                .build();
        // 設定檔案路徑,請根據實際需求修改路徑與檔案名稱
        Path filePath = Paths.get("src/main/java/org/example/阿里雲百鍊系列手機產品介紹.docx");
        // 建立檔案上傳參數
        FileCreateParams fileParams = FileCreateParams.builder()
                .file(filePath)
                .purpose(FilePurpose.of("file-extract"))
                .build();

        // 上傳檔案列印fileid
        FileObject fileObject = client.files().create(fileParams);
        System.out.println(fileObject.id());
    }
}

curl

curl --location --request POST 'https://dashscope.aliyuncs.com/compatible-mode/v1/files' \
  --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
  --form 'file=@"阿里雲百鍊系列手機產品介紹.docx"' \
  --form 'purpose="file-extract"'

運行以上代碼,您可以得到本次上傳檔案對應的file-id

通過檔案ID傳入資訊並對話

將擷取的 file-id 嵌入到System Message 中。第一條System Message用於設定角色向模型提問,後續的System Message用於傳入 file-id,User Message包含針對文檔的具體問題。

較長的文檔可能會需要相對更長的時間完成解析,請耐心等待解析完成後進行調用。

Python

import os
from openai import OpenAI, BadRequestError

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),  # 如果您沒有配置環境變數,請在此處替換您的API-KEY
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",  # 填寫DashScope服務base_url
)
try:
    # 初始化messages列表
    completion = client.chat.completions.create(
        model="qwen-long",
        messages=[
            {'role': 'system', 'content': 'You are a helpful assistant.'},
            # 請將 '{FILE_ID}'替換為您實際對話情境所使用的 fileid。
            {'role': 'system', 'content': f'fileid://{FILE_ID}'},
            {'role': 'user', 'content': '這篇文章講了什麼?'}
        ],
        # 所有程式碼範例均採用流式輸出,以清晰和直觀地展示模型輸出過程。如果您希望查看非流式輸出的案例,請參見https://www.alibabacloud.com/help/zh/model-studio/text-generation
        stream=True,
        stream_options={"include_usage": True}
    )

    full_content = ""
    for chunk in completion:
        if chunk.choices and chunk.choices[0].delta.content:
            # 拼接輸出內容
            full_content += chunk.choices[0].delta.content
            print(chunk.model_dump())
        
        # 擷取 token 使用方式
        if chunk.usage:
            print(f"總計 tokens: {chunk.usage.total_tokens}")

    print(full_content)

except BadRequestError as e:
    print(f"錯誤資訊:{e}")
    print("請參考文檔:https://www.alibabacloud.com/help/zh/model-studio/error-code")

Java

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.http.StreamResponse;
import com.openai.models.chat.completions.*;

public class Main {
    public static void main(String[] args) {
        // 建立用戶端,使用環境變數中的API密鑰
        OpenAIClient client = OpenAIOkHttpClient.builder()
                // 若沒有配置環境變數,請用百鍊API Key將下行替換為:.apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .baseUrl("https://dashscope.aliyuncs.com/compatible-mode/v1")
                .build();

        // 建立聊天請求
        ChatCompletionCreateParams chatParams = ChatCompletionCreateParams.builder()
                .addSystemMessage("You are a helpful assistant.")
                //請將 '{FILE_ID}'替換為您實際對話情境所使用的 fileid。
                .addSystemMessage("fileid://{FILE_ID}")
                .addUserMessage("這篇文章講了什嗎?")
                .model("qwen-long")
                .build();

        StringBuilder fullResponse = new StringBuilder();

        // 所有程式碼範例均採用流式輸出,以清晰和直觀地展示模型輸出過程。如果您希望查看非流式輸出的案例,請參見https://www.alibabacloud.com/help/zh/model-studio/text-generation
        try (StreamResponse<ChatCompletionChunk> streamResponse = client.chat().completions().createStreaming(chatParams)) {
            streamResponse.stream().forEach(chunk -> {
                // 列印每個 chunk 的內容並拼接
                System.out.println(chunk);
                String content = chunk.choices().get(0).delta().content().orElse("");
                if (!content.isEmpty()) {
                    fullResponse.append(content);
                }
            });
            System.out.println(fullResponse);
        } catch (Exception e) {
            System.err.println("錯誤資訊:" + e.getMessage());
            System.err.println("請參考文檔:https://www.alibabacloud.com/help/zh/model-studio/error-code");
        }
    }
}

curl

curl --location 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
    "model": "qwen-long",
    "messages": [
        {"role": "system","content": "You are a helpful assistant."},
        {"role": "system","content": "fileid://file-fe-xxx"},
        {"role": "user","content": "這篇文章講了什嗎?"}
    ],
    "stream": true,
    "stream_options": {
        "include_usage": true
    }
}'

傳入多個文檔

您可以在一條System Message中傳入多個file-id,以便在一次請求中處理多個文檔;也可以在messages中添加新的System Message以補充新的文檔資訊。

傳入多文檔

Python

import os
from openai import OpenAI, BadRequestError

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),  # 如果您沒有配置環境變數,請在此處替換您的API-KEY
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",  # 填寫DashScope服務base_url
)
try:
    # 初始化messages列表
    completion = client.chat.completions.create(
        model="qwen-long",
        messages=[
            {'role': 'system', 'content': 'You are a helpful assistant.'},
            # 請將 '{FILE_ID1}' 和 '{FILE_ID2}' 替換為您實際對話情境所使用的 fileid。
            {'role': 'system', 'content': f"fileid://{FILE_ID1},fileid://{FILE_ID2}"},
            {'role': 'user', 'content': '這幾篇文章講了什嗎?'}
        ],
        # 所有程式碼範例均採用流式輸出,以清晰和直觀地展示模型輸出過程。如果您希望查看非流式輸出的案例,請參見https://www.alibabacloud.com/help/zh/model-studio/text-generation
        stream=True,
        stream_options={"include_usage": True}
    )
    
    full_content = ""
    for chunk in completion:
        if chunk.choices and chunk.choices[0].delta.content:
            # 拼接輸出內容
            full_content += chunk.choices[0].delta.content
            print(chunk.model_dump())
    
    print(full_content)

except BadRequestError as e:
    print(f"錯誤資訊:{e}")
    print("請參考文檔:https://www.alibabacloud.com/help/zh/model-studio/error-code")

Java

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.http.StreamResponse;
import com.openai.models.chat.completions.*;

public class Main {
    public static void main(String[] args) {
        // 建立用戶端,使用環境變數中的API密鑰
        OpenAIClient client = OpenAIOkHttpClient.builder()
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .baseUrl("https://dashscope.aliyuncs.com/compatible-mode/v1")
                .build();

        // 建立聊天請求
        ChatCompletionCreateParams chatParams = ChatCompletionCreateParams.builder()
                .addSystemMessage("You are a helpful assistant.")
                //請將 '{FILE_ID1}' 和 '{FILE_ID2}' 替換為您實際對話情境所使用的 fileid。
                .addSystemMessage("fileid://{FILE_ID1},fileid://{FILE_ID2}")
                .addUserMessage("這兩篇文章講了什嗎?")
                .model("qwen-long")
                .build();

        StringBuilder fullResponse = new StringBuilder();

        // 所有程式碼範例均採用流式輸出,以清晰和直觀地展示模型輸出過程。如果您希望查看非流式輸出的案例,請參見https://www.alibabacloud.com/help/zh/model-studio/text-generation
        try (StreamResponse<ChatCompletionChunk> streamResponse = client.chat().completions().createStreaming(chatParams)) {
            streamResponse.stream().forEach(chunk -> {
                // 每個 chunk 的內容
                System.out.println(chunk);
                String content = chunk.choices().get(0).delta().content().orElse("");
                if (!content.isEmpty()) {
                    fullResponse.append(content);
                }
            });
            System.out.println("\n完整回複內容:");
            System.out.println(fullResponse);
        } catch (Exception e) {
            System.err.println("錯誤資訊:" + e.getMessage());
            System.err.println("請參考文檔:https://www.alibabacloud.com/help/zh/model-studio/error-code");
        }
    }
}

curl

curl --location 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
    "model": "qwen-long",
    "messages": [
        {"role": "system","content": "You are a helpful assistant."},
        {"role": "system","content": "fileid://file-fe-xxx1"},
        {"role": "system","content": "fileid://file-fe-xxx2"},
        {"role": "user","content": "這兩篇文章講了什嗎?"}
    ],
    "stream": true,
    "stream_options": {
        "include_usage": true
    }
}'

追加文檔

Python

import os
from openai import OpenAI, BadRequestError

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),  # 如果您沒有配置環境變數,請在此處替換您的API-KEY
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",  # 填寫DashScope服務base_url
)
# 初始化messages列表
messages = [
    {'role': 'system', 'content': 'You are a helpful assistant.'},
    # 請將 '{FILE_ID1}' 替換為您實際對話情境所使用的 fileid。
    {'role': 'system', 'content': f'fileid://{FILE_ID1}'},
    {'role': 'user', 'content': '這篇文章講了什嗎?'}
]

try:
    # 第一輪響應
    completion_1 = client.chat.completions.create(
        model="qwen-long",
        messages=messages,
        stream=False
    )
    # 列印出第一輪響應
    # 如果需要流式輸出第一輪的響應,需要將stream設定為True,並拼接每一段輸出內容,在構造assistant_message的content時傳入拼接後的字元
    print(f"第一輪響應:{completion_1.choices[0].message.model_dump()}")
except BadRequestError as e:
    print(f"錯誤資訊:{e}")
    print("請參考文檔:https://www.alibabacloud.com/help/zh/model-studio/error-code")

# 構造assistant_message
assistant_message = {
    "role": "assistant",
    "content": completion_1.choices[0].message.content}

# 將assistant_message添加到messages中
messages.append(assistant_message)

# 將追加文檔的fileid添加到messages中
# 請將 '{FILE_ID2}' 替換為您實際對話情境所使用的 fileid。
system_message = {'role': 'system', 'content': f'fileid://{FILE_ID2}'}
messages.append(system_message)

# 添加使用者問題
messages.append({'role': 'user', 'content': '這兩篇文章討論的方法有什麼異同點?'})

# 追加文檔後的響應
completion_2 = client.chat.completions.create(
    model="qwen-long",
    messages=messages,
    # 所有程式碼範例均採用流式輸出,以清晰和直觀地展示模型輸出過程。如果您希望查看非流式輸出的案例,請參見https://www.alibabacloud.com/help/zh/model-studio/text-generation
    stream=True,
    stream_options={
        "include_usage": True
    }
)

# 流式列印出追加文檔後的響應
print("追加文檔後的響應:")
for chunk in completion_2:
    print(chunk.model_dump())

Java

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.*;
import com.openai.core.http.StreamResponse;

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.builder()
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .baseUrl("https://dashscope.aliyuncs.com/compatible-mode/v1")
                .build();
        // 初始化messages列表
        List<ChatCompletionMessageParam> messages = new ArrayList<>();
        
        // 添加用於角色設定的資訊
        ChatCompletionSystemMessageParam roleSet = ChatCompletionSystemMessageParam.builder()
                .content("You are a helpful assistant.")
                .build();
        messages.add(ChatCompletionMessageParam.ofSystem(roleSet));
        
        // 請將 '{FILE_ID1}' 替換為您實際對話情境所使用的 fileid。
        ChatCompletionSystemMessageParam systemMsg1 = ChatCompletionSystemMessageParam.builder()
                .content("fileid://{FILE_ID1}")
                .build();
        messages.add(ChatCompletionMessageParam.ofSystem(systemMsg1));

        // 使用者提問訊息(USER角色)
        ChatCompletionUserMessageParam userMsg1 = ChatCompletionUserMessageParam.builder()
                .content("請總結文章內容")
                .build();
        messages.add(ChatCompletionMessageParam.ofUser(userMsg1));

        // 構造第一輪請求並處理異常
        ChatCompletion completion1;
        try {
            completion1 = client.chat().completions().create(
                    ChatCompletionCreateParams.builder()
                            .model("qwen-long")
                            .messages(messages)
                            .build()
            );
        } catch (Exception e) {
            System.err.println("請求出錯,請查看錯誤碼對照網頁:");
            System.err.println("https://www.alibabacloud.com/help/zh/model-studio/error-code");
            System.err.println("錯誤詳情:" + e.getMessage());
            e.printStackTrace(); 
            return; 
        }

        // 第一輪響應
        String firstResponse = completion1 != null ? completion1.choices().get(0).message().content().orElse("") : "";
        System.out.println("第一輪響應:" + firstResponse);

        // 構造AssistantMessage
        ChatCompletionAssistantMessageParam assistantMsg = ChatCompletionAssistantMessageParam.builder()
                .content(firstResponse)
                .build();
        messages.add(ChatCompletionMessageParam.ofAssistant(assistantMsg));

        // 請將 '{FILE_ID2}' 替換為您實際對話情境所使用的 fileid。
        ChatCompletionSystemMessageParam systemMsg2 = ChatCompletionSystemMessageParam.builder()
                .content("fileid://{FILE_ID2}")
                .build();
        messages.add(ChatCompletionMessageParam.ofSystem(systemMsg2));

        // 第二輪使用者提問(USER角色)
        ChatCompletionUserMessageParam userMsg2 = ChatCompletionUserMessageParam.builder()
                .content("請對比兩篇文章的結構差異")
                .build();
        messages.add(ChatCompletionMessageParam.ofUser(userMsg2));

        // 所有程式碼範例均採用流式輸出,以清晰和直觀地展示模型輸出過程。如果您希望查看非流式輸出的案例,請參見https://www.alibabacloud.com/help/zh/model-studio/text-generation
        StringBuilder fullResponse = new StringBuilder();
        try (StreamResponse<ChatCompletionChunk> streamResponse = client.chat().completions().createStreaming(
                ChatCompletionCreateParams.builder()
                        .model("qwen-long")
                        .messages(messages)
                        .build())) {

            streamResponse.stream().forEach(chunk -> {
                String content = chunk.choices().get(0).delta().content().orElse("");
                if (!content.isEmpty()) {
                    fullResponse.append(content);
                }
            });
            System.out.println("\n最終響應:");
            System.out.println(fullResponse.toString().trim());
        } catch (Exception e) {
            System.err.println("錯誤資訊:" + e.getMessage());
            System.err.println("請參考文檔:https://www.alibabacloud.com/help/zh/model-studio/error-code");
        }
    }
}

curl

curl --location 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
    "model": "qwen-long",
    "messages": [
        {"role": "system","content": "You are a helpful assistant."},
        {"role": "system","content": "fileid://file-fe-xxx1"},
        {"role": "user","content": "這篇文章講了什嗎?"},
        {"role": "system","content": "fileid://file-fe-xxx2"},
        {"role": "user","content": "這兩篇文章討論的方法有什麼異同點?"}
    ],
    "stream": true,
    "stream_options": {
        "include_usage": true
    }
}'

通過純文字傳入資訊

除了通過 file-id 傳入文檔資訊外,您還可以直接使用字串傳入文檔內容。在此方法下,為避免模型混淆角色設定與文檔內容,請確保在 messages 的第一條訊息中添加用於角色設定的資訊。

受限於API調用請求體大小,如果您的常值內容長度超過100萬Token,請通過檔案ID傳入資訊對話。

簡單樣本

您可以直接將文檔內容輸入System Message中。

Python

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),  # 如果您沒有配置環境變數,請在此處替換您的API-KEY
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",  # 填寫DashScope服務base_url
)
# 初始化messages列表
completion = client.chat.completions.create(
    model="qwen-long",
    messages=[
        {'role': 'system', 'content': 'You are a helpful assistant.'},
        {'role': 'system', 'content': '阿里雲百鍊手機產品介紹 阿里雲百鍊X1 ——————暢享極致視界:搭載6.7英寸1440 x 3200像素超清螢幕...'},
        {'role': 'user', 'content': '文章講了什嗎?'}
    ],
    # 所有程式碼範例均採用流式輸出,以清晰和直觀地展示模型輸出過程。如果您希望查看非流式輸出的案例,請參見https://www.alibabacloud.com/help/zh/model-studio/text-generation
    stream=True,
    stream_options={"include_usage": True}
)

full_content = ""
for chunk in completion:
    if chunk.choices and chunk.choices[0].delta.content:
        # 拼接輸出內容
        full_content += chunk.choices[0].delta.content
        print(chunk.model_dump())

print(full_content)

Java

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.http.StreamResponse;

import com.openai.models.chat.completions.*;


public class Main {
    public static void main(String[] args) {
        // 建立用戶端,使用環境變數中的API密鑰
        OpenAIClient client = OpenAIOkHttpClient.builder()
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .baseUrl("https://dashscope.aliyuncs.com/compatible-mode/v1")
                .build();

        // 建立聊天請求
        ChatCompletionCreateParams chatParams = ChatCompletionCreateParams.builder()
                .addSystemMessage("You are a helpful assistant.")
                .addSystemMessage("阿里雲百鍊手機產品介紹 阿里雲百鍊X1 ——————暢享極致視界:搭載6.7英寸1440 x 3200像素超清螢幕...")
                .addUserMessage("這篇文章講了什嗎?")
                .model("qwen-long")
                .build();

        StringBuilder fullResponse = new StringBuilder();

        // 所有程式碼範例均採用流式輸出,以清晰和直觀地展示模型輸出過程。如果您希望查看非流式輸出的案例,請參見https://www.alibabacloud.com/help/zh/model-studio/text-generation
        try (StreamResponse<ChatCompletionChunk> streamResponse = client.chat().completions().createStreaming(chatParams)) {
            streamResponse.stream().forEach(chunk -> {
                // 列印每個 chunk 的內容並拼接
                System.out.println(chunk);
                String content = chunk.choices().get(0).delta().content().orElse("");
                if (!content.isEmpty()) {
                    fullResponse.append(content);
                }
            });
            System.out.println(fullResponse);
        } catch (Exception e) {
            System.err.println("錯誤資訊:" + e.getMessage());
            System.err.println("請參考文檔:https://www.alibabacloud.com/help/zh/model-studio/error-code");
        }
    }
}

curl

curl --location 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
    "model": "qwen-long",
    "messages": [
        {"role": "system","content": "You are a helpful assistant."},
        {"role": "system","content": "阿里雲百鍊X1 —— 暢享極致視界:搭載6.7英寸1440 x 3200像素超清螢幕,搭配120Hz重新整理率,..."},
        {"role": "user","content": "這篇文章講了什嗎?"}
    ],
    "stream": true,
    "stream_options": {
        "include_usage": true
    }
}'

傳入多文檔

當您在本輪對話需要傳入多個文檔時,可以將文檔內容放在不同的System Message中。

Python

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),  # 如果您沒有配置環境變數,請在此處替換您的API-KEY
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",  # 填寫DashScope服務base_url
)
# 初始化messages列表
completion = client.chat.completions.create(
    model="qwen-long",
    messages=[
        {'role': 'system', 'content': 'You are a helpful assistant.'},
        {'role': 'system', 'content': '阿里雲百鍊X1————暢享極致視界:搭載6.7英寸1440 x 3200像素超清螢幕,搭配120Hz重新整理率...'},
        {'role': 'system', 'content': '星塵S9 Pro —— 創新視覺盛宴:突破性6.9英寸1440 x 3088像素屏下網路攝影機設計...'},
        {'role': 'user', 'content': '這兩篇文章討論的產品有什麼異同點?'}
    ],
    # 所有程式碼範例均採用流式輸出,以清晰和直觀地展示模型輸出過程。如果您希望查看非流式輸出的案例,請參見https://www.alibabacloud.com/help/zh/model-studio/text-generation
    stream=True,
    stream_options={"include_usage": True}
)
full_content = ""
for chunk in completion:
    if chunk.choices and chunk.choices[0].delta.content:
        # 拼接輸出內容
        full_content += chunk.choices[0].delta.content
        print(chunk.model_dump())

print(full_content)

Java

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.http.StreamResponse;

import com.openai.models.chat.completions.*;


public class Main {
    public static void main(String[] args) {
        // 建立用戶端,使用環境變數中的API密鑰
        OpenAIClient client = OpenAIOkHttpClient.builder()
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .baseUrl("https://dashscope.aliyuncs.com/compatible-mode/v1")
                .build();

        // 建立聊天請求
        ChatCompletionCreateParams chatParams = ChatCompletionCreateParams.builder()
                .addSystemMessage("You are a helpful assistant.")
                .addSystemMessage("阿里雲百鍊手機產品介紹 阿里雲百鍊X1 ——————暢享極致視界:搭載6.7英寸1440 x 3200像素超清螢幕...")
                .addSystemMessage("星塵S9 Pro —— 創新視覺盛宴:突破性6.9英寸1440 x 3088像素屏下網路攝影機設計...")
                .addUserMessage("這兩篇文章討論的產品有什麼異同點?")
                .model("qwen-long")
                .build();

        StringBuilder fullResponse = new StringBuilder();

        // 所有程式碼範例均採用流式輸出,以清晰和直觀地展示模型輸出過程。如果您希望查看非流式輸出的案例,請參見https://www.alibabacloud.com/help/zh/model-studio/text-generation
        try (StreamResponse<ChatCompletionChunk> streamResponse = client.chat().completions().createStreaming(chatParams)) {
            streamResponse.stream().forEach(chunk -> {
                // 列印每個 chunk 的內容並拼接
                System.out.println(chunk);
                String content = chunk.choices().get(0).delta().content().orElse("");
                if (!content.isEmpty()) {
                    fullResponse.append(content);
                }
            });
            System.out.println(fullResponse);
        } catch (Exception e) {
            System.err.println("錯誤資訊:" + e.getMessage());
            System.err.println("請參考文檔:https://www.alibabacloud.com/help/zh/model-studio/error-code");
        }
    }
}

curl

curl --location 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
    "model": "qwen-long",
    "messages": [
        {"role": "system","content": "You are a helpful assistant."},
        {"role": "system","content": "阿里雲百鍊X1 —— 暢享極致視界:搭載6.7英寸1440 x 3200像素超清螢幕,搭配120Hz重新整理率..."},
        {"role": "system","content": "星塵S9 Pro —— 創新視覺盛宴:突破性6.9英寸1440 x 3088像素屏下網路攝影機設計..."},
        {"role": "user","content": "這兩篇文章討論的產品有什麼異同點?"}
    ],
    "stream": true,
    "stream_options": {
        "include_usage": true
    }
}'

追加文檔

在您與模型的互動過程中,可能需要補充新的文檔資訊。您可以在Messages 數組中添加新的文檔內容到System Message中來實現這一效果。

Python

import os
from openai import OpenAI, BadRequestError

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),  # 如果您沒有配置環境變數,請在此處替換您的API-KEY
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",  # 填寫DashScope服務base_url
)
# 初始化messages列表
messages = [
    {'role': 'system', 'content': 'You are a helpful assistant.'},
    {'role': 'system', 'content': '阿里雲百鍊X1 —— 暢享極致視界:搭載6.7英寸1440 x 3200像素超清螢幕,搭配120Hz重新整理率...'},
    {'role': 'user', 'content': '這篇文章講了什嗎?'}
]

try:
    # 第一輪響應
    completion_1 = client.chat.completions.create(
        model="qwen-long",
        messages=messages,
        stream=False
    )
    # 列印出第一輪響應
    # 如果需要流式輸出第一輪的響應,需要將stream設定為True,並拼接每一段輸出內容,在構造assistant_message的content時傳入拼接後的字元
    print(f"第一輪響應:{completion_1.choices[0].message.model_dump()}")
except BadRequestError as e:
    print(f"錯誤資訊:{e}")
    print("請參考文檔:https://www.alibabacloud.com/help/zh/model-studio/error-code")

# 構造assistant_message
assistant_message = {
    "role": "assistant",
    "content": completion_1.choices[0].message.content}

# 將assistant_message添加到messages中
messages.append(assistant_message)
# 將追加文檔內容添加到messages中
system_message = {
    'role': 'system',
    'content': '星塵S9 Pro —— 創新視覺盛宴:突破性6.9英寸1440 x 3088像素屏下網路攝影機設計,帶來無界視覺享受...'
}
messages.append(system_message)

# 添加使用者問題
messages.append({
    'role': 'user',
    'content': '這兩篇文章討論的產品有什麼異同點?'
})

# 追加文檔後的響應
completion_2 = client.chat.completions.create(
    model="qwen-long",
    messages=messages,
    # 所有程式碼範例均採用流式輸出,以清晰和直觀地展示模型輸出過程。如果您希望查看非流式輸出的案例,請參見https://www.alibabacloud.com/help/zh/model-studio/text-generation
    stream=True,
    stream_options={"include_usage": True}
)

# 流式列印出追加文檔後的響應
print("追加文檔後的響應:")
for chunk in completion_2:
    print(chunk.model_dump())

Java

import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.*;
import com.openai.core.http.StreamResponse;

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.builder()
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .baseUrl("https://dashscope.aliyuncs.com/compatible-mode/v1")
                .build();
        // 初始化messages列表
        List<ChatCompletionMessageParam> messages = new ArrayList<>();
        
        // 添加用於角色設定的資訊
        ChatCompletionSystemMessageParam roleSet = ChatCompletionSystemMessageParam.builder()
                .content("You are a helpful assistant.")
                .build();
        messages.add(ChatCompletionMessageParam.ofSystem(roleSet));
        
        // 第一輪傳入內容
        ChatCompletionSystemMessageParam systemMsg1 = ChatCompletionSystemMessageParam.builder()
                .content("阿里雲百鍊X1 —— 暢享極致視界:搭載6.7英寸1440 x 3200像素超清螢幕,搭配120Hz重新整理率,256GB儲存空間,12GB RAM,5000mAh長續航...")
                .build();
        messages.add(ChatCompletionMessageParam.ofSystem(systemMsg1));

        // 使用者提問訊息(USER角色)
        ChatCompletionUserMessageParam userMsg1 = ChatCompletionUserMessageParam.builder()
                .content("請總結文章內容")
                .build();
        messages.add(ChatCompletionMessageParam.ofUser(userMsg1));

        // 構造第一輪請求並處理異常
        ChatCompletion completion1;
        try {
            completion1 = client.chat().completions().create(
                    ChatCompletionCreateParams.builder()
                            .model("qwen-long")
                            .messages(messages)
                            .build()
            );
        } catch (Exception e) {
            System.err.println("錯誤資訊:" + e.getMessage());
            System.err.println("請參考文檔:https://www.alibabacloud.com/help/zh/model-studio/error-code");
            e.printStackTrace(); 
            return; 
        }

        // 第一輪響應
        String firstResponse = completion1 != null ? completion1.choices().get(0).message().content().orElse("") : "";
        System.out.println("第一輪響應:" + firstResponse);

        // 構造AssistantMessage
        ChatCompletionAssistantMessageParam assistantMsg = ChatCompletionAssistantMessageParam.builder()
                .content(firstResponse)
                .build();
        messages.add(ChatCompletionMessageParam.ofAssistant(assistantMsg));

        // 第二輪傳入內容
        ChatCompletionSystemMessageParam systemMsg2 = ChatCompletionSystemMessageParam.builder()
                .content("星塵S9 Pro —— 創新視覺盛宴:突破性6.9英寸1440 x 3088像素屏下網路攝影機設計,帶來無界視覺享受...")
                .build();
        messages.add(ChatCompletionMessageParam.ofSystem(systemMsg2));

        // 第二輪使用者提問(USER角色)
        ChatCompletionUserMessageParam userMsg2 = ChatCompletionUserMessageParam.builder()
                .content("請對比兩篇描述的結構差異")
                .build();
        messages.add(ChatCompletionMessageParam.ofUser(userMsg2));

        // 所有程式碼範例均採用流式輸出,以清晰和直觀地展示模型輸出過程。如果您希望查看非流式輸出的案例,請參見https://www.alibabacloud.com/help/zh/model-studio/text-generation
        StringBuilder fullResponse = new StringBuilder();
        try (StreamResponse<ChatCompletionChunk> streamResponse = client.chat().completions().createStreaming(
                ChatCompletionCreateParams.builder()
                        .model("qwen-long")
                        .messages(messages)
                        .build())) {

            streamResponse.stream().forEach(chunk -> {
                String content = chunk.choices().get(0).delta().content().orElse("");
                if (!content.isEmpty()) {
                    fullResponse.append(content);
                }
            });
            System.out.println("\n最終響應:");
            System.out.println(fullResponse.toString().trim());
        } catch (Exception e) {
            System.err.println("錯誤資訊:" + e.getMessage());
            System.err.println("請參考文檔:https://www.alibabacloud.com/help/zh/model-studio/error-code");
        }
    }
}

curl

curl --location 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
    "model": "qwen-long",
    "messages": [
            {"role": "system","content": "You are a helpful assistant."},
            {"role": "system","content": "阿里雲百鍊X1 —— 暢享極致視界:搭載6.7英寸1440 x 3200像素超清螢幕,搭配120Hz重新整理率..."},
            {"role": "user","content": "這篇文章講了什嗎?"},
            {"role": "system","content": "星塵S9 Pro —— 創新視覺盛宴:突破性6.9英寸1440 x 3088像素屏下網路攝影機設計,帶來無界視覺享受..."},
            {"role": "user","content": "這兩篇文章討論的產品有什麼異同點"}
        ],
    "stream": true,
    "stream_options": {
        "include_usage": true
    }
}'

模型定價

模型名稱

版本

上下文長度

最大輸入

最大輸出

輸入成本

輸出成本

(Token數)

(每百萬Token)

qwen-long-latest

始終與最新快照版能力相同

最新版

10,000,000

10,000,000

32,768

$0.072

$0.287

qwen-long-2025-01-25

又稱qwen-long-0125

快照版

常見問題

  1. Qwen-Long模型是否支援批量提交任務?

    是的,Qwen-Long相容 OpenAI Batch 介面並按照即時調用費用的 50% 來進行計費出賬。該介面支援以檔案方式批量提交任務,任務會以非同步形式執行,並在完成或達到最長等待時間時返回結果。

  2. 通過OpenAI檔案相容介面上傳檔案後,檔案將被儲存在何處?

    所有通過OpenAI檔案相容介面上傳的檔案均將被儲存在當前阿里雲帳號下的阿里雲百鍊儲存空間且不會產生任何費用,關於所上傳檔案的資訊查詢與管理請參考OpenAI檔案介面

  3. qwen-long-2025-01-25 是什嗎?

    這是一個版本快照標識。它代表模型在某個時間點的功能和效能凍結版本,提供比 latest 版更高的穩定性。它不代表到期日。

  4. 如何確定檔案已經解析完成?

    擷取 file-id 後,可以嘗試使用該 file-id 與模型進行對話。若檔案尚未解析完成,系統將返回錯誤碼 400,並提示“File parsing in progress, please try again later.”;若模型調用成功並返回了回複內容,則表示檔案已解析完成。

  5. 如何確保模型輸出標準格式的 JSON 字串?

    qwen-long及其所有快照版本均支援結構化輸出功能。可以通過指定一個JSON Schema,使模型按照定義的結構以合法的JSON格式返回。

API參考

關於Qwen-Long模型的輸入與輸出參數,請參考通義千問API詳情

錯誤碼

如果模型調用失敗並返回報錯資訊,請參見錯誤資訊進行解決。

限制

  • SDK 依賴:

    • 檔案上傳、刪除、查詢等管理操作必須使用 OpenAI 相容 SDK。

    • 模型調用可使用 OpenAI 相容 SDK 或 Dashscope SDK。

  • 檔案上傳:

    • 支援格式:TXT, DOCX, PDF, XLSX, EPUB, MOBI, MD, CSV, JSON, BMP, PNG, JPG/JPEG, GIF。

    • 檔案大小:圖片格式檔案上限 20MB,其他格式檔案上限 150MB。

    • 賬戶配額:單個賬戶最多上傳 1 萬個檔案,總大小不超過 100GB。當檔案數量或總大小達到任一上限時,新的檔案上傳請求將會失敗。請先參考OpenAI相容-File,刪除不再需要的檔案以釋放配額,然後才能繼續上傳。

    • 儲存有效期間:當前暫無有效期間限制。

  • API 輸入:

    • 通過 file-id 引用時,單次請求最多引用 100 個檔案。總上下文長度上限為 1000 萬 Token。

    • 直接在 usersystem 訊息中輸入純文字時,單條訊息內容(非 file-id)限制在 9,000 Token 以內。

  • API 輸出:

    • 最大輸出長度為 32,768 Token。

  • 檔案分享權限設定:

    • file-id 僅在產生它的阿里雲主帳號內有效,不支援跨帳號或通過 RAM 使用者 API Key 調用。

  • 限流:關於模型的限流條件,請參見限流