Faça upload de arquivos para Q&A em documentos e extração de dados com Qwen-Long e Qwen-Doc-Turbo. Esta interface também oferece suporte ao upload de arquivos de entrada para tarefas em lote.
Uso
Chame a interface de arquivo usando o OpenAI SDK (Python ou Java) ou a API HTTP. A interface oferece suporte a upload, consulta e exclusão de arquivos.
Pré-requisitos
-
Uma chave de API do Alibaba Cloud Model Studio: Obtenha uma chave de API e Exporte a chave de API como variável de ambiente.
-
Para usar o OpenAI SDK, instale o OpenAI SDK.
Disponibilidade de modelos
Você pode usar IDs de arquivo nos seguintes cenários:
-
Qwen-Long: Realize Q&A em documentos longos.
-
Qwen-Doc-Turbo: Extraia dados e realize Q&A em arquivos.
-
Processamento em lote: Faça upload de arquivos em lote.
Introdução
Fazer upload de um arquivo
Os limites de armazenamento são 10.000 arquivos no máximo e 100 GB no total. Os arquivos não expiram.
Para análise de documentos
Defina `purpose` como file-extract. Os formatos suportados incluem arquivos de texto (TXT, DOCX, PDF, XLSX, EPUB, MOBI, MD, CSV, JSON) e imagens (BMP, PNG, JPG/JPEG, GIF, PDFs digitalizados). O tamanho máximo do arquivo é 150 MB.
Para obter mais informações sobre análise de documentos usando um file_id, consulte contexto longo (Qwen-Long).
Exemplos de solicitação
import os
from pathlib import Path
from openai import OpenAI
client = OpenAI(
# If you have not configured an environment variable, replace the following line with api_key="sk-xxx" and use your Model Studio API key.
# API keys for the Singapore and China (Beijing) regions are different. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
# The following is the URL for the Singapore region. If you use a model in the China (Beijing) region, replace the URL with: https://dashscope.aliyuncs.com/compatible-mode/v1
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
# test.txt is a local sample file.
file_object = client.files.create(file=Path("test.txt"), purpose="file-extract")
print(file_object.model_dump_json())import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.FileCreateParams;
import com.openai.models.FileObject;
import com.openai.models.FilePurpose;
import java.nio.file.Path;
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()
// API keys for the Singapore and China (Beijing) regions are different. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// The following is the URL for the Singapore region. If you use a model in the China (Beijing) region, replace the URL with: https://dashscope.aliyuncs.com/compatible-mode/v1
.baseUrl("https://dashscope-intl.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/test.txt");
// Create file upload parameters.
FileCreateParams params = FileCreateParams.builder()
.file(filePath)
.purpose(FilePurpose.of("file-extract"))
.build();
// Upload the file.
FileObject fileObject = client.files().create(params);
System.out.println(fileObject);
}
}# ======= Important =======
# API keys for the Singapore and China (Beijing) regions are different. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
# The following is the URL for the Singapore region. If you use a model in the China (Beijing) region, replace the URL with: https://dashscope.aliyuncs.com/compatible-mode/v1/files
# === Delete this comment before running ===
curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/files \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
--form 'file=@"test.txt"' \
--form 'purpose="file-extract"'Exemplo de resposta
{
"id": "file-fe-xxx",
"bytes": 2055,
"created_at": 1729065448,
"filename": "test.txt",
"object": "file",
"purpose": "file-extract",
"status": "processed",
"status_details": null
}
Para processamento em lote
Defina `purpose` como batch. O arquivo de entrada deve estar no formato JSONL e estar em conformidade com os Requisitos do arquivo em lote. O tamanho máximo do arquivo é 500 MB.
Para obter mais informações sobre chamadas em lote, consulte OpenAI-compatible - Batch (file input).
Exemplos de solicitação
import os
from pathlib import Path
from openai import OpenAI
client = OpenAI(
# If you have not configured an environment variable, replace the following line with api_key="sk-xxx" and use your Model Studio API key.
# API keys for the Singapore and China (Beijing) regions are different. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
# The following is the URL for the Singapore region. If you use a model in the China (Beijing) region, replace the URL with: https://dashscope.aliyuncs.com/compatible-mode/v1
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
# test.jsonl is a local sample file.
file_object = client.files.create(file=Path("test.jsonl"), purpose="batch")
print(file_object.model_dump_json())import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.FileCreateParams;
import com.openai.models.FileObject;
import com.openai.models.FilePurpose;
import java.nio.file.Path;
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()
// API keys for the Singapore and China (Beijing) regions are different. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// The following is the URL for the Singapore region. If you use a model in the China (Beijing) region, replace the URL with: https://dashscope.aliyuncs.com/compatible-mode/v1
.baseUrl("https://dashscope-intl.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/test.txt");
// Create file upload parameters.
FileCreateParams params = FileCreateParams.builder()
.file(filePath)
.purpose(FilePurpose.of("batch"))
.build();
// Upload the file.
FileObject fileObject = client.files().create(params);
System.out.println(fileObject);
}
}# ======= Important =======
# API keys for the Singapore and China (Beijing) regions are different. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
# The following is the URL for the Singapore region. If you use a model in the China (Beijing) region, replace the URL with: https://dashscope.aliyuncs.com/compatible-mode/v1/files
# === Delete this comment before running ===
curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/files \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
--form 'file=@"test.jsonl"' \
--form 'purpose="batch"'Exemplo de resposta
{
"id": "file-batch-xxx",
"bytes": 231,
"created_at": 1729065815,
"filename": "test.jsonl",
"object": "file",
"purpose": "batch",
"status": "processed",
"status_details": null
}
Consultar informações do arquivo
Especifique o file_id no método retrieve ou GET para consultar informações do arquivo.
OpenAI Python SDK
Exemplos de solicitação
import os
from openai import OpenAI
client = OpenAI(
# API keys for the Singapore and China (Beijing) regions are different. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
# The following is the URL for the Singapore region. If you use a model in the China (Beijing) region, replace the URL with: https://dashscope.aliyuncs.com/compatible-mode/v1
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
file = client.files.retrieve(file_id="file-batch-xxx")
print(file.model_dump_json())
Exemplo de resposta
{
"id": "file-batch-xxx",
"bytes": 27,
"created_at": 1722480306,
"filename": "test.txt",
"object": "file",
"purpose": "batch",
"status": "processed",
"status_details": null
}
OpenAI Java SDK
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.FileObject;
import com.openai.models.FileRetrieveParams;
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()
// API keys for the Singapore and China (Beijing) regions are different. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// The following is the URL for the Singapore region. If you use a model in the China (Beijing) region, replace the URL with: https://dashscope.aliyuncs.com/compatible-mode/v1
.baseUrl("https://dashscope-intl.aliyuncs.com/compatible-mode/v1")
.build();
// Create file query parameters. Replace the fileId as needed.
FileRetrieveParams params= FileRetrieveParams.builder()
.fileId("file-batch-xxx")
.build();
//Query the file.
FileObject fileObject = client.files().retrieve(params);
System.out.println(fileObject);
}
}
HTTP
Endpoint
Singapore region: GET https://dashscope-intl.aliyuncs.com/compatible-mode/v1/files/{file_id}
China (Beijing) region: GET https://dashscope.aliyuncs.com/compatible-mode/v1/files/{file_id}
Exemplos de solicitação
# ======= Important =======
# API keys for the Singapore and China (Beijing) regions are different. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
# The following is the URL for the Singapore region. If you use a model in the China (Beijing) region, replace the URL with: https://dashscope.aliyuncs.com/compatible-mode/v1/files/file-batch-xxx
# === Delete this comment before running ===
curl -X GET https://dashscope-intl.aliyuncs.com/compatible-mode/v1/files/file-batch-xxx \
-H "Authorization: Bearer $DASHSCOPE_API_KEY"
Se você usar um modelo na região China (Beijing), deverá usar uma API KEY da região China (Beijing) e substituir a URL por: https://dashscope.aliyuncs.com/compatible-mode/v1/files/file-batch-xxx
Exemplo de resposta
{
"id": "file-batch-xxx",
"object": "file",
"bytes": 499719,
"created_at": 1715935833,
"filename": "test.txt",
"purpose": "batch",
"status": "processed"
}
Consultar uma lista de arquivos
Esta operação retorna todas as informações de arquivos, incluindo arquivos enviados por upload e arquivos de resultado em lote.
Esta operação oferece suporte a mais parâmetros de filtragem. Para obter mais informações, consulte Descrição dos parâmetros.
OpenAI Python SDK
Exemplos de solicitação
import os
from openai import OpenAI
client = OpenAI(
# API keys for the Singapore and China (Beijing) regions are different. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
# The following is the URL for the Singapore region. If you use a model in the China (Beijing) region, replace the URL with: https://dashscope.aliyuncs.com/compatible-mode/v1
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
file_stk = client.files.list(after="file-batch-xxx",limit=20)
print(file_stk.model_dump_json())
Exemplo de resposta
{
"data": [
{
"id": "file-batch-xxx",
"bytes": 27,
"created_at": 1722480543,
"filename": "test.txt",
"object": "file",
"purpose": "batch",
"status": "processed",
"status_details": null
},
{
"id": "file-batch-yyy",
"bytes": 431986,
"created_at": 1718089390,
"filename": "test.pdf",
"object": "file",
"purpose": "batch",
"status": "processed",
"status_details": null
}
],
"object": "list",
"has_more": false
}
OpenAI Java SDK
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.FileListPage;
import com.openai.models.FileListParams;
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()
// API keys for the Singapore and China (Beijing) regions are different. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// The following is the URL for the Singapore region. If you use a model in the China (Beijing) region, replace the URL with: https://dashscope.aliyuncs.com/compatible-mode/v1
.baseUrl("https://dashscope-intl.aliyuncs.com/compatible-mode/v1")
.build();
// Create file list query parameters.
FileListParams params = FileListParams.builder()
.after("file-batch-xxx")
.limit(20)
.build();
//Query the file list.
FileListPage file_stk = client.files().list(params);
System.out.println(file_stk);
}
}
HTTP
Endpoint
Singapore region: GET https://dashscope-intl.aliyuncs.com/compatible-mode/v1/files
China (Beijing) region: GET https://dashscope.aliyuncs.com/compatible-mode/v1/files
Exemplos de solicitação
# ======= Important =======
# API keys for the Singapore and China (Beijing) regions are different. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
# The following is the URL for the Singapore region. If you use a model in the China (Beijing) region, replace the URL with: https://dashscope.aliyuncs.com/compatible-mode/v1/files
# === Delete this comment before running ===
curl -X GET https://dashscope-intl.aliyuncs.com/compatible-mode/v1/files \
-H "Authorization: Bearer $DASHSCOPE_API_KEY"
Se você usar um modelo na região China (Beijing), deverá usar uma API KEY da região China (Beijing) e substituir a URL por: https://dashscope.aliyuncs.com/compatible-mode/v1/files
Exemplo de resposta
{
"object": "list",
"has_more": true,
"data": [
{
"id": "file-batch-xxx",
"object": "file",
"bytes": 84889,
"created_at": 1715569225,
"filename": "example.txt",
"purpose": "batch",
"status": "processed"
},
{
"id": "file-batch-yyy",
"object": "file",
"bytes": 722355,
"created_at": 1715413868,
"filename": "Agent_survey.pdf",
"purpose": "batch",
"status": "processed"
}
]
}
Excluir um arquivo
Exclua um arquivo pelo file_id. Use a API Consultar uma lista de arquivos para localizar IDs de arquivo.
OpenAI Python SDK
Exemplos de solicitação
import os
from openai import OpenAI
client = OpenAI(
# API keys for the Singapore and China (Beijing) regions are different. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
# The following is the URL for the Singapore region. If you use a model in the China (Beijing) region, replace the URL with: https://dashscope.aliyuncs.com/compatible-mode/v1
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
file_object = client.files.delete("file-batch-xxx")
print(file_object.model_dump_json())
Exemplo de resposta
{
"object": "file",
"deleted": true,
"id": "file-batch-xxx"
}
OpenAI Java SDK
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.FileDeleteParams;
import com.openai.models.FileListPage;
import com.openai.models.FileListParams;
public class Main {
public static void main(String[] args) {
OpenAIClient client = OpenAIOkHttpClient.builder()
// API keys for the Singapore and China (Beijing) regions are different. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// The following is the URL for the Singapore region. If you use a model in the China (Beijing) region, replace the URL with: https://dashscope.aliyuncs.com/compatible-mode/v1
.baseUrl("https://dashscope-intl.aliyuncs.com/compatible-mode/v1")
.build();
FileDeleteParams params = FileDeleteParams.builder()
.fileId("file-batch-xxx")
.build();
System.out.println(client.files().delete(params));
}
}
HTTP
Endpoint
Singapore region: DELETE https://dashscope-intl.aliyuncs.com/compatible-mode/v1/files/{file_id}
China (Beijing) region: https://dashscope.aliyuncs.com/compatible-mode/v1/files/{file_id}
Exemplos de solicitação
# ======= Important =======
# API keys for the Singapore and China (Beijing) regions are different. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
# The following is the URL for the Singapore region. If you use a model in the China (Beijing) region, replace the URL with: https://dashscope.aliyuncs.com/compatible-mode/v1/files/file-batch-xxx
# === Delete this comment before running ===
curl -X DELETE https://dashscope-intl.aliyuncs.com/compatible-mode/v1/files/file-batch-xxx \
-H "Authorization: Bearer $DASHSCOPE_API_KEY"
Se você usar um modelo da região China (Beijing), deverá usar uma API KEY da região China (Beijing) e substituir a URL por: https://dashscope.aliyuncs.com/compatible-mode/v1/files/file-batch-xxx
Exemplo de resposta
{
"object": "file",
"deleted": true,
"id": "file-batch-oLIon7bzfxELqJBTS5okwC4E"
}
Faturamento
Upload, armazenamento e consulta de arquivos são gratuitos. As cobranças se aplicam apenas aos tokens de entrada e saída ao chamar modelos.
Limitação de taxa
O limite de QPS para upload de arquivo é 3. O limite total de QPS para operações de consulta, listagem e exclusão é 10.
Produção
-
Limpeza periódica: Exclua arquivos não utilizados regularmente para manter-se dentro do limite de 10.000 arquivos.
-
Verificação de status: Verifique se
statusestá comoprocessedantes de usar os arquivos enviados por upload. -
Verificação de limitação de taxa: Certifique-se de que está em conformidade com os limites de QPS (upload: 3 QPS, consulta/listagem/exclusão: 10 QPS no total).
-
Tratamento de erros: Implemente o tratamento de exceções para erros de rede, erros de API e outras falhas.
Perguntas frequentes
1. O que fazer se o status do arquivo permanecer "processing" após o upload?
O processamento do arquivo geralmente é concluído em segundos. Se o status permanecer "processing" por um período prolongado:
-
Verifique se o formato do arquivo é suportado.
-
Verifique se o tamanho do arquivo excede o limite.
-
Use a API
retrievepara consultar o status periodicamente.
2. Os IDs de arquivo podem ser usados em contas diferentes?
Não. Os IDs de arquivo são válidos apenas na conta Alibaba Cloud que os criou e não podem ser compartilhados entre contas.
3. Os arquivos enviados por upload são armazenados permanentemente?
Sim. Os arquivos são armazenados permanentemente na sua conta, a menos que sejam excluídos. Limpe arquivos desnecessários periodicamente.
4. Quais são os possíveis motivos para uma falha no upload de arquivo?
-
A chave de API é inválida ou não foi exportada.
-
O formato do arquivo não é suportado.
-
O tamanho do arquivo excede o limite (file-extract: 150 MB, batch: 500 MB).
-
O número máximo de arquivos (10.000) ou o limite de tamanho total (100 GB) foi atingido.
-
O limite de QPS para a interface de upload de arquivo foi excedido. O limite é de 3 QPS.
5. Devo escolher file-extract ou batch para o parâmetro purpose?
-
file-extract: Use para cenários de análise de documentos com Qwen-Long ou Qwen-Doc-Turbo. -
batch: Use para tarefas em lote. O arquivo deve ser um arquivo JSONL que atenda aos requisitos de formato.
Descrição dos parâmetros
|
Categoria |
Parâmetro |
Tipo |
Obrigatório |
Descrição |
Exemplo |
|
Upload de arquivo |
file |
File |
Yes |
O arquivo a ser enviado por upload. |
Path("test.txt") |
|
purpose |
String |
Yes |
Especifica a finalidade do arquivo enviado por upload. Valores válidos:
|
"file-extract" |
|
|
Consulta de arquivo |
file_id |
String |
Yes |
O ID do arquivo a ser consultado. |
"file-fe-xxx" |
|
after |
String |
No |
O cursor usado para paginação na tarefa Consultar uma lista de arquivos. Defina |
"file-fe-xxx" |
|
|
create_before |
String |
No |
Timestamp (formato string) para Consultar uma lista de arquivos. Retorna IDs de arquivo criados antes do horário especificado. |
|
|
|
create_after |
String |
No |
Timestamp (formato string) para Consultar uma lista de arquivos. Retorna IDs de arquivo criados depois do horário especificado. |
|
|
|
purpose |
String |
No |
Para Consultar uma lista de arquivos: filtra por finalidade ( |
"batch" |
|
|
limit |
Integer |
No |
Número de arquivos por consulta em Consultar uma lista de arquivos. Intervalo: 1-2.000. Padrão: 2.000. |
2000 |
|
|
Exclusão de arquivo |
file_id |
String |
Yes |
O ID do arquivo a ser excluído. |
"file-fe-xxx" |
|
Parâmetros de resposta |
|||||
|
Parâmetros de resposta comuns |
id |
String |
\ |
O ID do arquivo. Para Excluir um arquivo: o ID do arquivo excluído. |
"file-fe-xxx" |
|
bytes |
Integer |
O tamanho do arquivo em bytes. |
81067 |
||
|
created_at |
Integer |
O timestamp UNIX em segundos de quando o arquivo foi criado. |
1617981067 |
||
|
filename |
String |
O nome do arquivo enviado por upload. |
"text.txt" |
||
|
object |
String |
O tipo de objeto. Sempre "list" para Consultar uma lista de arquivos, "file" para outras operações. |
"file" |
||
|
purpose |
String |
A finalidade do arquivo. Os valores válidos são |
"file-extract" |
||
|
status |
String |
O status atual do arquivo. |
"processed" |
||
|
Consultar lista de arquivos |
has_more |
Boolean |
Indica se há uma próxima página de dados. |
false |
|
|
data |
Array |
Lista de arquivos. Cada elemento segue o formato dos parâmetros de resposta comuns. |
|
||
|
Excluir arquivo |
deleted |
Boolean |
Indica o sucesso da exclusão. Retorna `true` se bem-sucedido. |
true |
|
Códigos de erro
Se a chamada ao modelo falhar e retornar uma mensagem de erro, consulte 错误码 para resolução.