Todos los productos
Search
Centro de documentos

Alibaba Cloud Model Studio:Interfaz de archivos compatible con OpenAI

Última actualización: Oct 12, 2026

Cargue archivos para preguntas y respuestas sobre documentos y extracción de datos con Qwen-Long y Qwen-Doc-Turbo. Esta interfaz también admite la carga de archivos de entrada para tareas por lotes.

Uso

Llame a la interfaz de archivos utilizando el SDK de OpenAI (Python o Java) o la API HTTP. La interfaz admite la subida, consulta y eliminación de archivos.

Requisitos previos

Disponibilidad de modelos

Puede utilizar los ID de archivo en los siguientes escenarios:

  • Qwen-Long: Realizar preguntas y respuestas sobre documentos largos.
  • Qwen-Doc-Turbo: Extraer datos y realizar preguntas y respuestas sobre archivos.
  • Procesamiento por lotes: Subir archivos por lotes.

Introducción

Cargar un archivo

Los límites de almacenamiento son de 10,000 archivos como máximo y 100 GB en total. Los archivos no caducan.

Para análisis de documentos

Establezca purpose en file-extract. Los formatos admitidos incluyen archivos de texto (TXT, DOCX, PDF, XLSX, EPUB, MOBI, MD, CSV, JSON) e imágenes (BMP, PNG, JPG/JPEG, GIF, PDF escaneados). El tamaño máximo del archivo es de 150 MB.

Para obtener más información sobre el análisis de documentos utilizando un file_id, consulte contexto largo (Qwen-Long).

Ejemplos de solicitud

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/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/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/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"'

Respuesta de ejemplo

{
    "id": "file-fe-xxx",
    "bytes": 2055,
    "created_at": 1729065448,
    "filename": "test.txt",
    "object": "file",
    "purpose": "file-extract",
    "status": "processed",
    "status_details": null
}

Para procesamiento por lotes

Establezca purpose en batch. El archivo de entrada debe estar en formato JSONL y cumplir con los Requisitos de archivo por lotes. El tamaño máximo del archivo es de 500 MB.

Para obtener más información sobre las llamadas por lotes, consulte Compatible con OpenAI - Lotes (entrada de archivo).

Ejemplos de solicitud

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/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/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/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"'

Respuesta de ejemplo

{
    "id": "file-batch-xxx",
    "bytes": 231,
    "created_at": 1729065815,
    "filename": "test.jsonl",
    "object": "file",
    "purpose": "batch",
    "status": "processed",
    "status_details": null
}

Consultar información del archivo

Especifique el file_id en el método retrieve o GET para consultar la información del archivo.

SDK de Python de OpenAI

Ejemplos de solicitud

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/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())

Respuesta de ejemplo

{
  "id": "file-batch-xxx",
  "bytes": 27,
  "created_at": 1722480306,
  "filename": "test.txt",
  "object": "file",
  "purpose": "batch",
  "status": "processed",
  "status_details": null
}

SDK de Java de OpenAI

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/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}

Ejemplos de solicitud

# ======= Important =======
# API keys for the Singapore and China (Beijing) regions are different. Get an API key: https://www.alibabacloud.com/help/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"

Si utiliza un modelo en la región China (Beijing), debe usar una API KEY de la región China (Beijing) y reemplazar la URL con: https://dashscope.aliyuncs.com/compatible-mode/v1/files/file-batch-xxx

Respuesta de ejemplo

{
    "id": "file-batch-xxx",
    "object": "file",
    "bytes": 499719,
    "created_at": 1715935833,
    "filename": "test.txt",
    "purpose": "batch",
    "status": "processed"
}

Consultar una lista de archivos

Esta operación devuelve toda la información de los archivos, incluidos los archivos subidos y los archivos de resultados por lotes.

NotaEsta operación admite más parámetros de filtrado. Para obtener más información, consulte Descripción de parámetros.

SDK de Python de OpenAI

Ejemplos de solicitud

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/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())

Respuesta de ejemplo

{
  "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
}

SDK de Java de OpenAI

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/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

Ejemplos de solicitud

# ======= Important =======
# API keys for the Singapore and China (Beijing) regions are different. Get an API key: https://www.alibabacloud.com/help/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"

Si utiliza un modelo en la región China (Beijing), debe usar una API KEY de la región China (Beijing) y reemplazar la URL con: https://dashscope.aliyuncs.com/compatible-mode/v1/files

Respuesta de ejemplo

{
    "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"
        }
    ]
}

Eliminar un archivo

Elimine un archivo mediante file_id. Utilice la API Consultar una lista de archivos para encontrar los ID de archivo.

SDK de Python de OpenAI

Ejemplos de solicitud

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/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())

Respuesta de ejemplo

{
  "object": "file",
  "deleted": true,
  "id": "file-batch-xxx"
}

SDK de Java de OpenAI

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/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}

Ejemplos de solicitud

# ======= Important =======
# API keys for the Singapore and China (Beijing) regions are different. Get an API key: https://www.alibabacloud.com/help/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"

Si utiliza un modelo de la región China (Beijing), debe usar una API KEY de la región China (Beijing) y reemplazar la URL con: https://dashscope.aliyuncs.com/compatible-mode/v1/files/file-batch-xxx

Respuesta de ejemplo

{
  "object": "file",
  "deleted": true,
  "id": "file-batch-oLIon7bzfxELqJBTS5okwC4E"
}

Facturación

La subida, el almacenamiento y la consulta de archivos son gratuitos. Los cargos se aplican solo a los tokens de entrada y salida al llamar a los modelos.

