视觉画布设计
canvas-design
基于设计原则创作静态视觉作品,用于海报与品牌图形。
technical-documentation【文档与办公】Writes clear, structured technical documentation including READMEs, API docs, getting-started guides, and architectural overviews following industry conventions and developer experience best practices.
独立 GitHub 快照 · 自动分类 · 以原作者文档为准
name: technical-documentation description: Writes clear, structured technical documentation including READMEs, API docs, getting-started guides, and architectural overviews following industry conventions and developer experience best practices. license: MIT compatibility: opencode metadata: version: "1.0.0" domain: writing triggers: technical documentation, how do i write docs, README, API documentation, getting started guide, architecture overview, developer experience, docs-as-code getting started guide archetypes:
Writes clear, structured, and actionable technical documentation that helps developers understand, adopt, and use software effectively. Covers READMEs, API references, getting-started guides, and architectural overviews using proven conventions.
Use this skill when:
Avoid this skill for:
Identify the Audience and Purpose — Before writing a single word, determine:
Choose the Document Type — Match structure to purpose:
Draft the Content — Follow the structure for your document type:
Review for Developer Experience — Apply these lenses:
Format for Readability — Apply consistent formatting:
A good README answers these questions in order: What is this? Why should I care? How do I use it? How do I contribute?
# Project Name
One-sentence description that a stranger can understand. No jargon without explanation.
## Quick Start
Three to five commands or steps that get a developer from zero to "it works."
This section should be copy-paste executable for most users.
```bash
git clone https://github.com/owner/repo.git
cd repo
pip install -e .
# Run the example
python examples/basic.py
# Install from source
git clone https://github.com/owner/repo.git && cd repo
python -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
Copy .env.example to .env and fill in your values:
cp .env.example .env
# Edit .env with your database credentials, API keys, etc.
from myproject import Client
client = Client(api_key="your-key")
result = client.query("select count(*) from users")
print(result)
For large result sets, use streaming to avoid loading everything into memory:
with client.stream_query(
"SELECT * FROM events WHERE date > '2024-01-01'",
batch_size=1000
) as stream:
for batch in stream:
process_batch(batch)
Please read CONTRIBUTING.md before submitting pull requests.
### Pattern 2: API Reference Documentation (BAD vs GOOD)
API documentation should answer every question a consumer might have before they need to ask.
```markdown
<!-- ❌ BAD: Sparse, assumes too much knowledge -->
## Methods
### query(sql)
Executes SQL against the database. Returns results.
**Parameters:**
- `sql` — The SQL string
**Returns:** Results
---
<!-- ✅ GOOD: Complete, copy-paste ready, with edge cases covered -->
## Methods
### `query(sql: str) -> QueryResult`
Executes a SQL query against the connected database and returns structured results.
This method handles connection pooling automatically and supports both synchronous
and asynchronous execution contexts.
**Parameters:**
| Parameter | Type | Required | Description |
|-----------|--------|----------|--------------------------------------|
| `sql` | `str` | Yes | SQL query string to execute |
| `params` | `list` | No | Positional parameters for prepared statements |
| `timeout` | `int` | No | Query timeout in seconds (default: 30) |
**Returns:**
`QueryResult` object containing:
| Attribute | Type | Description |
|-------------|---------------|------------------------------------|
| `rows` | `list[dict]` | Result rows as dictionaries |
| `columns` | `list[str]` | Column names in order |
| `row_count` | `int` | Number of rows returned |
| `affected` | `int` | Rows affected (for INSERT/UPDATE) |
**Example:**
```python
result = client.query(
"SELECT id, name FROM users WHERE active = ?",
params=[True],
timeout=10
)
for row in result.rows:
print(f"{row['id']}: {row['name']}")
Error Handling:
| Error Type | When Raised | Recovery |
|---|---|---|
ConnectionError | Database unavailable | Retry with exponential backoff |
QueryTimeoutError | Query exceeded timeout limit | Simplify query or increase timeout |
ParseError | SQL syntax error | Validate SQL before execution |
Notes:
stream_query() to avoid memory pressureparams) are required for user-supplied input to prevent SQL injection
### Pattern 3: Getting Started Guide Structure
A getting started guide should take a developer from "never heard of this" to "building something real" in under 15 minutes.
```markdown
# Getting Started with [Project Name]
This guide walks you through your first working integration in about 10 minutes.
## What You'll Build
By the end of this guide, you'll have a running application that:
1. Connects to [Service/API/Database]
2. Performs a real operation (not "hello world")
3. Handles errors gracefully
**Prerequisites:**
- Python 3.10+ installed (`python --version` should show 3.10 or higher)
- An active [Account Type] with your API key from the [Dashboard URL]
- At least 500MB of free disk space
## Step 1: Install the SDK
```bash
pip install project-sdk
Verify the installation:
python -c "import project_sdk; print(project_sdk.__version__)"
# Should print something like: 2.4.1
If you see ModuleNotFoundError, ensure your virtual environment is activated:
source .venv/bin/activate # On macOS/Linux
# or
.venv\Scripts\activate # On Windows
Create a file called config.yaml in your project root:
api_key: "your-api-key-here"
environment: "development"
timeout: 30
⚠️ Security Note: Never commit your API key to version control. Add
config.yamlto your.gitignore.
Create main.py:
from project_sdk import Client, ConfigError
try:
client = Client.from_config("config.yaml")
# This is a real query — not "hello world"
response = client.list_resources(limit=10)
for resource in response.items:
print(f"{resource.id}: {resource.name} ({resource.status})")
except ConfigError as e:
print(f"Configuration error: {e}")
print("Check that config.yaml exists and contains a valid api_key.")
except ConnectionError as e:
print(f"Connection failed: {e}")
print("Verify your API key is correct and the service is reachable.")
Run it:
python main.py
# Expected output:
# abc123: My Resource (active)
# def456: Another Resource (pending)
# ...
### Pattern 4: Architecture Overview
An architecture overview explains the "why" behind system design decisions without drowning readers in implementation details.
```markdown
# System Architecture
This document describes the high-level architecture of [Project Name], including component responsibilities, data flow, and technology choices.
## High-Level Overview
[Project Name] follows a **service-oriented architecture** with three primary tiers:
┌─────────────┐ ┌──────────────┐ ┌──────────────────┐ │ Client App │────▶│ API Layer │────▶│ Data Services │ │ (Web/Mobile)│ │ (FastAPI) │ │ (PostgreSQL + │ │ │◀────│ │◀────│ Redis Cache) │ └─────────────┘ └──────┬───────┘ └──────────────────┘ │ ┌──────▼───────┐ │ Background │ │ Workers │ │ (Celery) │ └──────────────┘
**Key Design Decisions:**
1. **API Gateway Pattern** — All external traffic routes through a single FastAPI entry point for authentication, rate limiting, and request validation before reaching business logic.
2. **CQRS Separation** — Read operations use Redis-cached queries (fast path). Write operations go through the command pipeline with event sourcing for audit trails.
3. **Async Workers** — CPU-intensive tasks (report generation, data processing) are offloaded to Celery workers, keeping the API layer responsive.
## Component Responsibilities
### API Layer (FastAPI)
The public-facing entry point. Handles:
- Request/response serialization (Pydantic models)
- Authentication via JWT tokens
- Input validation and sanitization
- Rate limiting (100 req/min per API key)
- Structured logging (JSON format, correlation IDs)
**Not its responsibility:** Business logic, data persistence, or background processing.
### Data Services
**PostgreSQL** — Primary data store for:
- User accounts and profiles
- Transaction records (immutable audit trail)
- Configuration and metadata
**Redis** — Cache layer for:
- Session storage (TTL-based expiration)
- Query result caching (5-minute default TTL)
- Distributed rate limiting counters
### Background Workers
Celery workers consume from RabbitMQ queues:
- `high_priority` — Time-sensitive operations (webhooks, real-time notifications)
- `standard` — Report generation, data syncs, batch processing
- `low_priority` — Analytics aggregation, cleanup tasks
Each queue has configurable concurrency limits to prevent resource contention.
## Data Flow Example: Creating a Resource
1. **Client** sends POST `/resources` with JSON body and JWT token
2. **API Layer** validates the token, deserializes the request into a Pydantic model
3. **Business Logic** creates the record in PostgreSQL within a database transaction
4. **Event Emitter** publishes a `resource.created` event to RabbitMQ
5. **Worker** consumes the event and triggers downstream processes (notifications, cache invalidation)
6. **Response** returns HTTP 201 with the created resource representation
## Technology Rationale
| Component | Choice | Why | Alternative Considered |
|-----------|--------|-----|----------------------|
| API Framework | FastAPI | Native async support, automatic OpenAPI docs, Pydantic integration | Django REST Framework, Flask + Marshmallow |
| Database | PostgreSQL | ACID compliance, JSONB for flexible schemas, mature ORM support | MySQL, MongoDB |
| Cache | Redis | In-memory speed, pub/sub for real-time updates, native TTL | Memcached, local LRU cache |
| Task Queue | Celery + RabbitMQ | Battle-tested at scale, retry semantics, priority queues | RQ, Airflow (too heavy), Temporal (overkill) |
## Scaling Considerations
- **Read-heavy workloads:** Redis cache hit ratio typically 85-92%, reducing PostgreSQL load by ~60%
- **Write scaling:** PostgreSQL read replicas serve 40% of queries; primary handles all writes
- **Horizontal scaling:** API layer and workers are stateless — add instances behind a load balancer
- **Bottlenecks to watch:** Redis memory usage (maxmemory policy: `allkeys-lru`), RabbitMQ queue depth (>10K items triggers alert)
When writing or reviewing technical documentation, produce:
| Skill | Purpose |
|---|---|
humanizer | Detects and removes AI writing patterns after drafting docs to produce natural, human-sounding prose |