標準的な大規模言語モデルは、コンテキストウィンドウの制限により、非常に長いテキストドキュメントを処理することができません。Qwen-Long は、1,000 万トークンのコンテキストウィンドウを提供し、ファイルアップロードとリファレンスの仕組みを使用して大規模なデータを処理します。
このドキュメントは、「中国 (北京)」 リージョンにのみ適用されます。モデルを使用するには、「中国 (北京)」 リージョンの API キーを使用する必要があります。
仕組み
Qwen-Long で長いドキュメントを処理するには、ファイルアップロードと API 呼び出しの 2 つのステップが必要です。
ファイルのアップロードと解析:
API を使用してファイルをアップロードします。サポートされているフォーマットとサイズ制限の詳細については、「サポートされているフォーマット」をご参照ください。
アップロードが成功すると、システムはご利用のアカウントに対して一意の
file-idを返し、ファイルの解析を開始します。ファイルのアップロード、ストレージ、解析は無料です。
API 呼び出しと課金:
モデルを呼び出す際に、
systemメッセージで 1 つ以上のfile-idを参照します。モデルは
file-idに関連付けられたテキストコンテンツに基づいて推論を実行します。参照されたファイルコンテンツのトークン数は、各 API 呼び出しの入力トークンに含まれます。
この仕組みにより、リクエストごとに大きなファイルを転送する必要がなくなりますが、課金への影響にご注意ください。
クイックスタート
前提条件
API キーを取得して設定し、API キーを環境変数として設定していること。
SDK を使用して呼び出しを行う場合は、OpenAI SDK もインストールする必要があります。
ドキュメントのアップロード
この例では、Bailian Phones Specifications.docx ファイルを使用します。file-id を取得するには、OpenAI 互換のファイルインターフェイスを使用して Model Studio 上のセキュアなストレージスペースにファイルをアップロードします。ファイルアップロード API のパラメーターと呼び出しメソッドについては、「OpenAI 互換 - ファイル」をご参照ください。
Python
import os
from pathlib import Path
from openai import OpenAI
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"), # 環境変数を設定していない場合は、ここでキーを API キーに置き換えてください。
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", # DashScope サービスのベース URL を入力します。
)
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) {
// クライアントを作成し、環境変数から API キーを使用します。
OpenAIClient client = OpenAIOkHttpClient.builder()
// 環境変数が設定されていない場合は、次の行を .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/Bailian Phones Specifications.docx");
// ファイルアップロードパラメーターを作成します。
FileCreateParams fileParams = FileCreateParams.builder()
.file(filePath)
.purpose(FilePurpose.of("file-extract"))
.build();
// ファイルをアップロードし、ファイル ID を出力します。
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"'コードを実行して、アップロードされたファイルの file-id を取得します。
file-id を使用した情報の受け渡しとチャット
取得した file-id をシステムメッセージに埋め込みます。最初のシステムメッセージでモデルのロールを設定し、後続のシステムメッセージで file-id を渡し、ユーザーメッセージでドキュメントに関する具体的な質問をすることができます。
ドキュメントが長いほど、解析に時間がかかる場合があります。API を呼び出す前に、解析が完了するまでお待ちください。
Python
import os
from openai import OpenAI, BadRequestError
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"), # 環境変数を設定していない場合は、ここでキーを API キーに置き換えてください。
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", # DashScope サービスのベース URL を入力します。
)
try:
# messages リストを初期化します。
completion = client.chat.completions.create(
model="qwen-long",
messages=[
{'role': 'system', 'content': 'You are a helpful assistant.'},
# {FILE_ID} をチャットシナリオで使用するファイル ID に置き換えます。
{'role': 'system', 'content': f'fileid://{FILE_ID}'},
{'role': 'user', 'content': 'What is this article about?'}
],
# すべてのコード例では、モデルの出力プロセスを明確かつ直感的に示すためにストリーミング出力を使用しています。非ストリーミング出力の例については、https://www.alibabacloud.com/help/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())
# トークンの使用状況を取得します
if chunk.usage:
print(f"Total tokens: {chunk.usage.total_tokens}")
print(full_content)
except BadRequestError as e:
print(f"Error message: {e}")
print("For more information, see https://www.alibabacloud.com/help/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("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} をチャットシナリオで使用するファイル ID に置き換えます。
.addSystemMessage("fileid://{FILE_ID}")
.addUserMessage("What is this article about?")
.model("qwen-long")
.build();
StringBuilder fullResponse = new StringBuilder();
// すべてのコード例では、モデルの出力プロセスを明確かつ直感的に示すためにストリーミング出力を使用しています。非ストリーミング出力の例については、https://www.alibabacloud.com/help/model-studio/text-generation をご参照ください。
try (StreamResponse<ChatCompletionChunk> streamResponse = client.chat().completions().createStreaming(chatParams)) {
streamResponse.stream().forEach(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("For more information, see https://www.alibabacloud.com/help/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
}
}'複数ドキュメントの受け渡し
単一のシステムメッセージで複数の file-id を渡すことで、1 つのリクエストで複数のドキュメントを処理できます。また、messages 配列に新しいシステムメッセージを追加して、追加のドキュメントを含めることもできます。
複数ドキュメントの受け渡し
Python
import os
from openai import OpenAI, BadRequestError
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"), # 環境変数を設定していない場合は、ここでキーを API キーに置き換えてください。
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", # DashScope サービスのベース URL を入力します。
)
try:
# messages リストを初期化します。
completion = client.chat.completions.create(
model="qwen-long",
messages=[
{'role': 'system', 'content': 'You are a helpful assistant.'},
# {FILE_ID1} と {FILE_ID2} をチャットシナリオで使用するファイル ID に置き換えます。
{'role': 'system', 'content': f"fileid://{FILE_ID1},fileid://{FILE_ID2}"},
{'role': 'user', 'content': 'What are these articles about?'}
],
# すべてのコード例では、モデルの出力プロセスを明確かつ直感的に示すためにストリーミング出力を使用しています。非ストリーミング出力の例については、https://www.alibabacloud.com/help/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"Error message: {e}")
print("For more information, see https://www.alibabacloud.com/help/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} をチャットシナリオで使用するファイル ID に置き換えます。
.addSystemMessage("fileid://{FILE_ID1},fileid://{FILE_ID2}")
.addUserMessage("What are these two articles about?")
.model("qwen-long")
.build();
StringBuilder fullResponse = new StringBuilder();
// すべてのコード例では、モデルの出力プロセスを明確かつ直感的に示すためにストリーミング出力を使用しています。非ストリーミング出力の例については、https://www.alibabacloud.com/help/model-studio/text-generation をご参照ください。
try (StreamResponse<ChatCompletionChunk> streamResponse = client.chat().completions().createStreaming(chatParams)) {
streamResponse.stream().forEach(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("For more information, see https://www.alibabacloud.com/help/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
}
}'ドキュメントの追加
Python
import os
from openai import OpenAI, BadRequestError
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"), # 環境変数を設定していない場合は、ここでキーを API キーに置き換えてください。
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", # DashScope サービスのベース URL を入力します。
)
# messages リストを初期化します。
messages = [
{'role': 'system', 'content': 'You are a helpful assistant.'},
# {FILE_ID1} をチャットシナリオで使用するファイル ID に置き換えます。
{'role': 'system', 'content': f'fileid://{FILE_ID1}'},
{'role': 'user', 'content': 'What is this article about?'}
]
try:
# 1巡目の応答。
completion_1 = client.chat.completions.create(
model="qwen-long",
messages=messages,
stream=False
)
# 1巡目の応答を出力します。
# 1巡目の応答をストリーミングするには、stream を True に設定し、各出力セグメントを追加し、assistant_message を構築する際に連結された文字列をコンテンツとして渡します。
print(f"First-round response: {completion_1.choices[0].message.model_dump()}")
except BadRequestError as e:
print(f"Error message: {e}")
print("For more information, see https://www.alibabacloud.com/help/model-studio/error-code.")
# assistant_message を構築します。
assistant_message = {
"role": "assistant",
"content": completion_1.choices[0].message.content}
# assistant_message を messages に追加します。
messages.append(assistant_message)
# 追加されたドキュメントのファイル ID を messages に追加します。
# {FILE_ID2} をチャットシナリオで使用するファイル ID に置き換えます。
system_message = {'role': 'system', 'content': f'fileid://{FILE_ID2}'}
messages.append(system_message)
# ユーザーの質問を追加します。
messages.append({'role': 'user', 'content': 'What are the similarities and differences between the methods discussed in these two articles?'})
# ドキュメント追加後の応答。
completion_2 = client.chat.completions.create(
model="qwen-long",
messages=messages,
# すべてのコード例では、モデルの出力プロセスを明確かつ直感的に示すためにストリーミング出力を使用しています。非ストリーミング出力の例については、https://www.alibabacloud.com/help/model-studio/text-generation をご参照ください。
stream=True,
stream_options={
"include_usage": True
}
)
# ドキュメント追加後の応答をストリーミングして出力します。
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();
// messages リストを初期化します。
List<ChatCompletionMessageParam> messages = new ArrayList<>();
// ロール設定の情報を追加します。
ChatCompletionSystemMessageParam roleSet = ChatCompletionSystemMessageParam.builder()
.content("You are a helpful assistant.")
.build();
messages.add(ChatCompletionMessageParam.ofSystem(roleSet));
// {FILE_ID1} をチャットシナリオで使用するファイル ID に置き換えます。
ChatCompletionSystemMessageParam systemMsg1 = ChatCompletionSystemMessageParam.builder()
.content("fileid://{FILE_ID1}")
.build();
messages.add(ChatCompletionMessageParam.ofSystem(systemMsg1));
// ユーザーの質問メッセージ (USER ロール)。
ChatCompletionUserMessageParam userMsg1 = ChatCompletionUserMessageParam.builder()
.content("Summarize the article's content.")
.build();
messages.add(ChatCompletionMessageParam.ofUser(userMsg1));
// 1巡目のリクエストを構築し、例外を処理します。
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/model-studio/error-code");
System.err.println("Error details: " + e.getMessage());
e.printStackTrace();
return;
}
// 1巡目の応答。
String firstResponse = completion1 != null ? completion1.choices().get(0).message().content().orElse("") : "";
System.out.println("First-round response: " + firstResponse);
// AssistantMessage を構築します。
ChatCompletionAssistantMessageParam assistantMsg = ChatCompletionAssistantMessageParam.builder()
.content(firstResponse)
.build();
messages.add(ChatCompletionMessageParam.ofAssistant(assistantMsg));
// {FILE_ID2} をチャットシナリオで使用するファイル ID に置き換えます。
ChatCompletionSystemMessageParam systemMsg2 = ChatCompletionSystemMessageParam.builder()
.content("fileid://{FILE_ID2}")
.build();
messages.add(ChatCompletionMessageParam.ofSystem(systemMsg2));
// 2巡目のユーザーの質問 (USER ロール)。
ChatCompletionUserMessageParam userMsg2 = ChatCompletionUserMessageParam.builder()
.content("Compare the structural differences between the two articles.")
.build();
messages.add(ChatCompletionMessageParam.ofUser(userMsg2));
// すべてのコード例では、モデルの出力プロセスを明確かつ直感的に示すためにストリーミング出力を使用しています。非ストリーミング出力の例については、https://www.alibabacloud.com/help/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("For more information, see https://www.alibabacloud.com/help/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
}
}'プレーンテキストとしての情報受け渡し
file-id を使用してドキュメント情報を渡す代わりに、ドキュメントのコンテンツを文字列として直接渡すことができます。モデルがロール設定とドキュメントのコンテンツを混同しないように、ロール設定情報を messages 配列の最初のメッセージに追加します。
API 呼び出しリクエストボディのサイズ制限により、100万トークンを超えるテキストコンテンツを渡すには、ファイル ID を使用する必要があります。
簡単な例
ドキュメントのコンテンツをシステムメッセージに直接入力できます。
Python
import os
from openai import OpenAI
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"), # 環境変数を設定していない場合は、ここを API キーに置き換えてください。
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", # DashScope サービスのベース URL を入力します。
)
# 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?'}
],
# すべてのコード例では、モデルの出力プロセスを明確かつ直感的に示すためにストリーミング出力を使用しています。非ストリーミング出力の例については、https://www.alibabacloud.com/help/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("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();
// すべてのコード例では、モデルの出力プロセスを明確かつ直感的に示すためにストリーミング出力を使用しています。非ストリーミング出力の例については、https://www.alibabacloud.com/help/model-studio/text-generation をご参照ください。
try (StreamResponse<ChatCompletionChunk> streamResponse = client.chat().completions().createStreaming(chatParams)) {
streamResponse.stream().forEach(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("For more information, see https://www.alibabacloud.com/help/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
}
}'複数ドキュメントの受け渡し
1回の対話ターンで複数のドキュメントを渡す必要がある場合は、各ドキュメントのコンテンツを個別のシステムメッセージに配置します。
Python
import os
from openai import OpenAI
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"), # 環境変数を設定していない場合は、ここを API キーに置き換えてください。
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", # DashScope サービスのベース URL を入力します。
)
# 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?'}
],
# すべてのコード例では、モデルの出力プロセスを明確かつ直感的に示すためにストリーミング出力を使用しています。非ストリーミング出力の例については、https://www.alibabacloud.com/help/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("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();
// すべてのコード例では、モデルの出力プロセスを明確かつ直感的に示すためにストリーミング出力を使用しています。非ストリーミング出力の例については、https://www.alibabacloud.com/help/model-studio/text-generation をご参照ください。
try (StreamResponse<ChatCompletionChunk> streamResponse = client.chat().completions().createStreaming(chatParams)) {
streamResponse.stream().forEach(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("For more information, see https://www.alibabacloud.com/help/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
}
}'ドキュメントの追加
モデルとの対話中に新しいドキュメント情報を追加するには、新しいドキュメントのコンテンツを messages 配列のシステムメッセージに追加します。
Python
import os
from openai import OpenAI, BadRequestError
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"), # 環境変数を設定していない場合は、ここを API キーに置き換えてください。
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", # DashScope サービスのベース URL を入力します。
)
# 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:
# 1回目の応答。
completion_1 = client.chat.completions.create(
model="qwen-long",
messages=messages,
stream=False
)
# 1回目の応答を出力します。
# 1回目の応答をストリーミングするには、stream を True に設定し、各出力セグメントを追加し、連結された文字列を assistant_message の構築時に content として渡します。
print(f"First-round response: {completion_1.choices[0].message.model_dump()}")
except BadRequestError as e:
print(f"Error message: {e}")
print("For more information, see https://www.alibabacloud.com/help/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': '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)
# ユーザーの質問を追加します。
messages.append({
'role': 'user',
'content': 'What are the similarities and differences between the products discussed in these two articles?'
})
# ドキュメント追加後の応答。
completion_2 = client.chat.completions.create(
model="qwen-long",
messages=messages,
# すべてのコード例では、モデルの出力プロセスを明確かつ直感的に示すためにストリーミング出力を使用しています。非ストリーミング出力の例については、https://www.alibabacloud.com/help/model-studio/text-generation をご参照ください。
stream=True,
stream_options={"include_usage": True}
)
# ドキュメント追加後の応答をストリーミングして出力します。
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();
// 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("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));
// ユーザーの質問メッセージ (USER ロール)。
ChatCompletionUserMessageParam userMsg1 = ChatCompletionUserMessageParam.builder()
.content("Summarize the article's content.")
.build();
messages.add(ChatCompletionMessageParam.ofUser(userMsg1));
// 1回目のリクエストを構築し、例外を処理します。
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("For more information, see https://www.alibabacloud.com/help/model-studio/error-code.");
e.printStackTrace();
return;
}
// 1回目の応答。
String firstResponse = completion1 != null ? completion1.choices().get(0).message().content().orElse("") : "";
System.out.println("First-round response: " + firstResponse);
// AssistantMessage を構築します。
ChatCompletionAssistantMessageParam assistantMsg = ChatCompletionAssistantMessageParam.builder()
.content(firstResponse)
.build();
messages.add(ChatCompletionMessageParam.ofAssistant(assistantMsg));
// 2番目のコンテンツを渡します。
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));
// 2回目のユーザーの質問 (USER ロール)。
ChatCompletionUserMessageParam userMsg2 = ChatCompletionUserMessageParam.builder()
.content("Compare the structural differences between the two descriptions.")
.build();
messages.add(ChatCompletionMessageParam.ofUser(userMsg2));
// すべてのコード例では、モデルの出力プロセスを明確かつ直感的に示すためにストリーミング出力を使用しています。非ストリーミング出力の例については、https://www.alibabacloud.com/help/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("For more information, see https://www.alibabacloud.com/help/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
}
}'モデルの料金
モデル | バージョン | コンテキストウィンドウ | 最大入力 | 最大出力 | 入力コスト | 出力コスト |
(トークン) | (100 万トークンあたり) | |||||
qwen-long-latest 常に最新のスナップショットバージョンと同じ機能を持ちます。 | 最新 | 10,000,000 | 10,000,000 | 32,768 | $0.072 | $0.287 |
qwen-long-2025-01-25 qwen-long-0125 とも呼ばれます。 | スナップショット | |||||
よくある質問
Qwen-Long はバッチタスクの送信をサポートしていますか?
はい、サポートしています。Qwen-Long は OpenAI Batch API と互換性があり、ファイルを使用してバッチタスクを送信できます。これらのタスクは非同期で実行され、リアルタイム呼び出しの 50% のコストで課金されます。結果は、タスクが完了するか、最大待機時間に達した後に返されます。
OpenAI 互換ファイル API を使用してアップロードされたファイルはどこに保存されますか?
OpenAI 互換ファイル API を使用してアップロードしたファイルは、ご利用の Alibaba Cloud アカウントの Model Studio ストレージに無料で保存されます。アップロードされたファイルのクエリと管理方法については、「OpenAI ファイル API」をご参照ください。
qwen-long-2025-01-25とは何ですか?これはバージョンスナップショット識別子です。特定の時点でのモデルの特徴とパフォーマンスを固定したバージョンを表します。このバージョンは最新バージョンよりも高い安定性を提供し、有効期限を示すものではありません。
ファイルが解析されたことを確認するにはどうすればよいですか?
file-idを取得した後、そのfile-idを使用してモデルとの対話を開始できます。ファイルがまだ解析中の場合、システムはエラーコード 400 とメッセージ「File parsing in progress, please try again later.」を返します。モデル呼び出しが成功し、応答が返された場合は、ファイルが正常に解析されたことを示します。モデルの出力を標準 JSON 構造に制限するにはどうすればよいですか?
qwen-longとそのすべてのスナップショットは、構造化出力をサポートしています。JSON Schema を指定して、定義された構造に従う有効な JSON 応答を返すようにモデルを制約できます。
API リファレンス
Qwen-Long の入力パラメーターと出力パラメーターについては、Qwen API リファレンスをご参照ください。
エラーコード
呼び出しが失敗した場合、トラブルシューティングは「エラーメッセージ」をご参照ください。
制限事項
SDK の依存関係:
ファイルアップロード、削除、クエリなどの管理操作は、OpenAI 互換 SDK を使用して実行する必要があります。
モデル呼び出しには、OpenAI 互換 SDK または Dashscope SDK を使用できます。
ファイルアップロード:
サポートされている形式:TXT、DOCX、PDF、XLSX、EPUB、MOBI、MD、CSV、JSON、BMP、PNG、JPG/JPEG、GIF。
ファイルサイズの最大値は、画像の場合は 20 MB、その他のファイル形式の場合は 150 MB です。
アカウントクォータ:1 つのアカウントでアップロードできるファイルは最大 10,000 個、合計サイズは最大 100 GB です。いずれかの上限に達した場合、新しいアップロードリクエストは失敗します。クォータを解放するには、不要なファイルを削除する必要があります。詳細については、「OpenAI 互換 - ファイル」をご参照ください。
ストレージの有効期間:現在、制限はありません。
API 入力:
file-idを使用してファイルを参照する場合、1 つのリクエストで最大 100 個のファイルを参照できます。合計コンテキスト長は 1,000 万トークンに制限されます。userまたはsystemメッセージにプレーンテキストを直接入力する場合、単一メッセージ (file-idではない) のコンテンツは 9,000 トークンに制限されます。
API 出力:
最大出力長は 32,768 トークンです。
ファイル共有:
file-idは、それを生成した Alibaba Cloud アカウントに対してのみ有効です。アカウント間の呼び出しや、RAM ユーザーの API キーを使用した呼び出しには使用できません。
レート制限:モデルのレート制限の詳細については、「レート制限」をご参照ください。