O modelo de mineração de dados extrai informações, modera conteúdo, classifica dados e gera resumos. Ele produz dados estruturados (como JSON) com rapidez e precisão, diferentemente dos modelos de chat de uso geral, que podem retornar formatos inconsistentes ou extrair informações incorretamente. Além disso, este modelo permite gerar apresentações PPT a partir do conteúdo de documentos, com os modos template e creative disponíveis.
Além disso, este modelo permite gerar apresentações PPT a partir do conteúdo de documentos, com os modos template e creative disponíveis.
Este documento aplica-se apenas à região China (Beijing). Para usar o modelo, utilize uma API key da região China (Beijing).
Guia de implementação
O Qwen-Doc-Turbo oferece suporte à extração de informações de arquivos de três maneiras. Para obter mais detalhes sobre limites de tamanho e tipo de arquivo, consulte Limitações.
|
Recurso |
URL do arquivo (Recomendado) |
ID do arquivo |
Texto simples |
|
Origem do arquivo |
URL pública |
Arquivo local (upload necessário) |
Transmitido como string |
|
Limite de entrada |
Até 10 arquivos. Suporta arquivos grandes (entrada máxima de 253 mil tokens) |
1 arquivo. Suporta arquivos grandes (entrada máxima de 253 mil tokens) |
Até 9.000 tokens |
|
Compatibilidade com SDK |
Apenas |
Upload: |
|
|
Principais vantagens |
Dispensa upload para o Model Studio. Suporta chamadas em lote. |
Evita uploads repetidos. Ideal para reutilização. |
Dispensa gerenciamento de arquivos. |
Pré-requisitos
Você já criou uma API key e exportou a API key como variável de ambiente.
Se planeja chamar o modelo usando um SDK, instale o OpenAI SDK ou o DashScope SDK.
Passar uma URL de arquivo
Extraia dados estruturados usando URLs de arquivos (até 10 arquivos simultaneamente). Este exemplo utiliza os arquivos Sample Product Manual A e Sample Product Manual B e solicita ao modelo que retorne as informações extraídas no formato JSON.
O método de URL de arquivo suporta apenas o protocolo DashScope. Use o DashScope Python SDK ou chamadas HTTP (como curl).
import os
import dashscope
# The following is the base_url for the Beijing region.
dashscope.base_http_api_url = 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1'
response = dashscope.Generation.call(
api_key=os.getenv('DASHSCOPE_API_KEY'), # If you have not set the environment variable, replace this with your API key
model='qwen-doc-turbo',
messages=[
{"role": "system","content": "You are a helpful assistant."},
{
"role": "user",
"content": [
{
"type": "text",
"text": "From these two product manuals, extract all product information and organize it into a standard JSON array. Each object must include the following: model (the product model), name (the product name), and price (the price, with currency symbols and commas removed)."
},
{
"type": "doc_url",
"doc_url": [
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251107/jockge/%E7%A4%BA%E4%BE%8B%E4%BA%A7%E5%93%81%E6%89%8B%E5%86%8CA.docx",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251107/ztwxzr/%E7%A4%BA%E4%BE%8B%E4%BA%A7%E5%93%81%E6%89%8B%E5%86%8CB.docx"
],
"file_parsing_strategy": "auto"
}
]
}]
)
try:
if response.status_code == 200:
print(response.output.choices[0].message.content)
else:
print(f"Request failed, status code: {response.status_code}")
print(f"Error code: {response.code}")
print(f"Error message: {response.message}")
print("For more information, see https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code")
except Exception as e:
print(f"An error occurred: {e}")
print("For more information, see https://www.alibabacloud.com/help/en/model-studio/developer-reference/error-code")
curl --location 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer $DASHSCOPE_API_KEY' \
--header 'X-DashScope-SSE: enable' \
--data '{
"model": "qwen-doc-turbo",
"input": {
"messages": [
{
"role": "system",
"content": "you are a helpful assistant."
},
{
"role": "user",
"content": [
{
"type": "text",
"text": "From these two product manuals, extract all product information and organize it into a standard JSON array. Each object must include the following: model (the product model), name (the product name), and price (the price, with currency symbols and commas removed)."
},
{
"type": "doc_url",
"doc_url": [
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251107/jockge/%E7%A4%BA%E4%BE%8B%E4%BA%A7%E5%93%81%E6%89%8B%E5%86%8CA.docx",
"https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251107/ztwxzr/%E7%A4%BA%E4%BE%8B%E4%BA%A7%E5%93%81%E6%89%8B%E5%86%8CB.docx"
],
"file_parsing_strategy": "auto"
}
]
}
]
}
}'
O modelo retorna os dados extraídos como um array JSON no campo content. Observe que o conteúdo pode estar envolto em marcadores de bloco de código markdown (por exemplo, json\n[...]\n). Remova esses marcadores markdown antes de analisar a resposta com json.loads():
content = response.output.choices[0].message.content
# Strip markdown code block markers if present
if content.startswith("```"):
# Remove opening ```json or ``` marker
content = content.split("\n", 1)[1] if "\n" in content else content[3:]
# Remove closing ``` marker
if content.endswith("```"):
content = content[:-3]
content = content.strip()
data = json.loads(content)
Passar um ID de arquivo
Fazer upload de um arquivo
Antes de executar o código, baixe o arquivo Sample Product Manual A e coloque-o no diretório do seu projeto. Faça o upload do arquivo por meio da interface compatível com OpenAI para obter um file-id. Para detalhes da API de upload, consulte a Referência da API.
Python
import os
from pathlib import Path
from openai import OpenAI
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"), # If you have not set the environment variable, replace this with your API key
# The following is the base_url for the Beijing region.
base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1", # Enter the DashScope service base_url
)
file_object = client.files.create(file=Path("Sample Product Manual A.docx"), purpose="file-extract")
# Print the file-id for use in subsequent model calls
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.Paths;
public class Main {
public static void main(String[] args) {
// Create a client and use the API key from the environment variable
OpenAIClient client = OpenAIOkHttpClient.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// The following is the base_url for the Beijing region.
.baseUrl("https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1")
.build();
// Set the file path. Modify the path and filename as needed.
Path filePath = Paths.get("src/main/java/org/example/Sample Product Manual A.docx");
// Create file upload parameters
FileCreateParams fileParams = FileCreateParams.builder()
.file(filePath)
.purpose(FilePurpose.of("file-extract"))
.build();
// Upload the file and print the file-id
FileObject fileObject = client.files().create(fileParams);
// Print the file-id for use in subsequent model calls
System.out.println(fileObject.id());
}
}
curl
curl --location --request POST 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/files' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--form 'file=@"Sample Product Manual A.docx"' \
--form 'purpose="file-extract"'
Execute o código para obter o file-id do arquivo enviado.
Passar informações e iniciar uma conversa usando um ID de arquivo
Insira o file-id em uma mensagem de sistema (após a mensagem de definição de função). A mensagem do usuário contém sua consulta sobre o arquivo.
import os
from openai import OpenAI, BadRequestError
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"), # If you have not set the environment variable, replace this with your API key
# The following is the base_url for the Beijing region.
base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
try:
completion = client.chat.completions.create(
model="qwen-doc-turbo",
messages=[
{'role': 'system', 'content': 'You are a helpful assistant.'},
# Replace '{FILE_ID}' with the file-id from your scenario
{'role': 'system', 'content': 'fileid://{FILE_ID}'},
{'role': 'user', 'content': 'From this product manual, extract all product information and organize it into a standard JSON array. Each object must include the following: model (the product model), name (the product name), and price (the price, with currency symbols and commas removed).'}
],
# This code example uses streaming output to clearly show the model's output process. For non-streaming output examples, see https://www.alibabacloud.com/help/en/model-studio/user-guide/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/en/model-studio/developer-reference/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) {
// Create a client and use the API key from the environment variable
OpenAIClient client = OpenAIOkHttpClient.builder()
// If you have not set the environment variable, replace the next line with your Model Studio API key: .apiKey("sk-xxx");
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// The following is the base_url for the Beijing region.
.baseUrl("https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1")
.build();
ChatCompletionCreateParams chatParams = ChatCompletionCreateParams.builder()
.addSystemMessage("You are a helpful assistant.")
// Replace '{FILE_ID}' with the file-id from your scenario
.addSystemMessage("fileid://{FILE_ID}")
.addUserMessage("From this product manual, extract all product information and organize it into a standard JSON array. Each object must include the following: model (the product model), name (the product name), and price (the price, with currency symbols and commas removed).")
.model("qwen-doc-turbo")
.build();
try (StreamResponse<ChatCompletionChunk> streamResponse = client.chat().completions().createStreaming(chatParams)) {
streamResponse.stream().forEach(chunk -> {
String content = chunk.choices().get(0).delta().content().orElse("");
if (!content.isEmpty()) {
System.out.print(content);
}
});
} catch (Exception e) {
System.err.println("Error message: " + e.getMessage());
}
}
# The following is the base_url for the Beijing region.
}
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-doc-turbo",
"messages": [
{"role": "system","content": "You are a helpful assistant."},
{"role": "system","content": "fileid://{FILE_ID}"},
{"role": "user","content": "From this product manual, extract all product information and organize it into a standard JSON array. Each object must include the following: model (the product model), name (the product name), and price (the price, with currency symbols and commas removed)."}
],
"stream": true,
"stream_options": {
"include_usage": true
}
}'
O modelo retorna os dados extraídos como um array JSON no campo content. Observe que o conteúdo pode estar envolto em marcadores de bloco de código markdown (por exemplo, json\n[...]\n). Remova esses marcadores markdown antes de analisar a resposta com json.loads():
content = response.output.choices[0].message.content
# Strip markdown code block markers if present
if content.startswith("```"):
# Remove opening ```json or ``` marker
content = content.split("\n", 1)[1] if "\n" in content else content[3:]
# Remove closing ``` marker
if content.endswith("```"):
content = content[:-3]
content = content.strip()
data = json.loads(content)
Passar texto simples
É possível transmitir o conteúdo do arquivo diretamente como uma string em vez de usar um file-id. Para evitar confusão, coloque a mensagem de definição de função primeiro no array messages.
Se o conteúdo de texto exceder 9.000 tokens, use uma URL de arquivo ou ID de arquivo (devido aos limites de tamanho do corpo da API).
import os
from openai import OpenAI, BadRequestError
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"), # If you have not set the environment variable, replace this with your API key
# The following is the base_url for the Beijing region.
base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
try:
completion = client.chat.completions.create(
model="qwen-doc-turbo",
messages=[
{'role': 'system', 'content': 'You are a helpful assistant.'},
{'role': 'system', 'content': 'Smart Office Product Manual Version: V2.0 Release Date: January 2024 Table of Contents 1.1 Product Overview...'},
{'role': 'user', 'content': 'From this product manual, extract all product information and organize it into a standard JSON array. Each object must include the following: model (the product model), name (the product name), and price (the price, with currency symbols and commas removed).'}
],
# This code example uses streaming output to clearly show the model's output process. For non-streaming output examples, see https://www.alibabacloud.com/help/en/model-studio/user-guide/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/en/model-studio/developer-reference/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) {
// Create a client and use the API key from the environment variable
OpenAIClient client = OpenAIOkHttpClient.builder()
// If you have not set the environment variable, replace the next line with your Model Studio API key: .apiKey("sk-xxx");
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// The following is the base_url for the Beijing region.
.baseUrl("https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1")
.build();
ChatCompletionCreateParams chatParams = ChatCompletionCreateParams.builder()
.addSystemMessage("You are a helpful assistant.")
.addSystemMessage("Smart Office Product Manual Version: V2.0 Release Date: January 2024 Table of Contents 1.1 Product Overview...")
.addUserMessage("From this product manual, extract all product information and organize it into a standard JSON array. Each object must include the following: model (the product model), name (the product name), and price (the price, with currency symbols and commas removed).")
.model("qwen-doc-turbo")
.build();
try (StreamResponse<ChatCompletionChunk> streamResponse = client.chat().completions().createStreaming(chatParams)) {
streamResponse.stream().forEach(chunk -> {
String content = chunk.choices().get(0).delta().content().orElse("");
if (!content.isEmpty()) {
System.out.print(content);
}
});
} catch (Exception e) {
System.err.println("Error message: " + e.getMessage());
}
}
# The following is the base_url for the Beijing region.
}
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-doc-turbo",
"messages": [
{"role": "system","content": "You are a helpful assistant."},
{"role": "system","content": "Smart Office Product Manual Version: V2.0 Release Date: January 2024 Table of Contents 1.1 Product Overview..."},
{"role": "user","content": "From this product manual, extract all product information and organize it into a standard JSON array. Each object must include the following: model (the product model), name (the product name), and price (the price, with currency symbols and commas removed)."}
],
"stream": true,
"stream_options": {
"include_usage": true
}
}'
O modelo retorna os dados extraídos como um array JSON no campo content. Observe que o conteúdo pode estar envolto em marcadores de bloco de código markdown (por exemplo, json\n[...]\n). Remova esses marcadores markdown antes de analisar a resposta com json.loads():
content = response.output.choices[0].message.content
# Strip markdown code block markers if present
if content.startswith("```"):
# Remove opening ```json or ``` marker
content = content.split("\n", 1)[1] if "\n" in content else content[3:]
# Remove closing ``` marker
if content.endswith("```"):
content = content[:-3]
content = content.strip()
data = json.loads(content)
Preços do modelo
|
Modelo |
Janela de contexto |
Entrada máx. |
Saída máx. |
Custo de entrada |
Custo de saída |
Cota gratuita |
|
(Tokens) |
(Milhões de tokens) |
|||||
|
qwen-doc-turbo |
262.144 |
253.952 |
32.768 |
$0,087 |
$0,144 |
Sem cota gratuita |
Perguntas frequentes
-
Onde os arquivos são armazenados após o upload pela interface de arquivo compatível com OpenAI?
Os arquivos enviados por meio da interface compatível com OpenAI são armazenados gratuitamente no seu bucket do Model Studio. Para consultar e gerenciar arquivos, consulte Interface de arquivo OpenAI.
-
Ao fazer upload usando o método de URL de arquivo, quais são as diferenças entre as opções do parâmetro file_parsing_strategy?
"auto": analisa automaticamente com base no conteúdo. "text_only": analisa apenas texto. "text_and_images": analisa imagens e texto (aumenta o tempo de análise).
-
Como determinar se um arquivo terminou de ser analisado?
Tente iniciar uma conversa com o ID do arquivo. Se o arquivo ainda estiver sendo analisado, a API retorna
File parsing in progress, please try again later.-- tente novamente após um atraso. Se a chamada for bem-sucedida, o arquivo está pronto. -
O processo de análise após o upload do arquivo gera custos extras?
A análise de documentos é gratuita.
Referência da API
Para os parâmetros de entrada e saída do Qwen-Doc-Turbo, consulte a Referência da API compatível com OpenAI ou a Referência da API DashScope.
Códigos de erro
Se a chamada do modelo falhar e retornar uma mensagem de erro, consulte Códigos de erro para resolução.
Limitações
-
Dependências do SDK:
URL de arquivo (doc_url): Suporta apenas o protocolo DashScope. Use o
DashScope Python SDKou chamadas HTTP (como curl).Upload de arquivo (file-id): Use um SDK compatível com
OpenAIpara upload e gerenciamento.
-
Upload e referência de arquivo:
URL de arquivo (doc_url): Até 10 URLs por solicitação. As URLs devem ser acessíveis publicamente.
-
Upload de arquivo (file-id): Máximo de 150 MB por arquivo. Limites da conta: 10.000 arquivos ou 100 GB no total (os arquivos nunca expiram). Cada solicitação referencia apenas um arquivo.
As solicitações de upload falham quando os limites são atingidos. Exclua arquivos desnecessários para liberar cota. Consulte Compatível com OpenAI - Arquivo para obter detalhes.
Formatos suportados: TXT, DOC, DOCX, PDF, XLS, XLSX, MD, PPT, PPTX, JPG, JPEG, PNG, GIF e BMP.
-
Entrada da API:
Usando
doc_urloufile-id: máximo de 262.144 tokens.Texto simples em mensagens
user/system: máximo de 9.000 tokens por mensagem.
-
Saída da API:
O comprimento máximo de saída é de 32.768 tokens.
-
Compartilhamento de arquivo:
O
file-idfunciona apenas dentro da conta geradora -- não entre contas ou com API keys de usuários RAM.
Limite de taxa: Consulte Limitação de taxa.