Para cenários sem exigência de tempo real, como anotação de dados e geração de conteúdo, a API Batch Chat oferece uma alternativa de baixo custo e alta concorrência que utiliza o mesmo método de chamada síncrona. Desconto de 50% disponível por tempo limitado.
Esta API aceita apenas o envio de requisições individuais. Para enviar múltiplas requisições simultaneamente, agrupe-as em um arquivo. Consulte OpenAI-compatible - Batch (file input) .
Como funciona
-
Envio da requisição: O cliente envia uma requisição e estabelece uma conexão.
-
Fila e espera: A requisição entra em fila enquanto o cliente mantém a conexão ativa.
-
Retorno do resultado: Após o processamento, o servidor retorna o resultado completo pela conexão estabelecida.
A conexão é encerrada com erro de timeout caso o tempo máximo de espera seja excedido.
Disponibilidade
China (Beijing)
- Text generation models: qwen3.8-max, qwen3.8-flash, qwen3.7-max, qwen3.7-plus, qwen3.6-plus, qwen3.7-flash, qwen3.6-flash, qwen3.5-plus, qwen3.5-flash, qwen-plus, qwen-flash
- Image and video understanding models: qwen3.8-max, qwen3.8-flash, qwen3.7-plus, qwen3.6-plus, qwen3.7-flash, qwen3.6-flash, qwen3.5-plus, qwen3.5-flash, qwen3.5-omni-plus, qwen3-vl-plus
Importante
- No cenário de processamento em lote, o limite de tokens de contexto por requisição é de 256 K para os modelos
qwen3.8-max,qwen3.8-flash,qwen3.7-max,qwen3.7-plus,qwen3.6-plus,qwen3.7-flash,qwen3.6-flash,qwen3.5-plus,qwen3.5-flasheqwen3.5-omni-plus. - Alguns modelos suportam o modo de raciocínio. Ative esse modo gera
tokensde raciocínio e aumenta os custos. - Os modelos das séries
qwen3.8,qwen3.7,qwen3.6eqwen3.5têm o modo de raciocínio ativado por padrão. Ao usar um modelo de raciocínio híbrido, defina explicitamente o parâmetroenable_thinking. Defina este parâmetro comotruepara ativar o modo oufalsepara desativá-lo. - No corpo da requisição JSONL,
enable_thinkingé um parâmetro de nível superior debodye deve estar no mesmo nível demodel. Não o coloque dentro deextra_body.
Uso
Pré-requisitos
-
Ative o Alibaba Cloud Model Studio e obtenha uma API key.
Configure the API key as an environment variable para reduzir o risco de vazamento.
-
Para usar o SDK da OpenAI, instale-o:
pip3 install -U openai
Etapa 1: Configure o endpoint da API
Mude da inferência em tempo real para a inferência em lote modificando o endpoint da API (base_url) conforme o método de chamada:
SDK: Defina base_url como https://batch.dashscope.aliyuncs.com/compatible-mode/v1
HTTP: POST https://batch.dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
Etapa 2: Fazer uma chamada
Os exemplos a seguir mostram como chamar a API Batch Chat. O timeout padrão é de 3600 segundos (1 hora); nenhuma configuração extra é necessária na maioria dos casos.
Intervalo de timeout personalizado: 60–3600 segundos.
Python
Exemplo de requisiçãoimport os
from openai import OpenAI
client = OpenAI(
# If environment variable not set, replace with api_key="sk-xxx".
# Avoid hard-coding API keys in production to reduce leak risk.
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://batch.dashscope.aliyuncs.com/compatible-mode/v1", # Batch Chat API endpoint
).with_options(timeout=1800.0) # Timeout: 1800s (30 min). Max: 3600s.
completion = client.chat.completions.create(
model="qwen-plus",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Who are you?"},
]
)
print(completion.choices[0].message.content)
Exemplo de respostaI am Qwen, a large-scale language model from Alibaba Group. I can answer questions, create text such as stories, official documents, emails, and scripts, perform logical reasoning, write code, and more. I can also express opinions and play games. If you have any questions or need help, feel free to let me know!
Java
Exemplo de requisiçãoimport com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.ChatCompletion;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
import java.time.Duration;
public class Main {
public static void main(String[] args) {
OpenAIClient client = OpenAIOkHttpClient.builder()
// If environment variable not set, replace with .apiKey("sk-xxx").
// Avoid hard-coding API keys in production to reduce leak risk.
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.baseUrl("https://batch.dashscope.aliyuncs.com/compatible-mode/v1") // Batch Chat API endpoint
.timeout(Duration.ofSeconds(1800)) // Timeout: 1800s (30 min). Max: 3600s.
.build();
ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
.addUserMessage("Who are you?")
.model("qwen-plus")
.build();
try {
ChatCompletion chatCompletion = client.chat().completions().create(params);
System.out.println(chatCompletion);
} catch (Exception e) {
System.err.println("Error occurred: " + e.getMessage());
e.printStackTrace();
}
}
}
Exemplo de respostaChatCompletion{id=chatcmpl-a12c115e-15fc-94f9-a984-81bd65f0527b, choices=[Choice{finishReason=stop, index=0, logprobs=, message=ChatCompletionMessage{
content=I am Qwen, a large-scale language model from Alibaba Group. I can help you answer questions, create text, and provide information query services. It's nice to meet you!, refusal=, role=assistant, annotations=, audio=, functionCall=, toolCalls=, additionalProperties={}}, additionalProperties={}}], created=1763609020, model=qwen-plus, object_=chat.completion, serviceTier=, systemFingerprint=, usage=CompletionUsage{completionTokens=33, promptTokens=10, totalTokens=43, completionTokensDetails=, promptTokensDetails=, additionalProperties={}}, additionalProperties={}}
Node.js
Exemplo de requisiçãoimport OpenAI from "openai";
const openai = new OpenAI(
{
// If environment variable not set, replace with apiKey: "sk-xxx".
// Avoid hard-coding API keys in production to reduce leak risk.
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL: "https://batch.dashscope.aliyuncs.com/compatible-mode/v1", // Batch Chat API endpoint
// Timeout in milliseconds: 1800s = 1,800,000ms. Max: 3,600,000ms.
timeout: 1800 * 1000,
}
);
async function main() {
const completion = await openai.chat.completions.create({
model: "qwen-plus", // Replace with your model name as needed
messages: [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "Who are you?" }
],
});
console.log(JSON.stringify(completion))
}
main();
Exemplo de resposta{
"created": 1763618557,
"usage": {
"completion_tokens": 80,
"prompt_tokens": 22,
"total_tokens": 102
},
"model": "qwen-plus",
"id": "chatcmpl-af23c086-8662-91eb-b236-892032ddee92",
"choices": [
{
"finish_reason": "stop",
"index": 0,
"message": {
"role": "assistant",
"content": "I am Qwen, a large-scale language model developed by Alibaba Cloud. I can answer questions and create text, such as stories, official documents, emails, and scripts. I can also perform logical reasoning, write code, express opinions, and play games. I support multiple languages, including Chinese, English, German, French, and Spanish. If you have any questions or need help, feel free to let me know!"
}
}
],
"object": "chat.completion"
}
Go
Exemplo de requisiçãopackage main
import (
"context"
"os"
"time"
"github.com/openai/openai-go"
"github.com/openai/openai-go/option"
)
func main() {
client := openai.NewClient(
option.WithAPIKey(os.Getenv("DASHSCOPE_API_KEY")),
// Batch Chat API endpoint
option.WithBaseURL("https://batch.dashscope.aliyuncs.com/compatible-mode/v1"),
)
// Timeout: 1800s (30 min). Max: 3600s.
ctx, cancel := context.WithTimeout(context.Background(), 3600*time.Second)
defer cancel()
chatCompletion, err := client.Chat.Completions.New(
ctx, openai.ChatCompletionNewParams{
Messages: []openai.ChatCompletionMessageParamUnion{
openai.UserMessage("Who are you?"),
},
Model: "qwen-plus",
},
)
if err != nil {
panic(err.Error())
}
println(chatCompletion.Choices[0].Message.Content)
}
Exemplo de respostaI am Qwen, a large-scale language model developed by Alibaba Cloud. I can generate various types of text, such as articles, stories, and poems, and can adapt and expand them for different scenarios and needs. In addition, I can answer various questions and provide help and solutions. I am happy to be of service!
C# (HTTP)
Exemplo de requisiçãousing System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
class Program
{
private static readonly HttpClient httpClient = new HttpClient
{
// Timeout: 1800s (30 min). Max: 3600s.
Timeout = TimeSpan.FromSeconds(1800)
};
static async Task Main(string[] args)
{
// If environment variable not set, replace with: string? apiKey = "sk-xxx";
string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("API Key is not set. Make sure the 'DASHSCOPE_API_KEY' environment variable is set.");
return;
}
// Set the request URL and content
string url = "https://batch.dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"; // Batch Chat API endpoint
// Replace with your model name as needed
string jsonContent = @"{
""model"": ""qwen-plus"",
""messages"": [
{
""role"": ""system"",
""content"": ""You are a helpful assistant.""
},
{
""role"": ""user"",
""content"": ""Who are you?""
}
]
}";
// Send the request and get the response
string result = await SendPostRequestAsync(url, jsonContent, apiKey);
// Print the result
Console.WriteLine(result);
}
private static async Task<string> SendPostRequestAsync(string url, string jsonContent, string apiKey)
{
using (var content = new StringContent(jsonContent, Encoding.UTF8, "application/json"))
{
// Set request headers
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Send the request and get the response
HttpResponseMessage response = await httpClient.PostAsync(url, content);
// Process the response
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
else
{
return $"Request failed: {response.StatusCode}";
}
}
}
}
Exemplo de resposta{
"created": 1763620689,
"usage": {
"completion_tokens": 60,
"prompt_tokens": 22,
"total_tokens": 82
},
"model": "qwen-plus",
"id": "chatcmpl-db85828d-af47-97a3-a2f4-120b8f7d72d3",
"choices": [
{
"finish_reason": "stop",
"index": 0,
"message": {
"role": "assistant",
"content": "I am Qwen, a large-scale language model from Alibaba Group. I can answer questions, create text such as stories, official documents, emails, and scripts, perform logical reasoning, write code, and more. I can also express opinions and play games. If you have any questions or need help, feel free to let me know!"
}
}
],
"object": "chat.completion"
}
PHP (HTTP)
Exemplo de requisição<?php
// Set the URL for the Batch Chat request
$url = 'https://batch.dashscope.aliyuncs.com/compatible-mode/v1/chat/completions';
// If environment variable not set, replace with: $apiKey = "sk-xxx";
$apiKey = getenv('DASHSCOPE_API_KEY');
// Set request headers
$headers = [
'Authorization: Bearer '.$apiKey,
'Content-Type: application/json'
];
// Set the request body
$data = [
// Replace with your model name as needed
"model" => "qwen-plus",
"messages" => [
[
"role" => "system",
"content" => "You are a helpful assistant."
],
[
"role" => "user",
"content" => "Who are you?"
]
]
];
// Initialize cURL session
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Timeout: 1800s (30 min). Max: 3600s.
curl_setopt($ch, CURLOPT_TIMEOUT, 1800);
// Execute cURL session
$response = curl_exec($ch);
// Check for errors
if (curl_errno($ch)) {
echo 'Curl error: ' . curl_error($ch);
}
// Close cURL resource
curl_close($ch);
// Print the response
echo $response;
?>
Exemplo de resposta{
"created": 1763621824,
"usage": {
"completion_tokens": 81,
"prompt_tokens": 22,
"total_tokens": 103
},
"model": "qwen-plus",
"id": "chatcmpl-b25aeb86-5cfe-93ea-ab03-aa3de1381c23",
"choices": [
{
"finish_reason": "stop",
"index": 0,
"message": {
"role": "assistant",
"content": "I am Qwen, a large-scale language model developed by Alibaba Cloud. I can answer questions and create text, such as stories, official documents, emails, and scripts. I can also perform logical reasoning, write code, and even express opinions and play games. I support multiple languages, including but not limited to Chinese, English, German, French, and Spanish. If you have any questions or need help, feel free to let me know!"
}
}
],
"object": "chat.completion"
}
curl
Exemplo de requisiçãoDefina max-time como 1800 segundos. Máximo: 3600 segundos.
curl -X POST https://batch.dashscope.aliyuncs.com/compatible-mode/v1/chat/completions \
--max-time 1800 \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-plus",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Who are you?"
}
]
}'
Exemplo de resposta{
"created": 1763622152,
"usage": {
"completion_tokens": 79,
"prompt_tokens": 22,
"total_tokens": 101
},
"model": "qwen-plus",
"id": "chatcmpl-daa344d2-60df-9b79-81a4-28c9a10a0a0e",
"choices": [
{
"finish_reason": "stop",
"index": 0,
"message": {
"role": "assistant",
"content": "I am Qwen, a large-scale language model from Alibaba Group. I can answer questions and create text, such as stories, official documents, emails, and scripts. I can also perform logical reasoning, write code, express opinions, and play games. I support multiple languages, including but not limited to Chinese, English, German, French, and Spanish. If you have any questions or need help, feel free to let me know!"
}
}
],
"object": "chat.completion"
}
Limitações
-
Tempo de espera: Espera síncrona máxima de 3600 segundos (1 hora). Timeout personalizado: 60–3600 segundos.
-
Limites de concorrência: Máximo de 10.000 requisições pendentes por modelo e por conta. Requisições excedentes são rejeitadas com código de erro. Novas requisições só são aceitas após a conclusão das pendentes.
-
Taxa de chamadas: Máximo de 1.000 QPS por conta ou 10.000 chamadas a cada 10 segundos.
Apenas máximo teórico. A disponibilidade real depende da carga do sistema. Implemente lógica de nova tentativa.
Faturamento
- Preço unitário: Faturamento baseado em tokens de entrada/saída em requisições bem-sucedidas. O preço de tabela corresponde ao preço da chamada em tempo real. Desconto de 50% disponível por tempo limitado no site oficial. Consulte Model list.
- Escopo de faturamento: Apenas requisições bem-sucedidas são faturadas. Requisições com falha (erros de sistema ou timeouts) não geram cobrança.
Observação
- A inferência em lote é um item de faturamento separado. Ela suporta AI general-purpose savings plan, mas não aceita descontos, como subscription (outros planos de economia) ou free quotas for new users. Também não suporta recursos como context cache.
- Alguns modelos, como qwen3.5-plus e qwen3.5-flash, têm o modo de raciocínio ativado por padrão. Esse modo gera tokens adicionais de raciocínio, cobrados pelo preço de tokens de saída, o que aumenta os custos. Para controlar despesas, defina o parâmetro
enable_thinkingconforme a complexidade da tarefa. Para mais informações, consulte Deep thinking.
Códigos de erro
Se a chamada do modelo falhar e retornar uma mensagem de erro, consulte Error codes para resolução.
FAQ
-
Existe diferença no tempo de requisição entre o Batch Chat e a API em tempo real?
Sim. As requisições entram em fila para agendamento, portanto o tempo total geralmente é maior que na API em tempo real. Espera máxima: 1 hora. A conexão é encerrada com erro se o timeout for excedido.
-
Como escolher entre Batch Chat e Batch File?
Escolha o Batch Chat para muitas requisições de diálogo independentes com alta concorrência via chamadas síncronas. Opte pelo Batch File para processar um único arquivo grande com muitas requisições via recuperação assíncrona.
-
O Batch Chat garante que todas as requisições serão concluídas?
Não. A conclusão depende da alocação de recursos compartilhados. As requisições podem entrar em fila se os recursos estiverem ocupados. A conexão atinge timeout se não for executada dentro do tempo máximo de espera. Requisições com timeout não são faturadas; tente novamente mais tarde.
Referências
- Lista completa de parâmetros para chamadas de modelo em tempo real: OpenAI compatible - Chat.
- Processamento em lote via envio de arquivo com resultados assíncronos: OpenAI-compatible - Batch (file input).