Model bahasa besar standar gagal memproses dokumen teks yang sangat panjang karena keterbatasan jendela konteks. Qwen-Long menyediakan jendela konteks hingga 10 juta token dan memproses data berskala besar melalui mekanisme unggah dan referensi file.
Dokumen ini hanya berlaku untuk wilayah "China (Beijing)". Untuk menggunakan model ini, Anda harus menggunakan API key dari wilayah "China (Beijing)".
Cara kerja
Pemrosesan dokumen panjang dengan Qwen-Long terdiri dari dua langkah: unggah file dan panggil API.
Unggah dan parsing file:
Unggah file menggunakan API. Untuk informasi lebih lanjut mengenai format yang didukung dan batas ukuran, lihat Format yang Didukung.
Setelah unggah berhasil, sistem mengembalikan unique
file-iduntuk akun Anda dan mulai melakukan parsing file tersebut. Unggah, penyimpanan, dan parsing file tidak dikenai biaya.
Panggilan API dan penagihan:
Saat memanggil model, referensikan satu atau beberapa
file-iddalam pesansystem.Model melakukan inferensi berdasarkan konten teks yang terkait dengan
file-id.Jumlah token dari konten file yang direferensikan termasuk dalam input tokens untuk setiap panggilan API.
Mekanisme ini menghindari transfer file besar pada setiap permintaan, tetapi perlu diperhatikan implikasi penagihannya.
Memulai
Prasyarat
Anda telah mendapatkan dan mengonfigurasi API key serta mengonfigurasi API key sebagai variabel lingkungan.
Jika Anda melakukan panggilan menggunakan SDK, Anda juga harus menginstal OpenAI SDK.
Unggah dokumen
Contoh ini menggunakan file Bailian Phones Specifications.docx. Untuk mendapatkan file-id, unggah file ke storage space aman di Model Studio menggunakan antarmuka file yang kompatibel dengan OpenAI. Untuk parameter dan metode pemanggilan API unggah file, lihat Kompatibel dengan OpenAI - File.
Python
import os
from pathlib import Path
from openai import OpenAI
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"), # Jika Anda belum mengonfigurasi variabel lingkungan, ganti kunci ini dengan API key Anda di sini.
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", # Masukkan URL dasar layanan DashScope.
)
file_object = client.files.create(file=Path("Bailian Phones Specifications.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) {
// Buat klien dan gunakan API key dari variabel lingkungan.
OpenAIClient client = OpenAIOkHttpClient.builder()
// Jika tidak ada variabel lingkungan yang diatur, ganti baris berikut dengan: .apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.baseUrl("https://dashscope.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/Bailian Phones Specifications.docx");
// Buat parameter unggah file.
FileCreateParams fileParams = FileCreateParams.builder()
.file(filePath)
.purpose(FilePurpose.of("file-extract"))
.build();
// Unggah file dan cetak ID file-nya.
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=@"Bailian Phones Specifications.docx"' \
--form 'purpose="file-extract"'Jalankan kode untuk mendapatkan file-id dari file yang diunggah.
Kirim informasi dan chat menggunakan file ID
Sisipkan file-id yang diperoleh ke dalam pesan system. Anda dapat menggunakan pesan system pertama untuk menetapkan role model, pesan system berikutnya untuk mengirimkan file-id, dan pesan user untuk mengajukan pertanyaan spesifik tentang dokumen tersebut.
Dokumen yang lebih panjang mungkin memerlukan waktu parsing lebih lama. Tunggu hingga parsing selesai sebelum melakukan panggilan API.
Python
import os
from openai import OpenAI, BadRequestError
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"), # Jika Anda belum mengonfigurasi variabel lingkungan, ganti kunci ini dengan API key Anda di sini.
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", # Masukkan URL dasar layanan DashScope.
)
try:
# Inisialisasi daftar pesan.
completion = client.chat.completions.create(
model="qwen-long",
messages=[
{'role': 'system', 'content': 'You are a helpful assistant.'},
# Ganti {FILE_ID} dengan file ID yang digunakan dalam skenario chat Anda.
{'role': 'system', 'content': f'fileid://{FILE_ID}'},
{'role': 'user', 'content': 'What is this article about?'}
],
# 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}
)
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())
# Dapatkan penggunaan token
if chunk.usage:
print(f"Total tokens: {chunk.usage.total_tokens}")
print(full_content)
except BadRequestError as e:
print(f"Error message: {e}")
print("Untuk informasi lebih lanjut, lihat https://www.alibabacloud.com/help/en/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) {
// Buat klien dan gunakan API key dari variabel lingkungan.
OpenAIClient client = OpenAIOkHttpClient.builder()
// Jika tidak ada variabel lingkungan yang diatur, ganti baris berikut dengan: .apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.baseUrl("https://dashscope.aliyuncs.com/compatible-mode/v1")
.build();
// Buat permintaan chat.
ChatCompletionCreateParams chatParams = ChatCompletionCreateParams.builder()
.addSystemMessage("You are a helpful assistant.")
//Ganti {FILE_ID} dengan file ID yang digunakan dalam skenario chat Anda.
.addSystemMessage("fileid://{FILE_ID}")
.addUserMessage("What is this article about?")
.model("qwen-long")
.build();
StringBuilder fullResponse = new StringBuilder();
// 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.
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 message: " + e.getMessage());
System.err.println("Untuk informasi lebih lanjut, lihat https://www.alibabacloud.com/help/en/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": "What is this article about?"}
],
"stream": true,
"stream_options": {
"include_usage": true
}
}'Kirim beberapa dokumen
Anda dapat mengirimkan beberapa file-id dalam satu pesan system untuk memproses beberapa dokumen dalam satu permintaan. Anda juga dapat menambahkan pesan system baru ke dalam array messages untuk menyertakan dokumen tambahan.
Kirim beberapa dokumen
Python
import os
from openai import OpenAI, BadRequestError
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"), # Jika Anda belum mengonfigurasi variabel lingkungan, ganti kunci ini dengan API key Anda di sini.
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", # Masukkan URL dasar layanan DashScope.
)
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 skenario chat Anda.
{'role': 'system', 'content': f"fileid://{FILE_ID1},fileid://{FILE_ID2}"},
{'role': 'user', 'content': 'What are these articles about?'}
],
# 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}
)
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)
except BadRequestError as e:
print(f"Error message: {e}")
print("Untuk informasi lebih lanjut, lihat https://www.alibabacloud.com/help/en/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) {
// Buat klien dan gunakan API key dari variabel lingkungan.
OpenAIClient client = OpenAIOkHttpClient.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.baseUrl("https://dashscope.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 skenario chat 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 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.
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 message: " + e.getMessage());
System.err.println("Untuk informasi lebih lanjut, lihat https://www.alibabacloud.com/help/en/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": "What are these two articles about?"}
],
"stream": true,
"stream_options": {
"include_usage": true
}
}'Tambahkan dokumen
Python
import os
from openai import OpenAI, BadRequestError
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"), # Jika Anda belum mengonfigurasi variabel lingkungan, ganti kunci ini dengan API key Anda di sini.
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", # Masukkan URL dasar layanan DashScope.
)
# Inisialisasi daftar pesan.
messages = [
{'role': 'system', 'content': 'You are a helpful assistant.'},
# Ganti {FILE_ID1} dengan file ID yang digunakan dalam skenario chat 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 respons putaran pertama, atur stream ke True, tambahkan setiap segmen output, dan gunakan string gabungan tersebut 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 message: {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 file ID dokumen yang ditambahkan ke messages.
# Ganti {FILE_ID2} dengan file ID yang digunakan dalam skenario chat Anda.
system_message = {'role': 'system', 'content': f'fileid://{FILE_ID2}'}
messages.append(system_message)
# Tambahkan pertanyaan user.
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())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();
// 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 skenario chat Anda.
ChatCompletionSystemMessageParam systemMsg1 = ChatCompletionSystemMessageParam.builder()
.content("fileid://{FILE_ID1}")
.build();
messages.add(ChatCompletionMessageParam.ofSystem(systemMsg1));
// Pesan pertanyaan user (role USER).
ChatCompletionUserMessageParam userMsg1 = ChatCompletionUserMessageParam.builder()
.content("Summarize the article's 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 the error code reference 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 skenario chat Anda.
ChatCompletionSystemMessageParam systemMsg2 = ChatCompletionSystemMessageParam.builder()
.content("fileid://{FILE_ID2}")
.build();
messages.add(ChatCompletionMessageParam.ofSystem(systemMsg2));
// Pertanyaan user putaran kedua (role USER).
ChatCompletionUserMessageParam userMsg2 = ChatCompletionUserMessageParam.builder()
.content("Compare the structural differences between the two articles.")
.build();
messages.add(ChatCompletionMessageParam.ofUser(userMsg2));
// 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.
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 message: " + e.getMessage());
System.err.println("Untuk informasi lebih lanjut, lihat https://www.alibabacloud.com/help/en/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": "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 meneruskan informasi dokumen menggunakan file-id, Anda dapat meneruskan konten dokumen secara langsung sebagai string. Untuk mencegah model mengacaukan pengaturan role dengan konten dokumen, tambahkan informasi pengaturan role ke pesan pertama dalam array messages.
Karena batas ukuran badan permintaan panggilan API, Anda harus menggunakan file ID untuk meneruskan konten teks yang melebihi 1 juta token.
Contoh sederhana
Anda dapat memasukkan konten dokumen langsung di pesan sistem.
Python
import os
from openai import OpenAI
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"), # Jika Anda belum mengonfigurasi variabel lingkungan, ganti kunci ini dengan Kunci API Anda di sini.
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", # Masukkan URL dasar layanan DashScope.
)
# Inisialisasi daftar messages.
completion = client.chat.completions.create(
model="qwen-long",
messages=[
{'role': 'system', 'content': 'You are a helpful assistant.'},
{'role': 'system', 'content': 'Model Studio Phone Product Introduction Model Studio X1 ——————Enjoy an ultimate visual experience: equipped with a 6.7-inch 1440 x 3200 pixel ultra-clear screen...'},
{'role': 'user', 'content': 'What is this article about?'}
],
# Semua contoh kode menggunakan keluaran streaming untuk menampilkan 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}
)
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)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) {
// Buat klien dan gunakan Kunci API dari variabel lingkungan.
OpenAIClient client = OpenAIOkHttpClient.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.baseUrl("https://dashscope.aliyuncs.com/compatible-mode/v1")
.build();
// Buat permintaan chat.
ChatCompletionCreateParams chatParams = ChatCompletionCreateParams.builder()
.addSystemMessage("You are a helpful assistant.")
.addSystemMessage("Model Studio Phone Product Introduction Model Studio X1 ——————Enjoy an ultimate visual experience: equipped with a 6.7-inch 1440 x 3200 pixel ultra-clear screen...")
.addUserMessage("What is this article about?")
.model("qwen-long")
.build();
StringBuilder fullResponse = new StringBuilder();
// Semua contoh kode menggunakan keluaran streaming untuk menampilkan proses output model secara jelas dan intuitif. Untuk contoh output 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 message: " + e.getMessage());
System.err.println("Untuk informasi lebih lanjut, lihat https://www.alibabacloud.com/help/en/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": "Model Studio X1 - Enjoy an ultimate visual experience: equipped with a 6.7-inch 1440 x 3200 pixel ultra-clear screen with a 120Hz refresh rate..."},
{"role": "user","content": "What is this article about?"}
],
"stream": true,
"stream_options": {
"include_usage": true
}
}'Teruskan beberapa dokumen
Saat Anda perlu meneruskan beberapa dokumen dalam satu giliran percakapan, tempatkan konten setiap dokumen dalam pesan sistem terpisah.
Python
import os
from openai import OpenAI
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"), # Jika Anda belum mengonfigurasi variabel lingkungan, ganti kunci ini dengan Kunci API Anda di sini.
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", # Masukkan URL dasar layanan DashScope.
)
# Inisialisasi daftar messages.
completion = client.chat.completions.create(
model="qwen-long",
messages=[
{'role': 'system', 'content': 'You are a helpful assistant.'},
{'role': 'system', 'content': 'Model Studio X1-Enjoy an ultimate visual experience: equipped with a 6.7-inch 1440 x 3200 pixel ultra-clear screen with a 120Hz refresh rate...'},
{'role': 'system', 'content': 'Stardust S9 Pro - An innovative visual feast: a groundbreaking 6.9-inch 1440 x 3088 pixel under-screen 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 menampilkan 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}
)
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)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) {
// Buat klien dan gunakan Kunci API dari variabel lingkungan.
OpenAIClient client = OpenAIOkHttpClient.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.baseUrl("https://dashscope.aliyuncs.com/compatible-mode/v1")
.build();
// Buat permintaan chat.
ChatCompletionCreateParams chatParams = ChatCompletionCreateParams.builder()
.addSystemMessage("You are a helpful assistant.")
.addSystemMessage("Model Studio Phone Product Introduction Model Studio X1 - Enjoy an ultimate visual experience: equipped with a 6.7-inch 1440 x 3200 pixel ultra-clear screen...")
.addSystemMessage("Stardust S9 Pro - An innovative visual feast: a groundbreaking 6.9-inch 1440 x 3088 pixel under-screen 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 kode menggunakan keluaran streaming untuk menampilkan proses output model secara jelas dan intuitif. Untuk contoh output 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 message: " + e.getMessage());
System.err.println("Untuk informasi lebih lanjut, lihat https://www.alibabacloud.com/help/en/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": "Model Studio X1 - Enjoy an ultimate visual experience: equipped with a 6.7-inch 1440 x 3200 pixel ultra-clear screen with a 120Hz refresh rate..."},
{"role": "system","content": "Stardust S9 Pro - An innovative visual feast: a groundbreaking 6.9-inch 1440 x 3088 pixel under-screen 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
Untuk menambahkan informasi dokumen baru selama interaksi dengan model, tambahkan konten dokumen baru ke pesan sistem dalam array messages.
Python
import os
from openai import OpenAI, BadRequestError
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"), # Jika Anda belum mengonfigurasi variabel lingkungan, ganti kunci ini dengan Kunci API Anda di sini.
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", # Masukkan URL dasar layanan DashScope.
)
# Inisialisasi daftar messages.
messages = [
{'role': 'system', 'content': 'You are a helpful assistant.'},
{'role': 'system', 'content': 'Model Studio X1 - Enjoy an ultimate visual experience: equipped with a 6.7-inch 1440 x 3200 pixel ultra-clear screen with a 120Hz refresh rate...'},
{'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 melakukan streaming respons putaran pertama, atur stream ke True, tambahkan setiap segmen output, lalu 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 message: {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 yang ditambahkan ke messages.
system_message = {
'role': 'system',
'content': 'Stardust S9 Pro - An innovative visual feast: a groundbreaking 6.9-inch 1440 x 3088 pixel under-screen camera design for a borderless 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 menampilkan 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())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();
// Inisialisasi daftar messages.
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));
// Teruskan konten pertama.
ChatCompletionSystemMessageParam systemMsg1 = ChatCompletionSystemMessageParam.builder()
.content("Model Studio X1 - Enjoy an ultimate visual experience: equipped with a 6.7-inch 1440 x 3200 pixel ultra-clear screen, a 120Hz refresh rate, 256 GB storage, 12 GB RAM, and a 5000 mAh long-life battery...")
.build();
messages.add(ChatCompletionMessageParam.ofSystem(systemMsg1));
// Pesan pertanyaan pengguna (role USER).
ChatCompletionUserMessageParam userMsg1 = ChatCompletionUserMessageParam.builder()
.content("Summarize the article's content.")
.build();
messages.add(ChatCompletionMessageParam.ofUser(userMsg1));
// Buat permintaan putaran pertama dan tangani pengecualian.
ChatCompletion completion1;
try {
completion1 = client.chat().completions().create(
ChatCompletionCreateParams.builder()
.model("qwen-long")
.messages(messages)
.build()
);
} catch (Exception e) {
System.err.println("Error message: " + 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));
// Teruskan konten kedua.
ChatCompletionSystemMessageParam systemMsg2 = ChatCompletionSystemMessageParam.builder()
.content("Stardust S9 Pro - An innovative visual feast: a groundbreaking 6.9-inch 1440 x 3088 pixel under-screen camera design for a borderless visual experience...")
.build();
messages.add(ChatCompletionMessageParam.ofSystem(systemMsg2));
// Pertanyaan pengguna putaran kedua (role USER).
ChatCompletionUserMessageParam userMsg2 = ChatCompletionUserMessageParam.builder()
.content("Compare the structural differences between the two descriptions.")
.build();
messages.add(ChatCompletionMessageParam.ofUser(userMsg2));
// Semua contoh kode menggunakan keluaran streaming untuk menampilkan proses output model secara jelas dan intuitif. Untuk contoh output 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 message: " + e.getMessage());
System.err.println("Untuk informasi lebih lanjut, lihat https://www.alibabacloud.com/help/en/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": "Model Studio X1 - Enjoy an ultimate visual experience: equipped with a 6.7-inch 1440 x 3200 pixel ultra-clear screen with a 120Hz refresh rate..."},
{"role": "user","content": "What is this article about?"},
{"role": "system","content": "Stardust S9 Pro - An innovative visual feast: a groundbreaking 6.9-inch 1440 x 3088 pixel under-screen camera design for a borderless 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
Model | Version | Context window | Max input | Max output | Input cost | Output cost |
(Tokens) | (Million tokens) | |||||
qwen-long-latest Selalu memiliki kemampuan yang sama dengan versi snapshot terbaru. | Latest | 10.000.000 | 10.000.000 | 32.768 | $0,072 | $0,287 |
qwen-long-2025-01-25 Juga dikenal sebagai qwen-long-0125 | Snapshot | |||||
FAQ
Apakah Qwen-Long mendukung pengiriman tugas Batch?
Ya, didukung. Qwen-Long kompatibel dengan OpenAI Batch API, yang memungkinkan Anda mengirimkan tugas Batch menggunakan file. Tugas-tugas tersebut dieksekusi secara asinkron dan dikenai biaya sebesar 50% dari biaya panggilan real-time. Hasilnya dikembalikan setelah tugas selesai atau waktu tunggu maksimum tercapai.
Di mana file disimpan setelah diunggah menggunakan OpenAI-compatible file API?
File yang Anda unggah menggunakan OpenAI-compatible file API disimpan ke penyimpanan Model Studio dalam Akun Alibaba Cloud Anda tanpa biaya tambahan. Untuk informasi tentang cara melakukan kueri dan mengelola file yang telah diunggah, lihat OpenAI file API.
Apa itu
qwen-long-2025-01-25?Ini adalah pengenal Snapshot versi. Pengenal ini merepresentasikan versi model yang fitur dan performanya telah dibekukan pada titik waktu tertentu. Versi ini memberikan stabilitas lebih tinggi dibandingkan versi terbaru dan bukan merupakan tanggal kedaluwarsa.
Bagaimana cara memastikan bahwa suatu file telah selesai diurai?
Setelah Anda memperoleh
file-id, Anda dapat memulai percakapan dengan model menggunakanfile-idtersebut. Jika file masih dalam proses penguraian, sistem akan mengembalikan kode kesalahan 400 dengan pesan "File parsing in progress, please try again later." Jika panggilan model berhasil dan mengembalikan respons, hal ini menunjukkan bahwa file telah berhasil diurai.Bagaimana cara membatasi output model agar sesuai dengan struktur JSON standar?
qwen-longdan semua Snapshot-nya mendukung Structured output. Anda dapat menentukan JSON Schema untuk membatasi model agar mengembalikan respons JSON yang valid sesuai struktur yang telah ditentukan.
Referensi API
Untuk parameter input dan output Qwen-Long, lihat Qwen API reference.
Kode error
Jika panggilan gagal, lihat Error messages untuk troubleshooting.
Batasan
Dependensi SDK:
Operasi manajemen, seperti upload file, penghapusan, dan kueri, harus dilakukan menggunakan SDK yang kompatibel dengan OpenAI.
Untuk pemanggilan model, Anda dapat menggunakan SDK yang kompatibel dengan OpenAI atau SDK Dashscope.
Upload file:
Format yang didukung: TXT, DOCX, PDF, XLSX, EPUB, MOBI, MD, CSV, JSON, BMP, PNG, JPG/JPEG, dan GIF.
Ukuran maksimum file adalah 20 MB untuk citra dan 150 MB untuk format file lainnya.
Kuota akun: Satu akun dapat mengupload maksimal 10.000 file dengan ukuran total hingga 100 GB. Jika Anda mencapai salah satu batas tersebut, permintaan upload baru akan gagal. Untuk melepaskan kuota, Anda harus menghapus file yang tidak diperlukan. Untuk informasi selengkapnya, lihat OpenAI compatible - File.
Masa berlaku penyimpanan: Saat ini tidak ada batasan.
Input API:
Saat Anda mereferensikan file menggunakan
file-id, satu permintaan dapat mereferensikan maksimal 100 file. Panjang konteks total dibatasi hingga 10 juta token.Saat Anda memasukkan teks biasa secara langsung dalam pesan
useratausystem, konten dari satu pesan (bukanfile-id) dibatasi hingga 9.000 token.
Output API:
Panjang output maksimum adalah 32.768 token.
Berbagi file:
file-idhanya berlaku untuk Akun Alibaba Cloud yang menghasilkannya. ID tersebut tidak dapat digunakan untuk panggilan cross-account atau untuk panggilan yang dilakukan menggunakan kunci API dari RAM user.
Pembatasan laju: Untuk informasi selengkapnya mengenai batas laju untuk model ini, lihat Rate limits.