aws-lambda-python-integration
Provides AWS Lambda integration patterns for Python with cold start optimization. Use when deploying Python functions to AWS Lambda, choosing between AWS Chalice and raw Python approaches, optimizing cold starts, configuring API Gateway or ALB integration, or implementing serverless Python applications. Triggers include "create lambda python", "deploy python lambda", "chalice lambda aws", "python lambda cold start", "aws lambda python performance", "python serverless framework".
What this skill does
# AWS Lambda Python Integration
Patterns for creating high-performance AWS Lambda functions in Python with optimized cold starts and clean architecture.
## Overview
AWS Lambda Python integration with two approaches: **AWS Chalice** (full-featured framework) and **Raw Python** (minimal overhead). Both support API Gateway/ALB integration with production-ready configurations.
## When to Use
Use this skill when:
- Creating new Lambda functions in Python
- Migrating existing Python applications to Lambda
- Optimizing cold start performance for Python Lambda
- Choosing between framework-based and minimal Python approaches
- Configuring API Gateway or ALB integration
- Setting up deployment pipelines for Python Lambda
## Instructions
### 1. Choose Your Approach
| Approach | Cold Start | Best For | Complexity |
|----------|------------|----------|------------|
| AWS Chalice | < 200ms | REST APIs, rapid development, built-in routing | Low |
| Raw Python | < 100ms | Simple handlers, maximum control, minimal dependencies | Low |
### 2. Project Structure
#### AWS Chalice Structure
```
my-chalice-app/
├── app.py # Main application with routes
├── requirements.txt # Dependencies
├── .chalice/
│ ├── config.json # Chalice configuration
│ └── deploy/ # Deployment artifacts
├── chalicelib/ # Additional modules
│ ├── __init__.py
│ └── services.py
└── tests/
└── test_app.py
```
#### Raw Python Structure
```
my-lambda-function/
├── lambda_function.py # Handler entry point
├── requirements.txt # Dependencies
├── template.yaml # SAM/CloudFormation template
└── src/ # Additional modules
├── __init__.py
├── handlers.py
└── utils.py
```
### 3. Implementation Examples
See the [References](#references) section for detailed implementation guides. Quick examples:
**AWS Chalice:**
```python
from chalice import Chalice
app = Chalice(app_name='my-api')
@app.route('/')
def index():
return {'message': 'Hello from Chalice!'}
```
**Raw Python:**
```python
def lambda_handler(event, context):
return {
'statusCode': 200,
'body': json.dumps({'message': 'Hello from Lambda!'})
}
```
## Core Concepts
### Cold Start Optimization
Key strategies:
1. **Initialize at module level** - Persists across warm invocations
2. **Use lazy loading** - Defer heavy imports until needed
3. **Cache boto3 clients** - Reuse connections between invocations
See [Raw Python Lambda](references/raw-python-lambda.md#cold-start-optimization) for detailed patterns.
### Connection Management
Create clients at module level and reuse:
```python
_dynamodb = None
def get_table():
global _dynamodb
if _dynamodb is None:
_dynamodb = boto3.resource('dynamodb').Table('my-table')
return _dynamodb
```
### Environment Configuration
```python
class Config:
TABLE_NAME = os.environ.get('TABLE_NAME')
DEBUG = os.environ.get('DEBUG', 'false').lower() == 'true'
@classmethod
def validate(cls):
if not cls.TABLE_NAME:
raise ValueError("TABLE_NAME required")
```
## Best Practices
### Memory and Timeout Configuration
- **Memory**: Start with 256MB for simple handlers, 512MB for complex operations
- **Timeout**: Set based on expected processing time
- Simple handlers: 3-5 seconds
- API with DB calls: 10-15 seconds
- Data processing: 30-60 seconds
### Dependencies
Keep `requirements.txt` minimal:
```txt
# Core AWS SDK - always needed
boto3>=1.35.0
# Only add what you need
requests>=2.32.0 # If calling external APIs
pydantic>=2.5.0 # If using data validation
```
### Error Handling
Return proper HTTP codes with request ID:
```python
def lambda_handler(event, context):
try:
result = process_event(event)
return {'statusCode': 200, 'body': json.dumps(result)}
except ValueError as e:
return {'statusCode': 400, 'body': json.dumps({'error': str(e)})}
except Exception as e:
print(f"Error: {str(e)}") # Log to CloudWatch
return {'statusCode': 500, 'body': json.dumps({'error': 'Internal error'})}
```
See [Raw Python Lambda](references/raw-python-lambda.md#error-handling) for structured error patterns.
### Logging
Use structured logging for CloudWatch Insights:
```python
import logging, json
logger = logging.getLogger()
logger.setLevel(logging.INFO)
# Structured log
logger.info(json.dumps({
'eventType': 'REQUEST',
'requestId': context.aws_request_id,
'path': event.get('path')
}))
```
See [Raw Python Lambda](references/raw-python-lambda.md#logging) for advanced patterns.
## Deployment Options
### Quick Start
> **Validation Checkpoint:** Always run `serverless print` or `sam validate` before deploying to catch configuration errors early.
**Serverless Framework:**
```yaml
# serverless.yml
service: my-python-api
provider:
name: aws
runtime: python3.12 # or python3.11
functions:
api:
handler: lambda_function.lambda_handler
events:
- http:
path: /{proxy+}
method: ANY
```
**AWS SAM:**
```yaml
# template.yaml
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
ApiFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: ./
Handler: lambda_function.lambda_handler
Runtime: python3.12 # or python3.11
Events:
ApiEvent:
Type: Api
Properties:
Path: /{proxy+}
Method: ANY
```
**AWS Chalice:**
```bash
chalice new-project my-api
cd my-api
chalice local 8080 # Test locally before deploying
chalice deploy --stage dev
```
> **Validation Checkpoint:** Test locally with `chalice local` or `sam local invoke` before deploying to production.
For complete deployment configurations including CI/CD, environment-specific settings, and advanced SAM/Serverless patterns, see [Serverless Deployment](references/serverless-deployment.md).
## Constraints and Warnings
### Lambda Limits
- **Deployment package**: 250MB unzipped maximum (50MB zipped)
- **Memory**: 128MB to 10GB
- **Timeout**: 15 minutes maximum
- **Concurrent executions**: 1000 default (adjustable)
- **Environment variables**: 4KB total size
### Python-Specific Considerations
- **Cold start**: Python has excellent cold start performance; avoid heavy imports at module level
- **Dependencies**: Keep `requirements.txt` minimal; use Lambda Layers for shared dependencies
- **Native dependencies**: Must be compiled for Amazon Linux 2 (x86_64 or arm64)
### Common Pitfalls
1. **Importing heavy libraries at module level** - Defer to function level if not always needed
2. **Not handling Lambda context** - Use `context.get_remaining_time_in_millis()` for timeout awareness
3. **Not validating input** - Always validate and sanitize event data
4. **Printing sensitive data** - Be careful with logs and CloudWatch
**Error Recovery:** If deployment fails, check CloudWatch logs for initialization errors and run `sam logs` to diagnose issues.
### Security Considerations
- Never hardcode credentials; use IAM roles and environment variables
- Validate all input data
- Use least privilege IAM policies
- Enable CloudTrail for audit logging
## References
For detailed guidance on specific topics:
- **[AWS Chalice](references/chalice-lambda.md)** - Complete Chalice setup, routing, middleware, deployment
- **[Raw Python Lambda](references/raw-python-lambda.md)** - Minimal handler patterns, module caching, packaging
- **[Serverless Deployment](references/serverless-deployment.md)** - Serverless Framework, SAM, CI/CD pipelines
- **[Testing Lambda](references/testing-lambda.md)** - pytest, moto, SAM Local, localstack
## Examples
### Example 1: Create an AWS Chalice REST API
**Input:**
```
Create a Python Lambda REST API using AWS Chalice for a todo application
```
**Process:**
1. Initialize Chalice project with `chalice new-project`
2. ConfigRelated 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.