Limitación de tasa

El límite de QPS para la subida de archivos es 3. El límite total de QPS para operaciones de consulta, listado y eliminación es 10.

Puesta en marcha

  • Limpieza periódica: Elimine los archivos no utilizados regularmente para mantenerse dentro del límite de 10,000 archivos.
  • Verificación de estado: Verifique que status sea processed antes de utilizar los archivos subidos.
  • Verificación de límite de tasa: Asegúrese de cumplir con los límites de QPS (subida: 3 QPS, consulta/listado/eliminación: 10 QPS en total).
  • Manejo de errores: Implemente manejo de excepciones para errores de red, errores de API y otros fallos.

FAQ

1. ¿Qué hago si el estado del archivo permanece como "processing" después de la subida?

El procesamiento de archivos generalmente se completa en segundos. Si el estado permanece como "processing" durante un período prolongado:

  • Verifique si el formato del archivo es compatible.
  • Verifique si el tamaño del archivo excede el límite.
  • Utilice la API retrieve para consultar el estado periódicamente.

2. ¿Se pueden utilizar los ID de archivo en diferentes cuentas?

No. Los ID de archivo solo son válidos dentro de la cuenta de Alibaba Cloud que los creó y no se pueden compartir entre cuentas.

3. ¿Los archivos subidos se almacenan permanentemente?

Sí. Los archivos se almacenan permanentemente en su cuenta a menos que se eliminen. Limpie periódicamente los archivos innecesarios.

4. ¿Cuáles son las posibles razones de un fallo en la subida de archivos?

  • La clave de API no es válida o no se ha exportado.
  • El formato del archivo no es compatible.
  • El tamaño del archivo excede el límite (file-extract: 150 MB, batch: 500 MB).
  • Se ha alcanzado el número máximo de archivos (10,000) o el límite de tamaño total (100 GB).
  • Se ha excedido el límite de QPS para la interfaz de subida de archivos. El límite es de 3 QPS.

5. ¿Debería elegir file-extract o batch para el parámetro purpose?

  • file-extract: Utilice esto para escenarios de análisis de documentos con Qwen-Long o Qwen-Doc-Turbo.
  • batch: Utilice esto para tareas por lotes. El archivo debe ser un archivo JSONL que cumpla con los requisitos de formato.

Descripción de parámetros

CategoríaParámetroTipoObligatorioDescripciónEjemplo

Carga de archivos

file

Archivo

Sí

El archivo a subir.

Path("test.txt")

purpose

String

Sí

Especifica el propósito del archivo subido. Valores válidos:

file-extract: Para comprensión de documentos con el modelo qwen-long.

batch: Para trabajos de Compatible con OpenAI - Lote (entrada de archivo). El archivo debe tener el formato especificado en Compatible con OpenAI - Lote (entrada de archivo).

"file-extract"

Consulta de archivo

file_id

String

Sí

El ID del archivo a consultar.

"file-fe-xxx"

after

String

No

El cursor utilizado para la paginación en la tarea Consultar una lista de archivos.

Establezca after en el último file_id de la página actual para recuperar la siguiente página. Ejemplo: si el último file_id es file-batch-xxx, establezca after="file-batch-xxx" en la siguiente consulta.

"file-fe-xxx"

create_before

String

No

Marca de tiempo (formato de cadena) para Consultar una lista de archivos. Devuelve los ID de archivo creados antes de la hora especificada.

"20250306123000", "2025-11-12 10:10:10", "2025-11-12", "20251112"

create_after

String

No

Marca de tiempo (formato de cadena) para Consultar una lista de archivos. Devuelve los ID de archivo creados después de la hora especificada.

"20250306123000", "2025-11-12 10:10:10", "2025-11-12", "20251112"

purpose

String

No

Para Consultar una lista de archivos: filtra por propósito (file-extract o batch).

"batch"

limit

Integer

No

Número de archivos por consulta en Consultar una lista de archivos. Rango: 1-2,000. Valor predeterminado: 2,000.

2000

Eliminación de archivo

file_id

String

Sí

El ID del archivo a eliminar.

"file-fe-xxx"

Parámetros de respuesta

Parámetros de respuesta comunes

id

String

\

El ID del archivo.

Para Eliminar un archivo: el ID del archivo eliminado.

"file-fe-xxx"

bytes

Integer

El tamaño del archivo en bytes.

81067

created_at

Integer

La marca de tiempo UNIX en segundos cuando se creó el archivo.

1617981067

filename

String

El nombre del archivo subido.

"text.txt"

object

String

El tipo de objeto. Siempre es "list" para Consultar una lista de archivos, y "file" para otras operaciones.

"file"

purpose

String

El propósito del archivo. Los valores válidos son batch, file-extract y batch_output.

"file-extract"

status

String

El estado actual del archivo.

"processed"

Consultar lista de archivos

has_more

Boolean

Indica si hay una página siguiente de datos.

false

data

Array

Lista de archivos. Cada elemento sigue el formato de parámetros de respuesta comunes.

[{
 "id": "xxx",
 "bytes": 27,
 "created_at": 1722480543,
 "filename": "test.txt",
 "object": "file",
 "purpose": "batch",
 "status": "processed",
 "status_details": null
 }]

Eliminar archivo

deleted

Boolean

Indica el éxito de la eliminación. Devuelve true si tiene éxito.

true

Códigos de error

Si la llamada al modelo falla y devuelve un mensaje de error, consulte Códigos de error para su resolución.