async-patterns
Async/await patterns with comprehensive error handling and resource cleanup for Python 3.13. PROACTIVELY activate for: (1) Implementing async API clients, (2) Creating concurrent data fetching, (3) Building async context managers, (4) Implementing retry logic, (5) Managing background tasks. Triggers: "async", "await", "asyncio", "concurrent", "aiohttp", "gather", "create_task", "timeout"
What this skill does
# Async/Await Patterns with Comprehensive Error Handling
## Core Principles
Async programming in Python 3.13 enables high-performance I/O-bound operations. **All async code in Vibekit MUST include comprehensive error handling and proper resource cleanup.**
## Basic Async Functions
Every async function must handle errors properly:
```python
import asyncio
from typing import Any
# ✅ REQUIRED: Comprehensive error handling in async functions
async def fetch_data(url: str, timeout: float = 10.0) -> dict[str, Any]:
"""
Fetch data from URL with timeout and error handling.
Raises:
TimeoutError: If request exceeds timeout
ConnectionError: If network request fails
ValueError: If response is not valid JSON
"""
try:
async with aiohttp.ClientSession() as session:
async with session.get(url, timeout=aiohttp.ClientTimeout(total=timeout)) as response:
response.raise_for_status() # Raises on 4xx/5xx
return await response.json()
except asyncio.TimeoutError:
raise TimeoutError(f"Request to {url} timed out after {timeout}s")
except aiohttp.ClientError as e:
raise ConnectionError(f"Failed to fetch {url}: {e}")
except ValueError as e:
raise ValueError(f"Invalid JSON response from {url}: {e}")
# Let other exceptions propagate
# ❌ FORBIDDEN: Async function without error handling
async def bad_fetch(url: str):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.json() # No timeout, no error handling!
```
## Concurrent Execution with asyncio.gather()
Run multiple async operations concurrently:
```python
import asyncio
from typing import Any
# ✅ REQUIRED: Use asyncio.gather() for concurrent operations
async def fetch_multiple_urls(urls: list[str]) -> list[dict[str, Any]]:
"""
Fetch multiple URLs concurrently.
Returns list of results in same order as input URLs.
Failed requests return None instead of raising.
"""
tasks = [fetch_data(url) for url in urls]
# return_exceptions=True prevents one failure from cancelling all tasks
results = await asyncio.gather(*tasks, return_exceptions=True)
# Process results and exceptions
processed: list[dict[str, Any]] = []
for i, result in enumerate(results):
if isinstance(result, Exception):
print(f"Error fetching {urls[i]}: {result}")
processed.append(None)
else:
processed.append(result)
return processed
# Alternative: Fail-fast (any error cancels all)
async def fetch_multiple_strict(urls: list[str]) -> list[dict[str, Any]]:
"""Fetch URLs concurrently, raise on first error."""
tasks = [fetch_data(url) for url in urls]
return await asyncio.gather(*tasks) # return_exceptions=False (default)
```
## Task Management with create_task()
Control task lifecycle explicitly:
```python
import asyncio
from typing import Set
# ✅ REQUIRED: Track tasks and handle cleanup
class BackgroundTaskManager:
def __init__(self):
self.tasks: Set[asyncio.Task] = set()
def create_task(self, coro) -> asyncio.Task:
"""Create task and track it."""
task = asyncio.create_task(coro)
self.tasks.add(task)
task.add_done_callback(self.tasks.discard) # Auto-remove when done
return task
async def shutdown(self) -> None:
"""Cancel all pending tasks."""
for task in self.tasks:
task.cancel()
# Wait for all cancellations to complete
await asyncio.gather(*self.tasks, return_exceptions=True)
self.tasks.clear()
# Usage
async def main():
manager = BackgroundTaskManager()
# Start background tasks
task1 = manager.create_task(long_running_operation())
task2 = manager.create_task(periodic_cleanup())
try:
# Do main work
await some_main_task()
finally:
# Clean shutdown
await manager.shutdown()
```
## Async Context Managers
Ensure proper resource cleanup in async code:
```python
import asyncio
from typing import AsyncIterator
# ✅ REQUIRED: Use async context managers for resources
class AsyncDatabaseConnection:
"""Async context manager for database connections."""
def __init__(self, connection_string: str):
self.connection_string = connection_string
self.conn = None
async def __aenter__(self):
"""Establish connection on enter."""
try:
self.conn = await asyncio.wait_for(
connect_to_database(self.connection_string),
timeout=5.0
)
return self.conn
except asyncio.TimeoutError:
raise TimeoutError("Database connection timeout")
except Exception as e:
raise ConnectionError(f"Failed to connect: {e}")
async def __aexit__(self, exc_type, exc_val, exc_tb):
"""Close connection on exit, even if exception occurred."""
if self.conn is not None:
try:
await asyncio.wait_for(self.conn.close(), timeout=5.0)
except Exception as e:
print(f"Error closing connection: {e}")
return False # Don't suppress exceptions
# Usage
async def query_database():
async with AsyncDatabaseConnection("postgresql://...") as conn:
result = await conn.execute("SELECT * FROM users")
return result
```
## Timeouts and Cancellation
Always set timeouts for async operations:
```python
import asyncio
from typing import Any
# ✅ REQUIRED: Use timeouts for all external I/O
async def fetch_with_timeout(url: str, timeout: float = 10.0) -> dict[str, Any]:
"""Fetch data with overall timeout."""
try:
return await asyncio.wait_for(
fetch_data(url),
timeout=timeout
)
except asyncio.TimeoutError:
raise TimeoutError(f"Operation timed out after {timeout}s")
# ✅ REQUIRED: Handle cancellation gracefully
async def long_running_task():
"""Task that handles cancellation properly."""
try:
for i in range(100):
await asyncio.sleep(1)
print(f"Step {i}")
except asyncio.CancelledError:
print("Task was cancelled, cleaning up...")
# Perform cleanup
raise # Re-raise to propagate cancellation
# ❌ FORBIDDEN: Async operation without timeout
async def bad_fetch():
return await fetch_data("https://slow-api.com") # No timeout!
```
## Structured Concurrency with TaskGroup (Python 3.11+)
Use TaskGroup for managing related tasks:
```python
import asyncio
# ✅ REQUIRED: Use TaskGroup for structured concurrency
async def fetch_all_data() -> list[dict]:
"""Fetch data from multiple sources using TaskGroup."""
results = []
async with asyncio.TaskGroup() as tg:
# All tasks started within the group
task1 = tg.create_task(fetch_data("https://api1.example.com"))
task2 = tg.create_task(fetch_data("https://api2.example.com"))
task3 = tg.create_task(fetch_data("https://api3.example.com"))
# At this point, all tasks have completed or an exception was raised
results = [task1.result(), task2.result(), task3.result()]
return results
# TaskGroup automatically:
# - Waits for all tasks to complete
# - Cancels remaining tasks if one raises an exception
# - Raises the first exception that occurred
```
## Async Generators
Create async iterators for streaming data:
```python
import asyncio
from typing import AsyncIterator
# ✅ REQUIRED: Async generators for streaming data
async def fetch_paginated_data(api_url: str) -> AsyncIterator[dict]:
"""Fetch paginated data, yielding each item."""
page = 1
while True:
try:
response = await fetch_data(f"{api_url}?page={page}")
items = response.get("items", [])
if not items:
break
for item in items:
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.