import asynciofrom nawa import AsyncNawaasync def process_batch(comments: list[dict], concurrency: int = 5): async with AsyncNawa(api_key="nawa_live_sk_xxx") as nawa: semaphore = asyncio.Semaphore(concurrency) results = [] async def classify_one(comment): async with semaphore: result = await nawa.classify( text=comment["text"], platform=comment["platform"] ) if result.error and result.error.type == "rate_limit_error": delay = result.error.retry_after or 2 await asyncio.sleep(delay) # Retry once result = await nawa.classify( text=comment["text"], platform=comment["platform"] ) return { "id": comment["id"], "classification": result.data, "error": result.error.message if result.error else None, } tasks = [classify_one(c) for c in comments] results = await asyncio.gather(*tasks) return results# Usagecomments = [ {"id": "1", "text": "متى الجزء الثاني؟", "platform": "youtube"}, {"id": "2", "text": "ما شاء الله عليك", "platform": "youtube"}, {"id": "3", "text": "الصوت وحش أوي", "platform": "youtube"}, # ... thousands more]results = asyncio.run(process_batch(comments, concurrency=5))print(f"Processed {len(results)} comments")
Cost optimization
Semantic caching
NAWA automatically caches classification results. When the same or semantically similar text is classified again, the response is served from cache at $0 cost.Check the X-NAWA-Cache response header:
HIT - served from cache (free)
MISS - new classification (billed)
The cached field in the response body also indicates cache status.
const { data } = await nawa.classify({ text: 'متى الجزء الثاني؟', platform: 'youtube' })console.log(data.cached) // true on subsequent calls
Deduplication
Before sending a batch, deduplicate texts to avoid paying for identical comments: