backend-lambda
Skill329 starsChanged 6 days agoMIT-0View on GitHub
Use when writing Lambda handlers or idp_common Python code: thin handlers, reuse of the shared library, logging, retries and Lambda conventions.
- Installs packages
In this repository42 other files it gives its agents.
- .claude/rules/agents.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- add-modelSkill
- agent-capability-reviewSkill
- api-rbac-testSkill
- code-reviewSkill
- create-hf-dataset-prSkill
- curate-security-resultsSkill
- cut-release-changelogSkill
- dependabot-prsSkill
- documentationSkill
- extraction-pipelineSkill
- fix-single-issueSkill
- frontend-uiSkill
- full-test-batterySkill
- infrastructureSkill
- live-auth-checksSkill
- live-eval-and-costSkill
- prepare-changelogSkill
- prep-develop-for-releaseSkill
- product-demoSkill
- pr-review-ciSkill
- pr-reviewSkill
- releaseSkill
- release-validationSkill
- remove-classification-flat-keysSkill
- repo-quality-reviewSkill
- run-benchmarksSkill
- run-stack-testsSkill
- srt-security-scanSkill
- sync-pii-anonymizerSkill
- testing-qaSkill
- test-upgradeSkill
- transform-deploy-testSkill
- ui-i18nSkill
- update-solution-profileSkill
- ux-test-ciSkill
- ux-testSkill
- ux-test-stories-ciSkill
- ux-test-storiesSkill
- work-the-backlog-hazardsSkill
- work-the-backlogSkill
The file
We split this skill into the rules it gives an agent
10 rules. About 0 are common, 1 is distinctive, and 9 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
9
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 18
Every Lambda function lives in its own directory under src/lambda/:
- Distinctive: line 27
ALWAYS follow this pattern for new Lambda functions:
- Very specific: line 62
Handler: Always handler(event, context) in index.py → SAM references as Handler: index.handler
- Very specific: line 64
X-Ray: Import and call patch_all() at module level
- Very specific: line 124
When adding a new Lambda to patterns/unified/template.yaml:
- Very specific: line 125
Use AWS::Serverless::Function resource type
- Very specific: line 127
Add security suppression metadata for cfn-nag (W89, W92) and checkov (CKV_AWS_116, CKV_AWS_117, CKV_AWS_115)
- Very specific: line 128
Create a dedicated AWS::Logs::LogGroup with KMS encryption and configurable retention
- Very specific: line 130
Use !Sub "arn:${AWS::Partition}:..." for ALL ARNs (GovCloud compatibility)
- Very specific: line 131
Use !Sub "...${AWS::URLSuffix}" instead of hardcoded amazonaws.com
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Backend Lambda Development — GenAI IDP Accelerator
Stack & Runtime
- Python: 3.12 (target:
>=3.12,<3.14) - Framework: AWS SAM (
AWS::Serverless-2016-10-31) - Packaging: Zip (utility Lambdas) or Container Image via ECR (processing Lambdas)
- Architecture:
arm64preferred - Linting: ruff (line-length 88, double quotes, isort, TID251 banned-api rules)
- Type Checking: basedpyright (basic mode, Python 3.12, Linux platform)
- Testing: pytest with
@pytest.mark.unit/@pytest.mark.integrationmarkers
Lambda File Structure
Every Lambda function lives in its own directory under src/lambda/:
src/lambda/<function_name>/
├── index.py # ALWAYS named index.py
├── requirements.txt # Function-specific deps
└── __pycache__/Lambda Handler Template
ALWAYS follow this pattern for new Lambda functions:
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
import boto3
import json
import os
import logging
from typing import Any
from aws_xray_sdk.core import xray_recorder, patch_all
patch_all()
logger = logging.getLogger()
logger.setLevel(os.environ.get("LOG_LEVEL", "INFO"))
# Module-level AWS client initialization (connection reuse across invocations)
dynamodb = boto3.resource("dynamodb")
# Use TYPE_CHECKING guard for type stubs that aren't available at runtime
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from mypy_boto3_dynamodb.service_resource import Table
else:
Table = object
@xray_recorder.capture("function_name")
def handler(event: dict[str, Any], context: Any) -> dict[str, Any]:
"""Brief description of what this handler does."""
...Key Patterns (MUST follow)
- Handler: Always
handler(event, context)inindex.py→ SAM references asHandler: index.handler - Logging:
logging.getLogger()at module level; level fromLOG_LEVELenv var - X-Ray: Import and call
patch_all()at module level - AWS clients: Initialize at module level (outside handler) for connection reuse
- Environment variables:
os.environ['REQUIRED']for required,os.environ.get('OPTIONAL', 'default')for optional - Error handling: Catch
botocore.exceptions.ClientErrorexplicitly; uselogger.error(..., exc_info=True)for stack traces - License header: First two lines of EVERY file must be the MIT-0 copyright + SPDX header
Return Patterns
- SQS batch processor:
{"batchItemFailures": [{"itemIdentifier": id}]} - API-style:
{"statusCode": 200|400|500, "body": message}
idp_common Library (lib/idp_common_pkg/)
The shared library powering all processing. Key modules:
idp_common.models—Document,Page,Section,Status(Pydantic v2)idp_common.docs_service— Factory:create_document_service()idp_common.config—ConfigurationManagerfor DynamoDB-backed configidp_common.bedrock— Bedrock FM client with caching and guardrailsidp_common.extraction— Data extraction (traditional + agentic modes)idp_common.classification— Document classificationidp_common.ocr— OCR (Textract + Bedrock backends)idp_common.evaluation— Evaluation with stickler-evalidp_common.agents— Strands agent integration
Modular installation — only install what the Lambda needs:
pip install -e "lib/idp_common_pkg[core]" # Minimal
pip install -e "lib/idp_common_pkg[ocr]" # OCR support
pip install -e "lib/idp_common_pkg[extraction]" # Extraction
pip install -e "lib/idp_common_pkg[all]" # EverythingLazy loading: idp_common/__init__.py uses __getattr__ for lazy submodule imports. Don't import submodules eagerly at package level. It defers to importlib/sys.modules and caches nothing itself — a second cache can hold a different object for the same name, which makes mock.patch unreliable (#1159). ⚠️ Patch at the point of use, and check how the consumer imported the name: a module-level from idp_common import s3 is patched through the consumer (idp_common.<consumer>.s3.write_content), a function-local from idp_common.image import f through sys.modules (idp_common.image.f). The wrong target fails silently, as a mock with zero calls. See "Lazy submodule loading" in lib/idp_common_pkg/idp_common/README.md.
Banned Imports
from idp_sdk._core import ...— BANNED. Usefrom idp_sdk import IDPClientinstead.- This is enforced by ruff rule
TID251.
Key Dependencies
boto3==1.42.0,pydantic>=2.12.0,jsonschema>=4.25.1strands-agents==1.14.0(agent framework)bedrock-agentcore>=0.1.1PyYAML>=6.0.0,deepdiff>=6.0.0
Ruff Configuration Highlights
line-length = 88
target-version = "py312"
select = ["E4", "E7", "E9", "F"]
extend-select = ["I", "TID251"] # isort + banned API
quote-style = "double"Note: every tracked .py file is linted, including any file you add. What ruff.toml excludes is a named per-file list of pre-existing debt ([lint] exclude, [format] exclude), generated from scripts/lint_debt.json and ratcheted by make check-lint-debt — never add to it.
Pyright Configuration Highlights
typeCheckingMode:basic(not strict)reportUndefinedVariable:errorreportReturnType:warningreportCallIssue:warning- Most other checks are relaxed (
none) — this is intentional for gradual adoption
Adding a New Lambda to the SAM Template
When adding a new Lambda to patterns/unified/template.yaml:
- Use
AWS::Serverless::Functionresource type - Include
PermissionsBoundaryconditional:!If [HasPermissionsBoundary, !Ref PermissionsBoundaryArn, !Ref AWS::NoValue] - Add security suppression metadata for cfn-nag (W89, W92) and checkov (CKV_AWS_116, CKV_AWS_117, CKV_AWS_115)
- Create a dedicated
AWS::Logs::LogGroupwith KMS encryption and configurable retention - Pass standard env vars:
LOG_LEVEL,METRIC_NAMESPACE,STACK_NAME - Use
!Sub "arn:${AWS::Partition}:..."for ALL ARNs (GovCloud compatibility) - Use
!Sub "...${AWS::URLSuffix}"instead of hardcodedamazonaws.com
Commands
make ruff-lint # Lint with auto-fix
make format # Format Python code
make typecheck # basedpyright type checking
make test # Run all tests
cd lib/idp_common_pkg && make test-unit # Unit tests only
cd lib/idp_common_pkg && make dev # Install in edit modeDoes it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

