asyncio.gather per l'elaborazione in batch
In questa pagina
Orchestrazione di richieste parallele
asyncio.gather è la funzione principale per eseguire più coroutine in parallelo e raccogliere tutti i risultati. Combinata con un semaforo, ti permette di elaborare batch di richieste in modo efficiente rispettando i limiti delle API.
Sintassi di base
import asyncio
requests = ["Question 1", "Question 2", "Question 3"]
tasks = [process_request(r) for r in requests]
responses = await asyncio.gather(*tasks)
asyncio.gather accetta un numero variabile di coroutine (da qui l’uso di *tasks per espandere la lista) e restituisce una lista di risultati nello stesso ordine in cui sono stati inviati i task. Questo è un punto fondamentale: anche se la domanda 3 termina prima della domanda 1, responses[0] conterrà sempre il risultato della domanda 1.
Pattern completo: Batch con semaforo
Ecco il pattern che userai più spesso in produzione:
import os
from asyncio import Semaphore
from openai import AsyncOpenAI
import httpx
client = AsyncOpenAI(
api_key=os.getenv("XAI_API_KEY"),
base_url="https://api.x.ai/v1",
timeout=httpx.Timeout(3600.0)
)
async def process_batch(prompts: list[str], max_concurrent: int = 5) -> list[str]:
sem = Semaphore(max_concurrent)
async def single_request(prompt: str) -> str:
async with sem:
response = await client.chat.completions.create(
model="grok-4.5",
messages=[{"role": "user", "content": prompt}]
)
return response.choices[0].message.content
tasks = [single_request(p) for p in prompts]
return await asyncio.gather(*tasks)
Questo pattern incapsula il semaforo all’interno della funzione di batch. Ti basta chiamare process_batch(prompts) e recuperare la lista delle risposte.
Gestione degli errori in un batch
Di default, se una singola coroutine solleva un’eccezione, asyncio.gather annulla tutto e propaga l’errore. Il parametro return_exceptions=True modifica questo comportamento:
async def safe_batch(prompts: list[str]) -> list[str | Exception]:
sem = Semaphore(5)
async def single_request(prompt: str) -> str:
async with sem:
response = await client.chat.completions.create(
model="grok-4.5",
messages=[{"role": "user", "content": prompt}]
)
return response.choices[0].message.content
tasks = [single_request(p) for p in prompts]
results = await asyncio.gather(*tasks, return_exceptions=True)
return results
# Utilizzo
results = await safe_batch(mes_prompts)
for i, result in enumerate(results):
if isinstance(result, Exception):
print(f"Error on prompt {i}: {result}")
else:
print(f"Result {i}: {result[:100]}...")
Con return_exceptions=True, gli errori vengono catturati come valori nella lista dei risultati. Puoi quindi identificare e ritentare le richieste fallite.
Suddivisione in sotto-batch (Chunking)
Per volumi molto grandi, è meglio suddividere il lavoro in sotto-batch piuttosto che lanciare migliaia di task simultaneamente:
async def chunked_batch(
prompts: list[str],
chunk_size: int = 50,
max_concurrent: int = 5
) -> list[str]:
all_results = []
for i in range(0, len(prompts), chunk_size):
chunk = prompts[i:i + chunk_size]
print(f"Processing batch {i//chunk_size + 1} ({len(chunk)} prompts)")
results = await process_batch(chunk, max_concurrent)
all_results.extend(results)
return all_results
Il chunking offre diversi vantaggi: puoi visualizzare l’avanzamento, salvare i risultati intermedi e limitare l’uso della memoria. Se un sotto-batch fallisce, non perdi i risultati dei sotto-batch precedenti.
Monitoraggio dell’avanzamento
Per batch di grandi dimensioni, un indicatore di progresso è utile:
import asyncio
from asyncio import Semaphore
async def batch_with_progress(prompts: list[str], max_concurrent: int = 5) -> list[str]:
sem = Semaphore(max_concurrent)
completed = 0
total = len(prompts)
async def single_request(prompt: str) -> str:
nonlocal completed
async with sem:
response = await client.chat.completions.create(
model="grok-4.5",
messages=[{"role": "user", "content": prompt}]
)
completed += 1
print(f"\r{completed}/{total} completed", end="", flush=True)
return response.choices[0].message.content
tasks = [single_request(p) for p in prompts]
results = await asyncio.gather(*tasks)
print() # nuova riga dopo il progresso
return results
Punti chiave
asyncio.gather(*tasks)esegue le coroutine in parallelo e restituisce i risultati nell’ordine originalereturn_exceptions=Trueimpedisce che un singolo errore faccia fallire l’intero batch- Il chunking ti permette di gestire volumi molto grandi senza saturare la memoria
- Combina sempre
gathercon un semaforo per rispettare i limiti di frequenza (rate limits) - Aggiungi il monitoraggio dell’avanzamento per i processi di lunga durata