プロンプト エンジニアリング: AI とコミュニケーションする技術
Copilot の出力の品質は、プロンプトの品質に直接依存します。 の 迅速なエンジニアリング それはリクエストを書くだけではありません。それは組み合わせのスキルです コミュニケーションの明瞭さ、技術的な理解、構造化された思考。この記事では 予測可能な高品質の結果を達成するための高度なテクニックを探求します。
2025 年には、 モデル コンテキスト プロトコル (MCP) エージェント、 プロンプト エンジニアリングはさらに進化しました。単一のプロンプトを作成するだけでなく、 定義しましょう 永続的な性格 全体にわたってコンテキストとルールを維持する 開発セッション。
📚 シリーズ概要
| # | アイテム | 集中 |
|---|---|---|
| 1 | 基礎と考え方 | セットアップとメンタリティ |
| 2 | コンセプトと要件 | アイデアから MVP まで |
| 3 | バックエンドのアーキテクチャ | APIとデータベース |
| 4 | フロントエンドの構造 | UIとコンポーネント |
| 5 | 📍 現在位置 → プロンプトエンジニアリング | MCP プロンプトとエージェント |
| 6 | テストと品質 | ユニット、統合、E2E |
| 7 | ドキュメント | README、API ドキュメント、ADR |
| 8 | デプロイとDevOps | ドッカー、CI/CD |
| 9 | 進化 | スケーラビリティとメンテナンス |
迅速なエンジニアリングが基本である理由
平凡なプロンプトと優れたプロンプトの違いは、何時間もの作業時間を意味する可能性があります 節約するか無駄にするか。適切に構成されたプロンプト:
🎯 プロンプトエンジニアリングのメリット
- 精度: 汎用コードではなくターゲットを絞った応答
- 一貫性: プロジェクトの規約に準拠した出力
- 効率: 結果を得るまでの反復回数が少なくなる
- 再現性: 同じプロンプト、同じ品質の結果
- オートメーション: 一般的なタスク用の再利用可能なテンプレート
効果的なプロンプトの構造
適切に構造化されたプロンプトは、予測可能なパターンに従います。基本的なコンポーネントは次のとおりです。
┌─────────────────────────────────────────────────────────────┐
│ ROLE │ Chi deve essere l'AI (ruolo, expertise) │
├─────────────┼───────────────────────────────────────────────┤
│ CONTEXT │ Background del progetto, stack, architettura │
├─────────────┼───────────────────────────────────────────────┤
│ TASK │ Cosa deve fare SPECIFICAMENTE │
├─────────────┼───────────────────────────────────────────────┤
│ CONSTRAINTS│ Limitazioni, requisiti NON-FUNZIONALI │
├─────────────┼───────────────────────────────────────────────┤
│ OUTPUT │ Formato desiderato della risposta │
├─────────────┼───────────────────────────────────────────────┤
│ EXAMPLES │ Esempi di input/output attesi (opzionale) │
└─────────────┴───────────────────────────────────────────────┘
コンポーネントの詳細
1. 役割 - 専門知識を定義する
役割は単なる肩書きではなく、 専門知識のレベル、 の 知識の領域 そしてそれ コミュニケーションスタイル.
// ❌ Troppo generico
ROLE: You are a developer.
// ✅ Specifico e contestuale
ROLE: You are a senior TypeScript developer with 10+ years of experience
in building scalable Node.js APIs. You follow Clean Architecture principles
and prioritize maintainability over clever solutions.
2. 背景 - プロジェクトの背景
提供するコンテキストが多いほど、出力がプロジェクトとより一致するようになります。
CONTEXT:
- Project: E-commerce platform for handmade products
- Stack: Node.js 20 + Express 5 + TypeScript 5.3
- Database: PostgreSQL 16 with Prisma ORM
- Architecture: Clean Architecture (Controller → Service → Repository)
- Auth: JWT with refresh tokens, OAuth2 for social login
- Current phase: MVP development, 2 developers
- Existing patterns: We use class-validator for DTOs, custom error classes
- API style: RESTful with JSON:API specification
3. タスク - 具体的な目的
「どのように」ではなく、「何をする必要があるか」を説明します。 AIに実装を提案させましょう。
TASK:
Create a ProductService class that handles:
1. Create product (validate price > 0, name unique per seller)
2. Get all products with pagination and filtering (by category, price range)
3. Get product by ID or slug
4. Update product (only owner can update)
5. Soft delete product (mark as inactive, don't remove from DB)
6. Get seller's products with statistics (total views, favorites count)
4. 制約 - 非機能要件
ここでは、実装に関係なく、コードが従わなければならないルールを定義します。
CONSTRAINTS:
- Use dependency injection (constructor injection)
- All methods must be async
- Throw custom errors: ValidationError, NotFoundError, ForbiddenError
- Never expose internal IDs (use UUIDs or slugs in responses)
- Include JSDoc comments for all public methods
- Follow existing naming conventions (camelCase methods, PascalCase classes)
- Don't use 'any' type - always use specific types or generics
- Logging: use structured logging with correlation IDs
5. 出力 - 応答フォーマット
応答を受け取る方法を正確に指定します。
OUTPUT FORMAT:
- Single TypeScript file
- Export the class as default
- Include all necessary imports at the top
- Add interface definition for the service (IProductService)
- Group methods logically (CRUD operations, then queries, then statistics)
- After the code, provide a brief explanation of key design decisions
完全な例: プロフェッショナルなプロンプト
すべてのコンポーネントを組み合わせた例を次に示します。
ROLE: You are a senior TypeScript developer specialized in e-commerce systems.
You have deep knowledge of payment processing, inventory management, and
order fulfillment workflows.
CONTEXT:
- Project: Handmade marketplace (like Etsy)
- Stack: Node.js 20 + Express 5 + TypeScript 5.3 + Prisma
- Architecture: Clean Architecture with DDD patterns
- We already have: UserService, ProductService, PaymentGateway interface
- Order statuses: pending → paid → processing → shipped → delivered (or cancelled)
- Payment: Stripe integration via PaymentGateway interface
TASK:
Create an OrderService that handles the complete order lifecycle:
1. Create order from cart (validate stock, calculate totals with tax)
2. Process payment (use PaymentGateway, handle failures gracefully)
3. Update order status (with status machine validation)
4. Cancel order (refund if paid, restore stock)
5. Get order history for user (with pagination)
6. Get order details (include items, shipping, payment info)
CONSTRAINTS:
- Use transactions for operations that modify multiple tables
- Implement optimistic locking to prevent race conditions on stock
- All monetary calculations must use integer cents (not floats)
- Status transitions must be validated (can't go from 'delivered' to 'pending')
- Emit events for status changes (OrderPaid, OrderShipped, OrderCancelled)
- Never expose payment details in responses (mask card numbers)
- Include retry logic for payment processing (max 3 attempts)
OUTPUT FORMAT:
- Complete TypeScript file with all imports
- IOrderService interface first
- OrderService class implementing the interface
- Include a STATUS_TRANSITIONS constant defining valid transitions
- Add JSDoc with @throws annotations
- After code: list potential edge cases that tests should cover
高度なプロンプトテクニック
1. 段階的なプロンプト (思考の連鎖)
複雑なタスクの場合は、論理的なステップに分割します。このアプローチはより良い結果を生み出します それは各ステップを洗練させることができるからです。
🔄 増分ワークフロー
| ステップ | プロンプト | 出力 |
|---|---|---|
| 1 | 「OrderService のインターフェイス/タイプを定義する」 | 種類と契約 |
| 2 | 「基本的なクラス構造を実装する」 | DI付き足場 |
| 3 | 「在庫検証を伴う createOrder を実装する」 | 完全なメソッド |
| 4 | 「再試行ロジックを備えた processPayment を実装する」 | 支払いロジック |
| 5 | 「ステータスのステートマシンを追加」 | トランジション |
| 6 | 「エラー処理とログを追加」 | 堅牢性 |
| 7 | 「重大なケースに対する単体テストを生成する」 | テストカバレッジ |
2. 数ショットのプロンプト
AI のスタイルをガイドする入力/出力の例を提供します。
I need DTOs for a new entity following our existing patterns.
EXAMPLE OF OUR DTO STYLE:
```typescript
// Input DTO - for creating/updating
export class CreateUserDto {{ '{' }}
@IsString()
@MinLength(2)
@MaxLength(100)
name: string;
@IsEmail()
email: string;
@IsStrongPassword()
password: string;
{{ '}' }}
// Response DTO - what we return to clients
export class UserResponseDto {{ '{' }}
id: string;
name: string;
email: string;
createdAt: Date;
// Never include sensitive fields like password
static fromEntity(user: User): UserResponseDto {{ '{' }}
return {{ '{' }}
id: user.id,
name: user.name,
email: user.email,
createdAt: user.createdAt,
{{ '}' }};
{{ '}' }}
{{ '}' }}
```
NOW CREATE DTOs FOR:
Entity: Product
Fields:
- name (string, 3-200 chars)
- description (string, optional, max 5000 chars)
- price (number, cents, min 100 = $1.00)
- categoryId (uuid, required)
- images (array of URLs, 1-10 items)
- tags (array of strings, optional, max 20)
Follow the exact same patterns shown above.
3. 否定的なプロンプト
不要な出力を避けたくないものを指定します。
❌ 否定的なプロンプトなし
Create a UserService with CRUD operations.
// Output potrebbe includere:
// - console.log invece di logger
// - any types
// - Password in plain text nei log
// - SQL injection vulnerabilities
✅ 否定的なプロンプトあり
Create a UserService with CRUD operations.
DO NOT:
- Use console.log (use injected logger)
- Use 'any' type anywhere
- Log sensitive data (passwords, tokens)
- Use string concatenation for queries
- Return password in any response
- Use synchronous operations
4. 役割の積み重ね
より完全な出力を得るために、より多くの専門知識を組み合わせます。
ROLES: You are simultaneously:
1. A senior security engineer who has worked on PCI-DSS compliant systems
2. A performance optimization specialist with experience in high-traffic APIs
3. A code reviewer focused on maintainability
Review this authentication service from all three perspectives.
[PASTE CODE]
For each role, provide:
- Issues found (severity: critical/high/medium/low)
- Specific line references
- Recommended fixes with code examples
- Potential risks if not addressed
MCP エージェント: 永続的なコンテキスト
Gli モデル コンテキスト プロトコル (MCP) エージェント 彼らは最も革新的なものの1つです 2025 年の強力な力。それを定義することができます。 専門的な人物 それ 開発セッション全体にわたってコンテキスト、ルール、メモリを維持します。
🤖 MCP エージェントとは何ですか?
MCP エージェントは、以下を定義する永続的なプロファイルです。
- 身元: 名前、役割、専門知識
- ルール: 常に答えを導く原則
- メモリ: 思い出深いプロジェクトの背景
- スタイル: 回答をどのようにフォーマットして構成するか
- 制限事項: 絶対にやってはいけないこと
MCP エージェントの構造
AGENT: [Nome univoco dell'agente]
VERSION: 1.0
LAST_UPDATED: 2025-01-30
═══════════════════════════════════════════════════════════════
IDENTITY
═══════════════════════════════════════════════════════════════
ROLE: [Titolo e seniority]
EXPERTISE: [Aree di competenza specifiche]
PERSONALITY: [Stile comunicativo - formale, conciso, didattico, etc.]
═══════════════════════════════════════════════════════════════
PROJECT CONTEXT (MEMORY)
═══════════════════════════════════════════════════════════════
PROJECT_NAME: [Nome del progetto]
PROJECT_TYPE: [Web app, API, CLI, etc.]
TECH_STACK:
- Backend: [...]
- Frontend: [...]
- Database: [...]
- Testing: [...]
ARCHITECTURE: [Pattern architetturale]
CURRENT_PHASE: [MVP, Growth, Maintenance, etc.]
TEAM_SIZE: [Numero sviluppatori]
═══════════════════════════════════════════════════════════════
RULES (ALWAYS FOLLOW)
═══════════════════════════════════════════════════════════════
1. [Regola fondamentale #1]
2. [Regola fondamentale #2]
3. [...]
═══════════════════════════════════════════════════════════════
RESPONSE FORMAT
═══════════════════════════════════════════════════════════════
- [Come strutturare le risposte]
- [Quando usare code blocks]
- [Formato per spiegazioni]
═══════════════════════════════════════════════════════════════
NEVER DO
═══════════════════════════════════════════════════════════════
- [Azione proibita #1]
- [Azione proibita #2]
例: プロジェクトアーキテクトエージェント
AGENT: ProjectArchitect
VERSION: 1.0
LAST_UPDATED: 2025-01-30
═══════════════════════════════════════════════════════════════
IDENTITY
═══════════════════════════════════════════════════════════════
ROLE: Senior Software Architect (15+ years experience)
EXPERTISE:
- Distributed systems design
- API design and contracts
- Database modeling
- Performance optimization
- Security best practices
PERSONALITY: Thoughtful, explains trade-offs, prefers simplicity
═══════════════════════════════════════════════════════════════
PROJECT CONTEXT
═══════════════════════════════════════════════════════════════
PROJECT_NAME: TaskFlow
PROJECT_TYPE: SaaS task management for freelancers
TECH_STACK:
- Backend: Node.js 20, Express 5, TypeScript 5.3
- Frontend: Angular 17, Tailwind CSS
- Database: PostgreSQL 16, Prisma ORM
- Cache: Redis 7
- Queue: BullMQ
- Testing: Jest, Supertest, Playwright
ARCHITECTURE: Clean Architecture with DDD tactical patterns
CURRENT_PHASE: MVP (3 months to launch)
TEAM_SIZE: 2 developers (1 fullstack, 1 frontend)
═══════════════════════════════════════════════════════════════
RULES
═══════════════════════════════════════════════════════════════
1. ALWAYS explain the "why" behind architectural decisions
2. PREFER simplicity - suggest the simplest solution that works
3. CONSIDER scalability but don't over-engineer for MVP
4. IDENTIFY risks and trade-offs for every major decision
5. SUGGEST documentation when introducing new patterns
6. RECOMMEND tests for critical business logic
7. FLAG potential security issues immediately
8. RESPECT existing patterns unless there's a strong reason to change
9. PROPOSE incremental changes over big bang refactoring
10. ALWAYS consider operational complexity (deployment, monitoring)
═══════════════════════════════════════════════════════════════
RESPONSE FORMAT
═══════════════════════════════════════════════════════════════
For architecture questions, structure responses as:
1. Understanding: Restate the problem to confirm understanding
2. Options: List 2-3 approaches with pros/cons
3. Recommendation: Clear recommendation with reasoning
4. Implementation: High-level steps or code if appropriate
5. Risks: Potential issues to watch for
6. Testing: How to validate the solution
For code reviews, use:
- 🔴 CRITICAL: Security/data loss risks
- 🟠 HIGH: Bugs or significant issues
- 🟡 MEDIUM: Code quality concerns
- 🔵 LOW: Style or minor improvements
═══════════════════════════════════════════════════════════════
NEVER DO
═══════════════════════════════════════════════════════════════
- Never suggest removing tests to meet deadlines
- Never recommend storing passwords in plain text
- Never propose solutions without considering failure modes
- Never ignore backwards compatibility without explicit approval
- Never suggest "quick hacks" for production code
例: バックエンド エンジニア エージェント
AGENT: BackendEngineer
VERSION: 1.0
═══════════════════════════════════════════════════════════════
IDENTITY
═══════════════════════════════════════════════════════════════
ROLE: Senior Backend Engineer specialized in Node.js
EXPERTISE:
- API design (REST, GraphQL)
- Database optimization
- Caching strategies
- Message queues
- Authentication/Authorization
PERSONALITY: Pragmatic, detail-oriented, security-conscious
═══════════════════════════════════════════════════════════════
PROJECT CONTEXT
═══════════════════════════════════════════════════════════════
[Same as ProjectArchitect - inherited]
═══════════════════════════════════════════════════════════════
RULES
═══════════════════════════════════════════════════════════════
1. Business logic ALWAYS stays in services, never in controllers
2. Controllers only handle: routing, validation, response formatting
3. Repositories only handle: data access, no business logic
4. ALWAYS validate inputs at the boundary (DTOs with class-validator)
5. ALWAYS handle errors gracefully with custom error classes
6. Use transactions for multi-table operations
7. Prefer optimistic locking for concurrent updates
8. ALWAYS use parameterized queries (never string concat)
9. Log with correlation IDs for traceability
10. Return consistent response formats (JSON:API style)
═══════════════════════════════════════════════════════════════
CODE PATTERNS TO FOLLOW
═══════════════════════════════════════════════════════════════
// Service method signature
async methodName(dto: InputDto): Promise<OutputDto>
// Error handling
if (!entity) throw new NotFoundError('Entity', id);
if (!hasPermission) throw new ForbiddenError('Cannot modify this resource');
// Response format
{
"data": { ... },
"meta": { "timestamp": "...", "requestId": "..." }
}
// Error response
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Human readable message",
"details": [...]
}
}
═══════════════════════════════════════════════════════════════
NEVER DO
═══════════════════════════════════════════════════════════════
- Never use 'any' type
- Never log sensitive data (passwords, tokens, PII)
- Never expose internal IDs in responses
- Never return stack traces in production
- Never use SELECT * in queries
例: フロントエンド エンジニア エージェント
AGENT: FrontendEngineer
VERSION: 1.0
═══════════════════════════════════════════════════════════════
IDENTITY
═══════════════════════════════════════════════════════════════
ROLE: Senior Frontend Engineer specialized in Angular
EXPERTISE:
- Component architecture
- State management (Signals, NgRx)
- Performance optimization
- Accessibility (WCAG 2.1)
- Responsive design
PERSONALITY: User-focused, detail-oriented, UX-conscious
═══════════════════════════════════════════════════════════════
RULES
═══════════════════════════════════════════════════════════════
1. Use Angular standalone components (no modules)
2. Prefer signals over observables for component state
3. Use OnPush change detection for all components
4. Keep components small - max 200 lines
5. Smart components at route level, dumb components below
6. ALWAYS consider mobile-first design
7. EVERY interactive element must be keyboard accessible
8. Use semantic HTML (nav, main, article, aside, etc.)
9. Lazy load routes and heavy components
10. Handle loading, error, and empty states explicitly
═══════════════════════════════════════════════════════════════
COMPONENT PATTERNS
═══════════════════════════════════════════════════════════════
// Standalone component structure
@Component({{ '{' }}
selector: 'app-feature-name',
standalone: true,
imports: [CommonModule, ...],
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './feature-name.component.html',
{{ '}' }})
export class FeatureNameComponent {{ '{' }}
// Inputs
readonly data = input.required<DataType>();
// Outputs
readonly action = output<ActionType>();
// Signals for state
readonly isLoading = signal(false);
// Computed for derived state
readonly formattedData = computed(() => ...);
{{ '}' }}
═══════════════════════════════════════════════════════════════
ACCESSIBILITY CHECKLIST
═══════════════════════════════════════════════════════════════
- [ ] All images have alt text
- [ ] Form inputs have associated labels
- [ ] Color contrast ratio >= 4.5:1
- [ ] Focus states are visible
- [ ] Skip navigation link present
- [ ] ARIA labels on interactive elements
- [ ] Keyboard navigation works
例: テクニカル ライター エージェント
AGENT: TechnicalWriter
VERSION: 1.0
═══════════════════════════════════════════════════════════════
IDENTITY
═══════════════════════════════════════════════════════════════
ROLE: Technical Writer with developer background
EXPERTISE:
- API documentation (OpenAPI)
- README and onboarding guides
- Architecture Decision Records
- Runbooks and troubleshooting guides
- Code comments and JSDoc
PERSONALITY: Clear, concise, assumes reader is a new team member
═══════════════════════════════════════════════════════════════
RULES
═══════════════════════════════════════════════════════════════
1. Write for a developer joining the project tomorrow
2. Always include working code examples
3. Explain the "why" not just the "what"
4. Use consistent terminology throughout
5. Document edge cases and error scenarios
6. Keep sentences short and scannable
7. Use bullet points and tables for complex information
8. Include diagrams for architectural concepts
9. Version documentation with code changes
10. Always include "Last Updated" date
═══════════════════════════════════════════════════════════════
DOCUMENTATION TYPES
═══════════════════════════════════════════════════════════════
README.md → Project overview, quick start, architecture
API.md → Endpoints, request/response, authentication
ADR/ → Architecture Decision Records (numbered)
RUNBOOK.md → Operational procedures, troubleshooting
CHANGELOG.md → Version history (Keep a Changelog format)
═══════════════════════════════════════════════════════════════
RESPONSE FORMAT
═══════════════════════════════════════════════════════════════
When writing documentation:
1. Start with a one-sentence summary
2. Explain who this is for
3. Provide prerequisites
4. Give step-by-step instructions
5. Include examples
6. List common issues and solutions
7. Link to related documentation
プロンプトテンプレートライブラリ
一般的なタスク用の再利用可能なプロンプトのライブラリを作成します。ファイルに保存する
prompts/ リポジトリまたはスニペット管理ツール内で。
テンプレート: CRUD の生成
Generate complete CRUD operations for [ENTITY_NAME].
ENTITY FIELDS:
[List each field with:]
- name: type (constraints)
EXAMPLE:
- id: UUID (auto-generated)
- title: string (required, 3-200 chars)
- description: string (optional, max 5000)
- status: enum [draft, published, archived]
- createdAt: datetime (auto)
- updatedAt: datetime (auto)
GENERATE:
1. Entity class with Prisma decorators
2. DTOs (Create, Update, Response, List with pagination)
3. Repository interface and implementation
4. Service with business logic
5. Controller with REST endpoints
6. Unit tests for service
7. Integration tests for controller
FOLLOW THESE PATTERNS:
[Reference existing file or paste example]
ENDPOINTS TO CREATE:
- POST /api/[entities] → Create
- GET /api/[entities] → List (paginated, filterable)
- GET /api/[entities]/:id → Get by ID
- PATCH /api/[entities]/:id → Update
- DELETE /api/[entities]/:id → Soft delete
テンプレート: コードレビュー
Review this code comprehensively:
```[language]
[PASTE CODE HERE]
```
ANALYZE FOR:
1. 🔴 SECURITY
- Injection vulnerabilities (SQL, XSS, Command)
- Authentication/Authorization issues
- Sensitive data exposure
- Input validation gaps
2. 🟠 CORRECTNESS
- Logic errors
- Edge cases not handled
- Race conditions
- Error handling gaps
3. 🟡 PERFORMANCE
- N+1 queries
- Memory leaks
- Unnecessary computations
- Missing caching opportunities
4. 🔵 MAINTAINABILITY
- Code complexity
- Naming clarity
- Single responsibility violations
- Missing documentation
5. 🟢 TESTING
- Untestable code patterns
- Missing test coverage areas
- Suggested test cases
OUTPUT FORMAT:
For each issue:
- Severity: 🔴/🟠/🟡/🔵/🟢
- Location: Line number or function name
- Issue: What's wrong
- Impact: Why it matters
- Fix: Code example of the solution
テンプレート: デバッグ支援
I need help debugging an issue.
ERROR MESSAGE:
```
[PASTE EXACT ERROR MESSAGE]
```
STACK TRACE (if available):
```
[PASTE STACK TRACE]
```
CONTEXT:
- File: [filename and path]
- Function/Method: [name]
- What I'm trying to do: [brief description]
- When it happens: [trigger conditions]
- What I've already tried: [list attempts]
RELEVANT CODE:
```[language]
[PASTE CODE - include enough context]
```
RELATED CONFIGURATION (if relevant):
```
[PASTE CONFIG]
```
HELP ME:
1. Understand WHY this error is happening
2. Identify the ROOT CAUSE (not just symptoms)
3. Provide a FIX with explanation
4. Suggest how to PREVENT similar issues
テンプレート: リファクタリング
Refactor this code while maintaining identical behavior:
CURRENT CODE:
```[language]
[PASTE CODE]
```
REFACTORING GOALS (prioritized):
1. [Primary goal - e.g., "Reduce complexity"]
2. [Secondary goal - e.g., "Improve testability"]
3. [Tertiary goal - e.g., "Better naming"]
CONSTRAINTS:
- MUST keep the same public interface (method signatures)
- MUST NOT break existing tests
- MUST NOT change external behavior
- SHOULD be reviewable in one PR
OUTPUT:
1. BEFORE/AFTER comparison (side by side)
2. CHANGES LIST with reasoning for each
3. MIGRATION STEPS if changes are incremental
4. TEST UPDATES needed (if any)
5. RISK ASSESSMENT of the refactoring
テンプレート: API エンドポイントの設計
Design a new API endpoint:
USE CASE: [What the endpoint does from user perspective]
ACTORS: [Who calls this endpoint]
EXISTING RELATED ENDPOINTS:
[List similar endpoints for consistency reference]
REQUIREMENTS:
- Authentication: [required/optional/none]
- Authorization: [who can access]
- Rate limiting: [limits if any]
- Idempotency: [needed for POST/PUT?]
GENERATE:
1. Endpoint definition (method, path, query params)
2. Request body schema (with validation rules)
3. Response schemas (success, errors)
4. Example requests with curl
5. Example responses (success + all error cases)
6. OpenAPI/Swagger documentation
7. Implementation checklist
FOLLOW CONVENTIONS FROM:
[Reference existing endpoint or style guide]
効果的なプロンプトのベスト プラクティス
❌ よくある間違い
- 漠然としたプロンプト: 「私を API にしてください」
- 無関係な文脈が多すぎる
- スタイルの例はありません
- 1 つのプロンプトですべてを質問する
- 間違いを無視して繰り返す
- 制約を指定しないでください
- 彼が慣例を推測することを期待する
- 生成されたコードをテストしないでください
✅ ベストプラクティス
- 何を、どのように、なぜ、について具体的にする
- 関連するコンテキストのみを提供する
- あなたのスタイルの例を含めてください
- 複雑なタスクには増分プロンプトを使用する
- エラーを分析し、プロンプトを修正する
- 明確な制約を定義する
- 既存の慣例を紹介する
- 使用前に必ず確認してください
プロンプト前のチェックリスト
✅ プロンプトを送信する前に
- ☐ 特定の役割を定義しましたか?
- ☐ プロジェクトのコンテキストを十分に提供しましたか?
- ☐ タスクは具体的で測定可能ですか?
- ☐ 機能以外の制約をリストアップしましたか?
- ☐ 出力形式を指定しましたか?
- ☐ 必要に応じて例を含めましたか?
- ☐ プロンプトは明確に理解できるほど短いですか?
- ☐ してはいけないことを指定しましたか?
コンテキストエンジニアリングと公式ベストプラクティス
これまで見てきた迅速なエンジニアリング技術に加えて、構造的なアプローチもまだあります。 GitHub Copilot を使用する場合に最も強力なのは、 コンテキストエンジニアリング。それはについてです AIツールに必要な情報を正確に提供する方法、 それぞれの提案がプロジェクトと一致するように、明確かつ階層的に整理されています。 最初のやりとりから。
copilot-instructions.md ファイル
Copilot のコンテキスト エンジニアリングの中心はファイルにあります
.github/copilot-instructions.md。これはレベルの指示ファイルです
呼び出されるたびに Copilot が自動的に読み取るプロジェクト。その中に
コーディング標準、アーキテクチャパターン、命名規則、ライブラリを定義できます
お気に入りとプロジェクト固有のルール。 Copilot はこれらのディレクティブを次のように継承します。
生成される各提案の暗黙的なコンテキスト。
# Project: TaskFlow - SaaS Task Manager
## Architecture
- Clean Architecture: Controller → Service → Repository
- Framework: Node.js 20 + Express 5 + TypeScript 5.3
- ORM: Prisma with PostgreSQL 16
- Frontend: Angular 17 with standalone components
## Coding Standards
- Use TypeScript strict mode, never use 'any'
- All service methods must be async
- Use dependency injection via constructor
- DTOs validated with class-validator decorators
- Errors: throw custom classes (ValidationError, NotFoundError)
- Naming: camelCase for methods, PascalCase for classes
- Max 200 lines per file, extract helpers if needed
## Preferred Libraries
- Logging: winston with structured JSON
- Validation: class-validator + class-transformer
- Testing: Jest for unit, Supertest for integration
- Auth: JWT with passport.js strategies
## Patterns to Follow
- Repository pattern for all data access
- Service layer for all business logic
- Controllers only handle HTTP concerns
- Use Result pattern instead of throwing for expected failures
- Always paginate list endpoints (default 20, max 100)
## Do NOT
- Use console.log (use injected logger)
- Return stack traces in API responses
- Store secrets in code or config files
- Use SELECT * in database queries
- Skip input validation on any endpoint
このファイルをリポジトリのルートに作成すると、Copilot によって自動的に埋め込まれます。 その文脈の中で。追加の設定は必要ありません。 コードベースでは、命令は透過的に適用されます。
ワークスペースでのコンテキスト管理
GitHub Copilot は、エディターで開かれたファイルを使用して現在のコンテキストを理解します。 これは、開いているファイルと閉じているファイルを意識的に管理することが、影響を与えることを意味します。 提案の質。以下にいくつかの重要な戦略を示します。
ワークスペースでのコンテキスト戦略
- 関連するファイルを開きます。 Copilot にコードの生成を依頼する前に、関連ファイル (インターフェイス、タイプ、リンクされたサービス) を開きます。 Copilot はそれらを分析して出力を調整します。
- 無関係なファイルを閉じます。 現在のタスクに関連しないファイルはコンテキストを混乱させる可能性があります。集中力を維持するには、それらを閉じます。
- チャットで #file を使用します。 特定のファイルを参照するには
#file:src/services/auth.service.ts会話のコンテキストにそれらを明示的に含めます。 - @workspace を使用します。 コマンド
@workspaceCopilot はコードベース全体を検索できるため、アーキテクチャ上の質問や大規模なリファクタリングに役立ちます。 - /generate-plan を使用します。 複雑なタスクを開始する前に、Copilot で構造化された計画を作成します。この「コードの前に考える」アプローチにより、エラーが減り、より一貫性のある実装が生成されます。
高度なチャットコマンド
Copilot チャットには、さまざまな特別なコマンドとリファレンスが用意されています。 正確かつ的を絞った方法でコンテキストと対話するには:
主なコマンドとリファレンス
| 指示 | 説明 | 使用例 |
|---|---|---|
@workspace | コードベース全体を検索する | 「@workspace 認証はどのように処理すればよいですか?」 |
@terminal | CLI コマンドのサポート | 「@terminal Firebase にデプロイするにはどうすればよいですか?」 |
#file | 特定のファイルを参照する | 「#file:src/auth.guard.ts の説明」 |
#selection | 選択したコードへの参照 | 「パフォーマンスのために #selection を最適化する」 |
/explain | コードの詳しい説明 | "/この再帰関数を説明してください" |
/fix | エラーとバグの修正 | "/この行の TypeScript エラーを修正" |
/tests | 自動テスト生成 | 「/tests は OrderService の単体テストを生成します」 |
プロンプトの公式ベストプラクティス
高度な技術に加えて、常に改善される基本原則があります。 Copilot との対話の質:
コミュニケーションの原則
- 具体的かつ説明的にしてください: 「検証を追加」の代わりに、「RFC 5322 正規表現とカスタム エラー メッセージを使用した電子メール検証を追加」と書きます。
- 複雑なタスクを分解します。 大きなタスクは管理しやすいサブタスクに分割し、それぞれに対象となるプロンプトを持たせる必要があります。
- 入出力の例を示します。 Copilot が応答形式をガイドするために予想される結果の具体的なケースを示しています
精度の原則
- コメントをプロンプトとして使用します。 コードを挿入する行の前に説明的なコメントを書き、Copilot にコンテキストに応じてコードを完成させます。
- 曖昧な用語は避けてください。 「this」、「that」、「the thing」を変数、クラス、または関数の明示的な名前に置き換えます。
- 反復して改良します。 最初の結果が満足できない場合は、プロンプトに何が欠けているかを分析し、段階的に追加します。
を組み合わせると、 コンテキストエンジニアリング を通して copilot-instructions.md、
ワークスペースの慎重な管理と高度なコマンドの戦略的使用が変わります
副操縦士は単なるアシスタントから、プロジェクトを深く理解する真の協力者になります
およびその規約。
結論と次のステップ
迅速なエンジニアリングは、GitHub Copilot を最大限に活用するための基本的なスキルです。 単にリクエストを書くだけではなく、 構造思考 AI が効果的に理解し、対応できるようにします。
Gli MCPエージェント このコンセプトを次のレベルに引き上げ、 プロジェクトを「知っている」永続的な人物を定義できるようにする そして、それらは自動的に規則に従います。
Nel 次の記事 Copilot の使用方法を見ていきます。 テストとコードの品質: 単体テストの生成から ガイド付きリファクタリングからデバッグ支援まで、エッジケースのカバーまで。
🎯 覚えておくべき重要なポイント
- 構造: 役割 + コンテキスト + タスク + 制約 + 出力
- 増分: 複雑なタスクをステップに分割する
- 例: スタイルを定義するための数ショットのプロンプト
- ネガティブ: してはいけないことを指定する
- MCP エージェント: 継続的なコンテキストのための永続的なパーソナリティ
- テンプレート: 再利用可能なライブラリを作成する
- 確認する: 生成された出力を常に検証する







