Qwen-Long menangani dokumen hingga 10 juta token melalui mekanisme unggah dan referensi file, mengatasi batasan konteks model standar.
CatatanDokumen ini hanya berlaku untuk wilayah Tiongkok daratan (Beijing). Untuk menggunakan model ini, Anda harus menggunakan API key dariTiongkok daratan (Beijing).
Cara menggunakan
Gunakan Qwen-Long dalam dua langkah: unggah file, lalu panggil API.
-
Pengunggahan dan Penguraian File:
- Unggah file menggunakan API. Untuk detail format file yang didukung dan batas ukuran, lihat Format yang Didukung.
- Setelah unggahan berhasil, sistem mengembalikan unique
file-iduntuk akun Anda dan mulai mengurai. Tidak ada biaya yang dikenakan untuk unggah, penyimpanan, atau penguraian file.
-
Pemanggilan API dan Penagihan:
- Saat memanggil model, referensikan satu atau beberapa
file-iddalam pesansystem. - Model melakukan inferensi berdasarkan konten teks yang terkait dengan
file-id. - Untuk setiap pemanggilan API, jumlah token dalam konten file yang direferensikan dihitung sebagai input tokens untuk permintaan tersebut.
- Saat memanggil model, referensikan satu atau beberapa
Hal ini menghindari transfer file besar pada setiap permintaan, tetapi perlu diperhatikan bahwa token file ditagih per pemanggilan API.
Mulai
Prasyarat
- Dapatkan API key dan konfigurasikan sebagai variabel lingkungan.
- Untuk memanggil model melalui SDK, instal OpenAI SDK.
Unggah dokumen
Contoh ini mengunggah Model_Studio_Phone_Product_Introduction.docx ke penyimpanan aman Model Studio melalui antarmuka kompatibel OpenAI dan mendapatkan file-id. Lihat dokumentasi API untuk parameter unggah.
import os
from pathlib import Path
from openai import OpenAI
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"), # Jika belum dikonfigurasi, ganti dengan API key Anda.
# URL berikut untuk wilayah Tiongkok (Beijing). Ganti {WorkspaceId} dengan ID Workspace Anda. URL berbeda-beda per wilayah.
base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
file_object = client.files.create(file=Path("Model_Studio_Phone_Product_Introduction.docx"), purpose="file-extract")
print(file_object.id)
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) {
// Buat klien dan gunakan API key dari variabel lingkungan.
OpenAIClient client = OpenAIOkHttpClient.builder()
// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan: .apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// URL berikut untuk wilayah Tiongkok (Beijing). Ganti {WorkspaceId} dengan ID Workspace Anda. URL berbeda-beda per wilayah.
.baseUrl("https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1")
.build();
// Atur path file. Sesuaikan path dan nama file sesuai kebutuhan.
Path filePath = Paths.get("src/main/java/org/example/Model_Studio_Phone_Product_Introduction.docx");
// Buat parameter unggah file.
FileCreateParams fileParams = FileCreateParams.builder()
.file(filePath)
.purpose(FilePurpose.of("file-extract"))
.build();
// Unggah file dan cetak file-id.
FileObject fileObject = client.files().create(fileParams);
System.out.println(fileObject.id());
}
}
# URL berikut untuk wilayah Tiongkok (Beijing). Ganti {WorkspaceId} dengan ID Workspace Anda. URL berbeda-beda per wilayah.
curl --location --request POST 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/files' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--form 'file=@"Alibaba Cloud Model Studio Phone Series Product Introduction.docx"' \
--form 'purpose="file-extract"'
Jalankan kode untuk mendapatkan file-id dari file yang diunggah.
Teruskan informasi dan chat menggunakan file ID
Teruskan file-id dalam pesan system: pesan pertama mendefinisikan role, pesan kedua berisi file-id, lalu tambahkan pertanyaan pengguna.
Dokumen yang lebih panjang memerlukan waktu penguraian lebih lama. Tunggu hingga penguraian selesai sebelum memanggil.
import os
from openai import OpenAI, BadRequestError
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"), # Jika belum dikonfigurasi, ganti dengan API key Anda.
# Endpoint untuk wilayah Tiongkok (Beijing). Ganti {WorkspaceId} dengan ID Workspace Anda. URL berbeda-beda per wilayah.
base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
try:
# Inisialisasi daftar pesan.
completion = client.chat.completions.create(
model="qwen-long",
messages=[
# sys1: Definisi role.
{'role': 'system', 'content': 'You are a helpful assistant.'},
# sys2: Konten dokumen (teks biasa atau file-id).
# Ganti '{FILE_ID}' dengan file-id yang digunakan dalam percakapan Anda.
{'role': 'system', 'content': f'fileid://{FILE_ID}'},
# Saat permintaan mencakup pesan system kedua, konten pesan user dibatasi hingga 9.000 token.
{'role': 'user', 'content': 'What is this article about?'}
],
# Semua contoh menggunakan keluaran streaming untuk menunjukkan proses respons model. Untuk contoh non-streaming, lihat https://www.alibabacloud.com/help/en/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:
# Gabungkan konten output.
full_content += chunk.choices[0].delta.content
print(chunk.model_dump())
# Dapatkan penggunaan token.
if chunk.usage:
print(f"Total tokens: {chunk.usage.total_tokens}")
print(full_content)
except BadRequestError as e:
print(f"Error: {e}")
print("Lihat dokumentasi: https://www.alibabacloud.com/help/en/model-studio/error-code")
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) {
// Buat klien dan gunakan API key dari variabel lingkungan.
OpenAIClient client = OpenAIOkHttpClient.builder()
// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan: .apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// Endpoint untuk wilayah Tiongkok (Beijing). Ganti {WorkspaceId} dengan ID Workspace Anda. URL berbeda-beda per wilayah.
.baseUrl("https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1")
.build();
// Buat permintaan chat.
ChatCompletionCreateParams chatParams = ChatCompletionCreateParams.builder()
//sys1: Definisi role.
.addSystemMessage("You are a helpful assistant.")
//sys2: Konten dokumen (teks biasa atau file-id).
//Ganti '{FILE_ID}' dengan file-id yang digunakan dalam percakapan Anda.
.addSystemMessage("fileid://{FILE_ID}")
//Saat permintaan mencakup pesan system kedua, konten pesan user dibatasi hingga 9.000 token.
.addUserMessage("What is this article about?")
.model("qwen-long")
.build();
StringBuilder fullResponse = new StringBuilder();
// Semua contoh menggunakan keluaran streaming untuk menunjukkan proses respons model. Untuk contoh non-streaming, lihat https://www.alibabacloud.com/help/en/model-studio/text-generation
try (StreamResponse<ChatCompletionChunk> streamResponse = client.chat().completions().createStreaming(chatParams)) {
streamResponse.stream().forEach(chunk -> {
// Cetak dan gabungkan konten setiap 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("Error: " + e.getMessage());
System.err.println("Lihat dokumentasi: https://www.alibabacloud.com/help/en/model-studio/error-code");
}
}
}
# Endpoint untuk wilayah Tiongkok (Beijing). Ganti {WorkspaceId} dengan ID Workspace Anda. URL berbeda-beda per wilayah.
curl --location 'https://{WorkspaceId}.cn-beijing.maas.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": "What is this article about?"}
],
"stream": true,
"stream_options": {
"include_usage": true
}
}'
Teruskan beberapa dokumen
Teruskan beberapa file-id dalam satu pesan system atau tambahkan pesan system terpisah untuk setiap dokumen.
Teruskan beberapa dokumen
import os
from openai import OpenAI, BadRequestError
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"), # Jika belum dikonfigurasi, ganti dengan API key Anda.
# Endpoint untuk wilayah Tiongkok (Beijing). Ganti {WorkspaceId} dengan ID Workspace Anda. URL berbeda-beda per wilayah.
base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
try:
# Inisialisasi daftar pesan.
completion = client.chat.completions.create(
model="qwen-long",
messages=[
{'role': 'system', 'content': 'You are a helpful assistant.'},
# Ganti '{FILE_ID1}' dan '{FILE_ID2}' dengan file-id yang digunakan dalam percakapan Anda.
{'role': 'system', 'content': f"fileid://{FILE_ID1},fileid://{FILE_ID2}"},
{'role': 'user', 'content': 'What are these articles about?'}
],
# Semua contoh menggunakan keluaran streaming untuk menunjukkan proses respons model. Untuk contoh non-streaming, lihat https://www.alibabacloud.com/help/en/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:
# Gabungkan konten output.
full_content += chunk.choices[0].delta.content
print(chunk.model_dump())
print(full_content)
except BadRequestError as e:
print(f"Error: {e}")
print("Lihat dokumentasi: https://www.alibabacloud.com/help/en/model-studio/error-code")
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) {
// Buat klien dan gunakan API key dari variabel lingkungan.
OpenAIClient client = OpenAIOkHttpClient.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// Endpoint untuk wilayah Tiongkok (Beijing). Ganti {WorkspaceId} dengan ID Workspace Anda. URL berbeda-beda per wilayah.
.baseUrl("https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1")
.build();
// Buat permintaan chat.
ChatCompletionCreateParams chatParams = ChatCompletionCreateParams.builder()
.addSystemMessage("You are a helpful assistant.")
//Ganti '{FILE_ID1}' dan '{FILE_ID2}' dengan file-id yang digunakan dalam percakapan Anda.
.addSystemMessage("fileid://{FILE_ID1},fileid://{FILE_ID2}")
.addUserMessage("What are these two articles about?")
.model("qwen-long")
.build();
StringBuilder fullResponse = new StringBuilder();
// Semua contoh menggunakan keluaran streaming untuk menunjukkan proses respons model. Untuk contoh non-streaming, lihat https://www.alibabacloud.com/help/en/model-studio/text-generation
try (StreamResponse<ChatCompletionChunk> streamResponse = client.chat().completions().createStreaming(chatParams)) {
streamResponse.stream().forEach(chunk -> {
// Konten setiap chunk.
System.out.println(chunk);
String content = chunk.choices().get(0).delta().content().orElse("");
if (!content.isEmpty()) {
fullResponse.append(content);
}
});
System.out.println("\nFull response content:");
System.out.println(fullResponse);
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
System.err.println("Lihat dokumentasi: https://www.alibabacloud.com/help/en/model-studio/error-code");
}
}
}
# Endpoint untuk wilayah Tiongkok (Beijing). Ganti {WorkspaceId} dengan ID Workspace Anda. URL berbeda-beda per wilayah.
curl --location 'https://{WorkspaceId}.cn-beijing.maas.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": "What are these two articles about?"}
],
"stream": true,
"stream_options": {
"include_usage": true
}
}'
Tambahkan dokumen
import os
from openai import OpenAI, BadRequestError
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"), # Jika belum dikonfigurasi, ganti dengan API key Anda.
# Endpoint untuk wilayah Tiongkok (Beijing). Ganti {WorkspaceId} dengan ID Workspace Anda. URL berbeda-beda per wilayah.
base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
# Inisialisasi daftar pesan.
messages = [
{'role': 'system', 'content': 'You are a helpful assistant.'},
# Ganti '{FILE_ID1}' dengan file-id yang digunakan dalam percakapan Anda.
{'role': 'system', 'content': f'fileid://{FILE_ID1}'},
{'role': 'user', 'content': 'What is this article about?'}
]
try:
# Respons putaran pertama
completion_1 = client.chat.completions.create(
model="qwen-long",
messages=messages,
stream=False
)
# Cetak respons putaran pertama.
# Untuk streaming: atur stream=True, gabungkan segmen, dan teruskan ke konten assistant_message.
print(f"First-round response: {completion_1.choices[0].message.model_dump()}")
except BadRequestError as e:
print(f"Error: {e}")
print("Lihat dokumentasi: https://www.alibabacloud.com/help/en/model-studio/error-code")
# Buat assistant_message.
assistant_message = {
"role": "assistant",
"content": completion_1.choices[0].message.content}
# Tambahkan assistant_message ke messages.
messages.append(assistant_message)
# Tambahkan file-id dokumen yang ditambahkan ke messages.
# Ganti '{FILE_ID2}' dengan file-id yang digunakan dalam percakapan Anda.
system_message = {'role': 'system', 'content': f'fileid://{FILE_ID2}'}
messages.append(system_message)
# Tambahkan pertanyaan pengguna.
messages.append({'role': 'user', 'content': 'What are the similarities and differences between the methods discussed in these two articles?'})
# Respons setelah menambahkan dokumen.
completion_2 = client.chat.completions.create(
model="qwen-long",
messages=messages,
# Semua contoh kode menggunakan keluaran streaming untuk menunjukkan proses output model secara jelas dan intuitif. Untuk contoh output non-streaming, lihat https://www.alibabacloud.com/help/en/model-studio/text-generation
stream=True,
stream_options={
"include_usage": True
}
)
# Streaming dan cetak respons setelah menambahkan dokumen.
print("Response after appending the document:")
for chunk in completion_2:
print(chunk.model_dump())
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"))
// Endpoint untuk wilayah Tiongkok (Beijing). Ganti {WorkspaceId} dengan ID Workspace Anda. URL berbeda-beda per wilayah.
.baseUrl("https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1")
.build();
// Inisialisasi daftar pesan.
List<ChatCompletionMessageParam> messages = new ArrayList<>();
// Tambahkan informasi untuk pengaturan role.
ChatCompletionSystemMessageParam roleSet = ChatCompletionSystemMessageParam.builder()
.content("You are a helpful assistant.")
.build();
messages.add(ChatCompletionMessageParam.ofSystem(roleSet));
// Ganti '{FILE_ID1}' dengan file-id yang digunakan dalam percakapan Anda.
ChatCompletionSystemMessageParam systemMsg1 = ChatCompletionSystemMessageParam.builder()
.content("fileid://{FILE_ID1}")
.build();
messages.add(ChatCompletionMessageParam.ofSystem(systemMsg1));
// Pesan pertanyaan pengguna (role USER).
ChatCompletionUserMessageParam userMsg1 = ChatCompletionUserMessageParam.builder()
.content("Please summarize the article content.")
.build();
messages.add(ChatCompletionMessageParam.ofUser(userMsg1));
// Buat permintaan putaran pertama dan tangani exception.
ChatCompletion completion1;
try {
completion1 = client.chat().completions().create(
ChatCompletionCreateParams.builder()
.model("qwen-long")
.messages(messages)
.build()
);
} catch (Exception e) {
System.err.println("Request error. See error code page:");
System.err.println("https://www.alibabacloud.com/help/en/model-studio/error-code");
System.err.println("Error details: " + e.getMessage());
e.printStackTrace();
return;
}
// Respons putaran pertama.
String firstResponse = completion1 != null ? completion1.choices().get(0).message().content().orElse("") : "";
System.out.println("First-round response: " + firstResponse);
// Buat AssistantMessage.
ChatCompletionAssistantMessageParam assistantMsg = ChatCompletionAssistantMessageParam.builder()
.content(firstResponse)
.build();
messages.add(ChatCompletionMessageParam.ofAssistant(assistantMsg));
// Ganti '{FILE_ID2}' dengan file-id yang digunakan dalam percakapan Anda.
ChatCompletionSystemMessageParam systemMsg2 = ChatCompletionSystemMessageParam.builder()
.content("fileid://{FILE_ID2}")
.build();
messages.add(ChatCompletionMessageParam.ofSystem(systemMsg2));
// Pertanyaan pengguna putaran kedua (role USER).
ChatCompletionUserMessageParam userMsg2 = ChatCompletionUserMessageParam.builder()
.content("Please compare the structural differences between the two articles.")
.build();
messages.add(ChatCompletionMessageParam.ofUser(userMsg2));
// Semua contoh menggunakan keluaran streaming untuk menunjukkan proses respons model. Untuk contoh non-streaming, lihat https://www.alibabacloud.com/help/en/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("\nFinal response:");
System.out.println(fullResponse.toString().trim());
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
System.err.println("Lihat dokumentasi: https://www.alibabacloud.com/help/en/model-studio/error-code");
}
}
}
# Endpoint untuk wilayah Tiongkok (Beijing). Ganti {WorkspaceId} dengan ID Workspace Anda. URL berbeda-beda per wilayah.
curl --location 'https://{WorkspaceId}.cn-beijing.maas.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": "What is this article about?"},
{"role": "system","content": "fileid://file-fe-xxx2"},
{"role": "user","content": "What are the similarities and differences between the methods discussed in these two articles?"}
],
"stream": true,
"stream_options": {
"include_usage": true
}
}'
Teruskan informasi sebagai teks biasa
Alih-alih menggunakan file-id, teruskan konten dokumen langsung sebagai string. Tambahkan pengaturan role pada pesan pertama untuk menghindari kebingungan dengan konten dokumen.
Jika konten dokumen melebihi 1 juta token, gunakan file ID karena batasan ukuran API.
Contoh sederhana
Anda dapat memasukkan konten dokumen langsung ke System Message.
import os
from openai import OpenAI
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"), # Ganti API key Anda di sini jika belum mengatur variabel lingkungan
# Endpoint untuk wilayah Tiongkok (Beijing). Ganti {WorkspaceId} dengan ID Workspace Anda. URL berbeda-beda per wilayah.
base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
# Inisialisasi daftar pesan
completion = client.chat.completions.create(
model="qwen-long",
messages=[
{'role': 'system', 'content': 'You are a helpful assistant.'},
{'role': 'system', 'content': 'Alibaba Cloud Model Studio smartphone product introduction: Alibaba Cloud Model Studio X1 —————— Enjoy an ultimate visual experience: features a 6.7-inch 1440 x 3200 pixel ultra-clear screen...'},
{'role': 'user', 'content': 'What does the article talk about?'}
],
# Semua contoh kode menggunakan keluaran streaming untuk menunjukkan proses output model secara jelas dan intuitif. Untuk contoh non-streaming, lihat https://www.alibabacloud.com/help/en/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:
# Tambahkan konten output
full_content += chunk.choices[0].delta.content
print(chunk.model_dump())
print(full_content)
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) {
// Buat klien menggunakan API key dari variabel lingkungan
OpenAIClient client = OpenAIOkHttpClient.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// Endpoint untuk wilayah Tiongkok (Beijing). Ganti {WorkspaceId} dengan ID Workspace Anda. URL berbeda-beda per wilayah.
.baseUrl("https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1")
.build();
// Buat permintaan chat
ChatCompletionCreateParams chatParams = ChatCompletionCreateParams.builder()
.addSystemMessage("You are a helpful assistant.")
.addSystemMessage("Alibaba Cloud Model Studio smartphone product introduction: Alibaba Cloud Model Studio X1 —————— Enjoy an ultimate visual experience: features a 6.7-inch 1440 x 3200 pixel ultra-clear screen...")
.addUserMessage("What does this article talk about?")
.model("qwen-long")
.build();
StringBuilder fullResponse = new StringBuilder();
// Semua contoh menggunakan keluaran streaming untuk menunjukkan proses respons model. Untuk contoh non-streaming, lihat https://www.alibabacloud.com/help/en/model-studio/text-generation
try (StreamResponse<ChatCompletionChunk> streamResponse = client.chat().completions().createStreaming(chatParams)) {
streamResponse.stream().forEach(chunk -> {
// Cetak dan tambahkan konten setiap 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("Error: " + e.getMessage());
System.err.println("Untuk informasi lebih lanjut, lihat https://www.alibabacloud.com/help/en/model-studio/error-code");
}
}
}
# Endpoint untuk wilayah Tiongkok (Beijing). Ganti {WorkspaceId} dengan ID Workspace Anda. URL berbeda-beda per wilayah.
curl --location 'https://{WorkspaceId}.cn-beijing.maas.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": "Alibaba Cloud Model Studio X1 —— Enjoy an ultimate visual experience: features a 6.7-inch 1440 x 3200 pixel ultra-clear screen with a 120Hz refresh rate, ..."},
{"role": "user","content": "What does this article talk about?"}
],
"stream": true,
"stream_options": {
"include_usage": true
}
}'
Teruskan beberapa dokumen
Untuk meneruskan beberapa dokumen dalam satu giliran percakapan, tempatkan konten setiap dokumen dalam System Message terpisah.
import os
from openai import OpenAI
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"), # Ganti API key Anda di sini jika belum mengatur variabel lingkungan
# Endpoint untuk wilayah Tiongkok (Beijing). Ganti {WorkspaceId} dengan ID Workspace Anda. URL berbeda-beda per wilayah.
base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
# Inisialisasi daftar pesan
completion = client.chat.completions.create(
model="qwen-long",
messages=[
{'role': 'system', 'content': 'You are a helpful assistant.'},
{'role': 'system', 'content': 'Alibaba Cloud Model Studio X1————Enjoy an ultimate visual experience: features a 6.7-inch 1440 x 3200 pixel ultra-clear screen with a 120Hz refresh rate...'},
{'role': 'system', 'content': 'Stardust S9 Pro —— A revolutionary visual feast: breakthrough 6.9-inch 1440 x 3088 pixel under-display camera design...'},
{'role': 'user', 'content': 'What are the similarities and differences between the products discussed in these two articles?'}
],
# Semua contoh kode menggunakan keluaran streaming untuk menunjukkan proses output model secara jelas dan intuitif. Untuk contoh non-streaming, lihat https://www.alibabacloud.com/help/en/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:
# Tambahkan konten output
full_content += chunk.choices[0].delta.content
print(chunk.model_dump())
print(full_content)
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) {
// Buat klien menggunakan API key dari variabel lingkungan
OpenAIClient client = OpenAIOkHttpClient.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// Endpoint untuk wilayah Tiongkok (Beijing). Ganti {WorkspaceId} dengan ID Workspace Anda. URL berbeda-beda per wilayah.
.baseUrl("https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1")
.build();
// Buat permintaan chat
ChatCompletionCreateParams chatParams = ChatCompletionCreateParams.builder()
.addSystemMessage("You are a helpful assistant.")
.addSystemMessage("Alibaba Cloud Model Studio smartphone product introduction: Alibaba Cloud Model Studio X1 —————— Enjoy an ultimate visual experience: features a 6.7-inch 1440 x 3200 pixel ultra-clear screen...")
.addSystemMessage("Stardust S9 Pro —— A revolutionary visual feast: breakthrough 6.9-inch 1440 x 3088 pixel under-display camera design...")
.addUserMessage("What are the similarities and differences between the products discussed in these two articles?")
.model("qwen-long")
.build();
StringBuilder fullResponse = new StringBuilder();
// Semua contoh menggunakan keluaran streaming untuk menunjukkan proses respons model. Untuk contoh non-streaming, lihat https://www.alibabacloud.com/help/en/model-studio/text-generation
try (StreamResponse<ChatCompletionChunk> streamResponse = client.chat().completions().createStreaming(chatParams)) {
streamResponse.stream().forEach(chunk -> {
// Cetak dan tambahkan konten setiap 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("Error: " + e.getMessage());
System.err.println("Untuk informasi lebih lanjut, lihat https://www.alibabacloud.com/help/en/model-studio/error-code");
}
}
}
# Endpoint untuk wilayah Tiongkok (Beijing). Ganti {WorkspaceId} dengan ID Workspace Anda. URL berbeda-beda per wilayah.
curl --location 'https://{WorkspaceId}.cn-beijing.maas.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": "Alibaba Cloud Model Studio X1 —— Enjoy an ultimate visual experience: features a 6.7-inch 1440 x 3200 pixel ultra-clear screen with a 120Hz refresh rate..."},
{"role": "system","content": "Stardust S9 Pro —— A revolutionary visual feast: breakthrough 6.9-inch 1440 x 3088 pixel under-display camera design..."},
{"role": "user","content": "What are the similarities and differences between the products discussed in these two articles?"}
],
"stream": true,
"stream_options": {
"include_usage": true
}
}'
Tambahkan dokumen
Selama interaksi dengan model, Anda mungkin perlu menambahkan informasi dokumen baru. Untuk melakukannya, tambahkan konten dokumen baru sebagai System Message ke array Messages.
import os
from openai import OpenAI, BadRequestError
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"), # Ganti API key Anda di sini jika belum mengatur variabel lingkungan
# Endpoint untuk wilayah Tiongkok (Beijing). Ganti {WorkspaceId} dengan ID Workspace Anda. URL berbeda-beda per wilayah.
base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
# Inisialisasi daftar pesan
messages = [
{'role': 'system', 'content': 'You are a helpful assistant.'},
{'role': 'system', 'content': 'Alibaba Cloud Model Studio X1 —— Enjoy an ultimate visual experience: features a 6.7-inch 1440 x 3200 pixel ultra-clear screen with a 120Hz refresh rate...'},
{'role': 'user', 'content': 'What does this article talk about?'}
]
try:
# Respons putaran pertama
completion_1 = client.chat.completions.create(
model="qwen-long",
messages=messages,
stream=False
)
# Cetak respons putaran pertama
# Untuk keluaran streaming di putaran pertama, atur stream=True dan gabungkan konten setiap segmen. Teruskan string yang digabungkan sebagai konten saat membuat assistant_message
print(f"First-round response: {completion_1.choices[0].message.model_dump()}")
except BadRequestError as e:
print(f"Error: {e}")
print("Untuk informasi lebih lanjut, lihat https://www.alibabacloud.com/help/en/model-studio/error-code")
# Buat assistant_message
assistant_message = {
"role": "assistant",
"content": completion_1.choices[0].message.content}
# Tambahkan assistant_message ke messages
messages.append(assistant_message)
# Tambahkan konten dokumen baru ke messages
system_message = {
'role': 'system',
'content': 'Stardust S9 Pro —— A revolutionary visual feast: breakthrough 6.9-inch 1440 x 3088 pixel under-display camera design, delivering an immersive visual experience...'}
messages.append(system_message)
# Tambahkan pertanyaan pengguna
messages.append({
'role': 'user',
'content': 'What are the similarities and differences between the products discussed in these two articles?'
})
# Respons setelah menambahkan dokumen
completion_2 = client.chat.completions.create(
model="qwen-long",
messages=messages,
# Semua contoh kode menggunakan keluaran streaming untuk menunjukkan proses output model secara jelas dan intuitif. Untuk contoh non-streaming, lihat https://www.alibabacloud.com/help/en/model-studio/text-generation
stream=True,
stream_options={"include_usage": True}
)
# Streaming dan cetak respons setelah menambahkan dokumen
print("Response after appending the document:")
for chunk in completion_2:
print(chunk.model_dump())
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"))
// Endpoint untuk wilayah Tiongkok (Beijing). Ganti {WorkspaceId} dengan ID Workspace Anda. URL berbeda-beda per wilayah.
.baseUrl("https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1")
.build();
// Inisialisasi daftar pesan
List<ChatCompletionMessageParam> messages = new ArrayList<>();
// Tambahkan informasi pengaturan role
ChatCompletionSystemMessageParam roleSet = ChatCompletionSystemMessageParam.builder()
.content("You are a helpful assistant.")
.build();
messages.add(ChatCompletionMessageParam.ofSystem(roleSet));
// Konten putaran pertama
ChatCompletionSystemMessageParam systemMsg1 = ChatCompletionSystemMessageParam.builder()
.content("Alibaba Cloud Model Studio X1 —— Enjoy an ultimate visual experience: features a 6.7-inch 1440 x 3200 pixel ultra-clear screen with a 120Hz refresh rate, 256GB storage, 12GB RAM, and a 5000mAh long-lasting battery...")
.build();
messages.add(ChatCompletionMessageParam.ofSystem(systemMsg1));
// Pertanyaan pengguna (role USER)
ChatCompletionUserMessageParam userMsg1 = ChatCompletionUserMessageParam.builder()
.content("Please summarize the article content")
.build();
messages.add(ChatCompletionMessageParam.ofUser(userMsg1));
// Buat permintaan putaran pertama dan tangani exception
ChatCompletion completion1;
try {
completion1 = client.chat().completions().create(
ChatCompletionCreateParams.builder()
.model("qwen-long")
.messages(messages)
.build()
);
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
System.err.println("Untuk informasi lebih lanjut, lihat https://www.alibabacloud.com/help/en/model-studio/error-code");
e.printStackTrace();
return;
}
// Respons putaran pertama
String firstResponse = completion1 != null ? completion1.choices().get(0).message().content().orElse("") : "";
System.out.println("First-round response: " + firstResponse);
// Buat AssistantMessage
ChatCompletionAssistantMessageParam assistantMsg = ChatCompletionAssistantMessageParam.builder()
.content(firstResponse)
.build();
messages.add(ChatCompletionMessageParam.ofAssistant(assistantMsg));
// Konten putaran kedua
ChatCompletionSystemMessageParam systemMsg2 = ChatCompletionSystemMessageParam.builder()
.content("Stardust S9 Pro —— A revolutionary visual feast: breakthrough 6.9-inch 1440 x 3088 pixel under-display camera design, delivering an immersive visual experience...")
.build();
messages.add(ChatCompletionMessageParam.ofSystem(systemMsg2));
// Pertanyaan pengguna putaran kedua (role USER)
ChatCompletionUserMessageParam userMsg2 = ChatCompletionUserMessageParam.builder()
.content("Please compare the structural differences between the two descriptions")
.build();
messages.add(ChatCompletionMessageParam.ofUser(userMsg2));
// Semua contoh menggunakan keluaran streaming untuk menunjukkan proses respons model. Untuk contoh non-streaming, lihat https://www.alibabacloud.com/help/en/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("\nFinal response:");
System.out.println(fullResponse.toString().trim());
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
System.err.println("Untuk informasi lebih lanjut, lihat https://www.alibabacloud.com/help/en/model-studio/error-code");
}
}
}
# Endpoint untuk wilayah Tiongkok (Beijing). Ganti {WorkspaceId} dengan ID Workspace Anda. URL berbeda-beda per wilayah.
curl --location 'https://{WorkspaceId}.cn-beijing.maas.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": "Alibaba Cloud Model Studio X1 —— Enjoy an ultimate visual experience: features a 6.7-inch 1440 x 3200 pixel ultra-clear screen with a 120Hz refresh rate..."},
{"role": "user","content": "What does this article talk about?"},
{"role": "system","content": "Stardust S9 Pro —— A revolutionary visual feast: breakthrough 6.9-inch 1440 x 3088 pixel under-display camera design, delivering an immersive visual experience..."},
{"role": "user","content": "What are the similarities and differences between the products discussed in these two articles"}
],
"stream": true,
"stream_options": {
"include_usage": true
}
}'
Harga model
| Nama model | Versi | Panjang konteks | Input maks | Output maks | Biaya input | Biaya output |
|---|---|---|---|---|---|---|
| (Tokens) | (per 1 juta token) | |||||
qwen-long-latest
| Terbaru | 10.000.000 | 10.000.000 | 32.768 | $0,072 | $0,287 |
qwen-long-2025-01-25
| Snapshot | |||||
FAQ
-
Apakah model Qwen-Long mendukung pengiriman pekerjaan batch?
Ya. Qwen-Long mendukung OpenAI Batch API dengan tarif 50% dari panggilan real-time. Kirim pekerjaan batch sebagai file; pekerjaan dijalankan asinkron dan mengembalikan hasil saat selesai atau timeout.
-
Di mana file disimpan setelah diunggah menggunakan OpenAI-compatible file API?
File diunggah ke bucket Model Studio Anda tanpa biaya. Lihat OpenAI File API untuk mengkueri dan mengelola file.
-
Apa itu
qwen-long-2025-01-25?Ini adalah snapshot versi yang dibekukan pada titik waktu tertentu, lebih stabil daripada latest dan tidak memiliki tanggal kedaluwarsa.
-
Bagaimana saya tahu kapan file selesai diurai?
Untuk memeriksa progres penguraian tanpa melakukan panggilan uji coba berulang, kueri status file: panggil antarmuka retrieve file dan periksa bidang
status—processingberarti penguraian masih berlangsung,processedberarti penguraian selesai dan file dapat direferensikan, sedangkanerrormenandakan penguraian gagal. Setelah status menjadiprocessed, Anda dapat memanggil model. Untuk detail selengkapnya, lihat OpenAI File API. Alternatifnya, panggil model langsung denganfile-id: jika penguraian belum selesai, Anda akan menerima error 400: "File parsing in progress, please try again later."; respons sukses menandakan penguraian telah selesai. -
Bagaimana cara memastikan model menghasilkan string JSON dalam format standar?
qwen-longdan semua snapshot-nya mendukung structured output. Tentukan JSON Schema untuk memastikan output JSON valid sesuai struktur yang Anda inginkan.
Referensi API
Lihat Detail API Qwen untuk informasi mengenai parameter input dan output model Qwen-Long.
Kode kesalahan
Jika pemanggilan model gagal dan mengembalikan pesan kesalahan, lihat Kode Kesalahan untuk resolusi.
Batasan
-
Dependensi SDK:
- Operasi file (unggah, hapus, kueri) memerlukan SDK kompatibel OpenAI.
- Panggil model menggunakan SDK kompatibel OpenAI atau Dashscope SDK.
-
Pengunggahan file:
- Format yang didukung: TXT, DOCX, PDF, XLSX, EPUB, MOBI, MD, CSV, JSON, BMP, PNG, JPG/JPEG, dan GIF.
- Ukuran file: Maksimum 20 MB untuk file gambar dan 150 MB untuk format file lainnya.
- Kuota akun: Maksimum 10.000 file atau 100 GB per akun. Unggahan gagal jika salah satu batas tercapai. Hapus file untuk membebaskan kuota. Lihat Kompatibel OpenAI - File.
- Periode penyimpanan: Saat ini, file yang disimpan tidak memiliki batas kedaluwarsa.
-
Input API:
- Pesan system pertama mendefinisikan role. Pesan
systemkedua berisi konten dokumen ataufileid://xxx. Pesanuserberisi kueri. - Saat mereferensikan file menggunakan
file-id, satu permintaan dapat mereferensikan maksimal 100 file. - Dengan dua pesan
system, batas pesanuseradalah 9.000 token. Tidak ada batas jika hanya menggunakan satu pesan system. - Panjang konteks total dibatasi hingga 10 juta token.
- Pesan system pertama mendefinisikan role. Pesan
-
Output API:
- Panjang output maksimum adalah 32.768 token.
-
Berbagi file:
file-idbersifat spesifik akun dan tidak dapat digunakan lintas akun atau dengan kunci API pengguna RAM.
-
Pembatasan kecepatan: Untuk informasi tentang kondisi pembatasan kecepatan model, lihat Pembatasan kecepatan.