@patricio0312rev/skillset 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/LICENSE +21 -0
  3. package/README.md +176 -0
  4. package/bin/cli.js +37 -0
  5. package/package.json +55 -0
  6. package/src/commands/init.js +301 -0
  7. package/src/index.js +168 -0
  8. package/src/lib/config.js +200 -0
  9. package/src/lib/generator.js +166 -0
  10. package/src/utils/display.js +95 -0
  11. package/src/utils/readme.js +196 -0
  12. package/src/utils/tool-specific.js +233 -0
  13. package/templates/ai-engineering/agent-orchestration-planner/ SKILL.md +266 -0
  14. package/templates/ai-engineering/cost-latency-optimizer/ SKILL.md +270 -0
  15. package/templates/ai-engineering/doc-to-vector-dataset-generator/ SKILL.md +239 -0
  16. package/templates/ai-engineering/evaluation-harness/ SKILL.md +219 -0
  17. package/templates/ai-engineering/guardrails-safety-filter-builder/ SKILL.md +226 -0
  18. package/templates/ai-engineering/llm-debugger/ SKILL.md +283 -0
  19. package/templates/ai-engineering/prompt-regression-tester/ SKILL.md +216 -0
  20. package/templates/ai-engineering/prompt-template-builder/ SKILL.md +393 -0
  21. package/templates/ai-engineering/rag-pipeline-builder/ SKILL.md +244 -0
  22. package/templates/ai-engineering/tool-function-schema-designer/ SKILL.md +219 -0
  23. package/templates/architecture/adr-writer/ SKILL.md +250 -0
  24. package/templates/architecture/api-versioning-deprecation-planner/ SKILL.md +331 -0
  25. package/templates/architecture/domain-model-boundaries-mapper/ SKILL.md +300 -0
  26. package/templates/architecture/migration-planner/ SKILL.md +376 -0
  27. package/templates/architecture/performance-budget-setter/ SKILL.md +318 -0
  28. package/templates/architecture/reliability-strategy-builder/ SKILL.md +286 -0
  29. package/templates/architecture/rfc-generator/ SKILL.md +362 -0
  30. package/templates/architecture/scalability-playbook/ SKILL.md +279 -0
  31. package/templates/architecture/system-design-generator/ SKILL.md +339 -0
  32. package/templates/architecture/tech-debt-prioritizer/ SKILL.md +329 -0
  33. package/templates/backend/api-contract-normalizer/ SKILL.md +487 -0
  34. package/templates/backend/api-endpoint-generator/ SKILL.md +415 -0
  35. package/templates/backend/auth-module-builder/ SKILL.md +99 -0
  36. package/templates/backend/background-jobs-designer/ SKILL.md +166 -0
  37. package/templates/backend/caching-strategist/ SKILL.md +190 -0
  38. package/templates/backend/error-handling-standardizer/ SKILL.md +174 -0
  39. package/templates/backend/rate-limiting-abuse-protection/ SKILL.md +147 -0
  40. package/templates/backend/rbac-permissions-builder/ SKILL.md +158 -0
  41. package/templates/backend/service-layer-extractor/ SKILL.md +269 -0
  42. package/templates/backend/webhook-receiver-hardener/ SKILL.md +211 -0
  43. package/templates/ci-cd/artifact-sbom-publisher/ SKILL.md +236 -0
  44. package/templates/ci-cd/caching-strategy-optimizer/ SKILL.md +195 -0
  45. package/templates/ci-cd/deployment-checklist-generator/ SKILL.md +381 -0
  46. package/templates/ci-cd/github-actions-pipeline-creator/ SKILL.md +348 -0
  47. package/templates/ci-cd/monorepo-ci-optimizer/ SKILL.md +298 -0
  48. package/templates/ci-cd/preview-environments-builder/ SKILL.md +187 -0
  49. package/templates/ci-cd/quality-gates-enforcer/ SKILL.md +342 -0
  50. package/templates/ci-cd/release-automation-builder/ SKILL.md +281 -0
  51. package/templates/ci-cd/rollback-workflow-builder/ SKILL.md +372 -0
  52. package/templates/ci-cd/secrets-env-manager/ SKILL.md +242 -0
  53. package/templates/db-management/backup-restore-runbook-generator/ SKILL.md +505 -0
  54. package/templates/db-management/data-integrity-auditor/ SKILL.md +505 -0
  55. package/templates/db-management/data-retention-archiving-planner/ SKILL.md +430 -0
  56. package/templates/db-management/data-seeding-fixtures-builder/ SKILL.md +375 -0
  57. package/templates/db-management/db-performance-watchlist/ SKILL.md +425 -0
  58. package/templates/db-management/etl-sync-job-builder/ SKILL.md +457 -0
  59. package/templates/db-management/multi-tenant-safety-checker/ SKILL.md +398 -0
  60. package/templates/db-management/prisma-migration-assistant/ SKILL.md +379 -0
  61. package/templates/db-management/schema-consistency-checker/ SKILL.md +440 -0
  62. package/templates/db-management/sql-query-optimizer/ SKILL.md +324 -0
  63. package/templates/foundation/changelog-writer/ SKILL.md +431 -0
  64. package/templates/foundation/code-formatter-installer/ SKILL.md +320 -0
  65. package/templates/foundation/codebase-summarizer/ SKILL.md +360 -0
  66. package/templates/foundation/dependency-doctor/ SKILL.md +163 -0
  67. package/templates/foundation/dev-environment-bootstrapper/ SKILL.md +259 -0
  68. package/templates/foundation/dev-onboarding-builder/ SKILL.md +556 -0
  69. package/templates/foundation/docs-starter-kit/ SKILL.md +574 -0
  70. package/templates/foundation/explaining-code/SKILL.md +13 -0
  71. package/templates/foundation/git-hygiene-enforcer/ SKILL.md +455 -0
  72. package/templates/foundation/project-scaffolder/ SKILL.md +65 -0
  73. package/templates/foundation/project-scaffolder/references/templates.md +126 -0
  74. package/templates/foundation/repo-structure-linter/ SKILL.md +0 -0
  75. package/templates/foundation/repo-structure-linter/references/conventions.md +98 -0
  76. package/templates/frontend/animation-micro-interaction-pack/ SKILL.md +41 -0
  77. package/templates/frontend/component-scaffold-generator/ SKILL.md +562 -0
  78. package/templates/frontend/design-to-component-translator/ SKILL.md +547 -0
  79. package/templates/frontend/form-wizard-builder/ SKILL.md +553 -0
  80. package/templates/frontend/frontend-refactor-planner/ SKILL.md +37 -0
  81. package/templates/frontend/i18n-frontend-implementer/ SKILL.md +44 -0
  82. package/templates/frontend/modal-drawer-system/ SKILL.md +377 -0
  83. package/templates/frontend/page-layout-builder/ SKILL.md +630 -0
  84. package/templates/frontend/state-ux-flow-builder/ SKILL.md +23 -0
  85. package/templates/frontend/table-builder/ SKILL.md +350 -0
  86. package/templates/performance/alerting-dashboard-builder/ SKILL.md +162 -0
  87. package/templates/performance/backend-latency-profiler-helper/ SKILL.md +108 -0
  88. package/templates/performance/caching-cdn-strategy-planner/ SKILL.md +150 -0
  89. package/templates/performance/capacity-planning-helper/ SKILL.md +242 -0
  90. package/templates/performance/core-web-vitals-tuner/ SKILL.md +126 -0
  91. package/templates/performance/incident-runbook-generator/ SKILL.md +162 -0
  92. package/templates/performance/load-test-scenario-builder/ SKILL.md +256 -0
  93. package/templates/performance/observability-setup/ SKILL.md +232 -0
  94. package/templates/performance/postmortem-writer/ SKILL.md +203 -0
  95. package/templates/performance/structured-logging-standardizer/ SKILL.md +122 -0
  96. package/templates/security/auth-security-reviewer/ SKILL.md +428 -0
  97. package/templates/security/dependency-vulnerability-triage/ SKILL.md +495 -0
  98. package/templates/security/input-validation-sanitization-auditor/ SKILL.md +76 -0
  99. package/templates/security/pii-redaction-logging-policy-builder/ SKILL.md +65 -0
  100. package/templates/security/rbac-policy-tester/ SKILL.md +80 -0
  101. package/templates/security/secrets-scanner/ SKILL.md +462 -0
  102. package/templates/security/secure-headers-csp-builder/ SKILL.md +404 -0
  103. package/templates/security/security-incident-playbook-generator/ SKILL.md +76 -0
  104. package/templates/security/security-pr-checklist-skill/ SKILL.md +62 -0
  105. package/templates/security/threat-model-generator/ SKILL.md +394 -0
  106. package/templates/testing/contract-testing-builder/ SKILL.md +492 -0
  107. package/templates/testing/coverage-strategist/ SKILL.md +436 -0
  108. package/templates/testing/e2e-test-builder/ SKILL.md +382 -0
  109. package/templates/testing/flaky-test-detective/ SKILL.md +416 -0
  110. package/templates/testing/integration-test-builder/ SKILL.md +525 -0
  111. package/templates/testing/mocking-assistant/ SKILL.md +383 -0
  112. package/templates/testing/snapshot-test-refactorer/ SKILL.md +375 -0
  113. package/templates/testing/test-data-factory-builder/ SKILL.md +449 -0
  114. package/templates/testing/test-reporting-triage-skill/ SKILL.md +469 -0
  115. package/templates/testing/unit-test-generator/ SKILL.md +548 -0
@@ -0,0 +1,196 @@
1
+ const { TOOLS, DOMAINS } = require('../lib/config');
2
+
3
+ /**
4
+ * Generate README.md content for the generated configuration
5
+ * @param {Object} config - Configuration object
6
+ * @param {Object} result - Generation result
7
+ * @returns {string} README content
8
+ */
9
+ function generateReadme(config, result) {
10
+ const tool = TOOLS[config.tool];
11
+ const timestamp = new Date().toISOString();
12
+
13
+ return `# Development Skills Configuration
14
+
15
+ > Generated with [SkillSet](https://github.com/patricio0312rev/skillset)
16
+
17
+ ## Overview
18
+
19
+ - **Tool**: ${tool.name}
20
+ - **Location**: \`${config.folder}/\`
21
+ - **Domains**: ${config.domains.length}
22
+ - **Skills**: ${result.skillsGenerated}
23
+ - **Generated**: ${new Date().toLocaleString()}
24
+
25
+ ## Usage
26
+
27
+ ${getDetailedUsageInstructions(config.tool, config.folder)}
28
+
29
+ ## Structure
30
+
31
+ \`\`\`
32
+ ${config.folder}/
33
+ ${generateStructureTree(config)}
34
+ \`\`\`
35
+
36
+ ## Domains Included
37
+
38
+ ${generateDomainsList(config)}
39
+
40
+ ## Updating
41
+
42
+ To regenerate or update your configuration:
43
+
44
+ \`\`\`bash
45
+ npx @patricio0312rev/skillset init
46
+ \`\`\`
47
+
48
+ Or if installed globally:
49
+
50
+ \`\`\`bash
51
+ skillset init
52
+ \`\`\`
53
+
54
+ ## Resources
55
+
56
+ - [SkillSet Documentation](https://github.com/patricio0312rev/skillset)
57
+ - [Skills Collection](https://github.com/patricio0312rev/skills)
58
+ - [Claude Code Documentation](https://claude.com/claude-code)
59
+ - [Agent Skills Documentation](https://agentskills.io)
60
+
61
+ ## Tips
62
+
63
+ - Commit these files to version control
64
+ - Share with your team for consistent AI assistance
65
+ - Update regularly as your project evolves
66
+ - Customize skill instructions for your specific needs
67
+
68
+ ---
69
+
70
+ *Generated by SkillSet v${require('../../package.json').version}*
71
+ `;
72
+ }
73
+
74
+ function getDetailedUsageInstructions(tool, folder) {
75
+ const instructions = {
76
+ 'claude-code': `### With Claude Code
77
+
78
+ Skills in this folder are automatically loaded by Claude Code.
79
+
80
+ \`\`\`bash
81
+ # Skills are available in your Claude Code session
82
+ # Reference them in your prompts
83
+ "Use the api-endpoint-generator skill to create a REST API"
84
+ \`\`\`
85
+
86
+ ### In VS Code / IDE
87
+
88
+ Skills are loaded from \`${folder}/\` automatically when you open this project in an IDE with Claude Code integration.`,
89
+
90
+ 'copilot': `### With GitHub Copilot (Agent Skills)
91
+
92
+ Skills in this folder follow GitHub's Agent Skills format and are automatically recognized by GitHub Copilot.
93
+
94
+ \`\`\`bash
95
+ # Skills are available when working in this repository
96
+ # GitHub Copilot will use them automatically for suggestions and code generation
97
+ \`\`\`
98
+
99
+ **Note**: GitHub also supports skills in \`.claude/skills/\` as a fallback location.`,
100
+
101
+ 'cursor': `### With Cursor
102
+
103
+ Skills in this folder are formatted as Project Rules for Cursor.
104
+
105
+ \`\`\`
106
+ # Use @-mentions in Cursor chat:
107
+ @.cursor/rules/api-endpoint-generator/RULE.md
108
+
109
+ # Or reference naturally in prompts:
110
+ "Using the API endpoint generator rule, create a REST API..."
111
+ \`\`\`
112
+
113
+ Cursor automatically detects and loads rules from \`.cursor/rules/\`.`,
114
+
115
+ 'other': `### With Any AI Tool
116
+
117
+ Skills in this folder use a universal format compatible with most AI coding assistants.
118
+
119
+ **Methods**:
120
+
121
+ 1. **Upload Method**: Upload relevant skill files to your AI chat
122
+ 2. **Reference**: Reference them in your prompts
123
+ 3. **Copy-Paste**: Or copy skill content directly into context
124
+
125
+ Example:
126
+ \`\`\`
127
+ [Upload: ${folder}/api-endpoint-generator/SKILL.md]
128
+
129
+ "Following the API endpoint generator skill, help me create..."
130
+ \`\`\``
131
+ };
132
+
133
+ return instructions[tool] || instructions.other;
134
+ }
135
+
136
+ function generateStructureTree(config) {
137
+ const lines = ['├── README.md'];
138
+ const toolInfo = TOOLS[config.tool];
139
+ const fileExtension = toolInfo.fileExtension || 'SKILL.md';
140
+
141
+ // Collect all skills across all domains
142
+ const allSkills = [];
143
+ config.domains.forEach((domain) => {
144
+ const skills = DOMAINS[domain].skills;
145
+
146
+ // Filter skills if specific ones were selected
147
+ let displaySkills = skills;
148
+ if (config.skills && config.skills.length > 0) {
149
+ displaySkills = skills.filter(skill =>
150
+ config.skills.includes(skill) ||
151
+ config.skills.includes(`${domain}/${skill}`)
152
+ );
153
+ }
154
+
155
+ displaySkills.forEach(skill => {
156
+ allSkills.push(skill);
157
+ });
158
+ });
159
+
160
+ // Display skills directly in the target folder
161
+ allSkills.forEach((skill, index) => {
162
+ const isLast = index === allSkills.length - 1;
163
+ const prefix = isLast ? '└──' : '├──';
164
+ lines.push(`${prefix} ${skill}/`);
165
+ lines.push(`${isLast ? ' ' : '│'} └── ${fileExtension}`);
166
+ });
167
+
168
+ return lines.join('\n');
169
+ }
170
+
171
+ function generateDomainsList(config) {
172
+ return config.domains.map(domain => {
173
+ const domainInfo = DOMAINS[domain];
174
+
175
+ // Filter skills if specific ones were selected
176
+ let displaySkills = domainInfo.skills;
177
+ if (config.skills && config.skills.length > 0) {
178
+ displaySkills = domainInfo.skills.filter(skill =>
179
+ config.skills.includes(skill) ||
180
+ config.skills.includes(`${domain}/${skill}`)
181
+ );
182
+ }
183
+
184
+ return `### ${domainInfo.name}
185
+
186
+ ${domainInfo.description}
187
+
188
+ **Skills** (${displaySkills.length}):
189
+ ${displaySkills.map(skill => `- \`${skill}\``).join('\n')}
190
+ `;
191
+ }).join('\n');
192
+ }
193
+
194
+ module.exports = {
195
+ generateReadme
196
+ };
@@ -0,0 +1,233 @@
1
+ const fs = require('fs-extra');
2
+ const path = require('path');
3
+ const { TOOLS } = require('../lib/config');
4
+
5
+ /**
6
+ * Generate tool-specific configuration files
7
+ * @param {Object} config - Configuration object
8
+ * @param {string} targetDir - Target directory path
9
+ * @param {Array} skillsList - List of generated skills
10
+ * @returns {Promise<Array>} Array of created file paths
11
+ */
12
+ async function generateToolSpecificFiles(config, targetDir, skillsList) {
13
+ const files = [];
14
+
15
+ switch (config.tool) {
16
+ case 'cursor':
17
+ const cursorFiles = await generateCursorFiles(config, targetDir, skillsList);
18
+ files.push(...cursorFiles);
19
+ break;
20
+
21
+ case 'copilot':
22
+ const copilotFiles = await generateCopilotFiles(config, targetDir, skillsList);
23
+ files.push(...copilotFiles);
24
+ break;
25
+
26
+ case 'claude-code':
27
+ case 'other':
28
+ // These use the multi-file structure as-is
29
+ const indexFile = await generateIndexFile(config, targetDir, skillsList);
30
+ if (indexFile) files.push(indexFile);
31
+ break;
32
+ }
33
+
34
+ return files;
35
+ }
36
+
37
+ /**
38
+ * Generate Cursor-specific files
39
+ */
40
+ async function generateCursorFiles(config, targetDir, skillsList) {
41
+ const files = [];
42
+
43
+ // Create usage instructions file inside the target directory
44
+ const instructionsPath = path.join(targetDir, 'CURSOR_USAGE.md');
45
+ const instructions = generateCursorInstructions(config, skillsList);
46
+ await fs.writeFile(instructionsPath, instructions);
47
+ files.push(instructionsPath);
48
+
49
+ return files;
50
+ }
51
+
52
+ /**
53
+ * Generate GitHub Copilot configuration
54
+ */
55
+ async function generateCopilotFiles(config, targetDir, skillsList) {
56
+ const files = [];
57
+
58
+ // Create usage instructions
59
+ const instructionsPath = path.join(targetDir, 'COPILOT_USAGE.md');
60
+ const instructions = generateCopilotInstructions(config, skillsList);
61
+ await fs.writeFile(instructionsPath, instructions);
62
+ files.push(instructionsPath);
63
+
64
+ return files;
65
+ }
66
+
67
+ /**
68
+ * Generate index file listing all skills
69
+ */
70
+ async function generateIndexFile(config, targetDir, skillsList) {
71
+ const content = `# Development Skills Index
72
+
73
+ ## Available Skills
74
+
75
+ ${skillsList.map(({ domain, skill }) => {
76
+ return `- **${skill}** (${domain}) - [View](${skill}/${TOOLS[config.tool].fileExtension})`;
77
+ }).join('\n')}
78
+
79
+ ## Quick Reference
80
+
81
+ ${generateQuickReference(skillsList)}
82
+ `;
83
+
84
+ const indexPath = path.join(targetDir, 'INDEX.md');
85
+ await fs.writeFile(indexPath, content);
86
+ return indexPath;
87
+ }
88
+
89
+ function generateQuickReference(skillsList) {
90
+ const byDomain = {};
91
+ skillsList.forEach(({ domain, skill }) => {
92
+ if (!byDomain[domain]) byDomain[domain] = [];
93
+ byDomain[domain].push(skill);
94
+ });
95
+
96
+ return Object.entries(byDomain).map(([domain, skills]) => {
97
+ return `### ${domain}\n${skills.map(s => `- ${s}`).join('\n')}`;
98
+ }).join('\n\n');
99
+ }
100
+
101
+ /**
102
+ * Generate Cursor usage instructions
103
+ */
104
+ function generateCursorInstructions(config, skillsList) {
105
+ return `# Using Development Skills with Cursor
106
+
107
+ ## Setup Complete
108
+
109
+ Your development skills are configured and ready to use.
110
+
111
+ ## How to Use
112
+
113
+ ### 1. @-Mentions (Primary Method)
114
+
115
+ The most powerful way to use skills in Cursor:
116
+
117
+ \`\`\`
118
+ @${config.folder}/api-endpoint-generator/RULE.md
119
+
120
+ Create a REST API for user management with:
121
+ - Authentication
122
+ - CRUD operations
123
+ - Rate limiting
124
+ \`\`\`
125
+
126
+ ### 2. Multiple Skills
127
+
128
+ Combine multiple skills for complex tasks:
129
+
130
+ \`\`\`
131
+ @${config.folder}/api-endpoint-generator/RULE.md
132
+ @${config.folder}/unit-test-generator/RULE.md
133
+
134
+ Create and test a payment processing API
135
+ \`\`\`
136
+
137
+ ### 3. In Composer
138
+
139
+ Use skills in Cursor's Composer mode for multi-file changes:
140
+
141
+ 1. Open Composer (Cmd/Ctrl + I)
142
+ 2. Add skill with @-mention
143
+ 3. Describe your task
144
+ 4. Cursor will apply changes across files
145
+
146
+ ## Tips
147
+
148
+ - **Specific Skills**: Use the most relevant skill for your task
149
+ - **Combine Skills**: Multiple skills can collaborate on complex tasks
150
+ - **Context**: Skills have access to your codebase context
151
+ - **Iterations**: Refine results by providing feedback
152
+
153
+ ## Available Skills
154
+
155
+ ${skillsList.map(({ domain, skill }) => `- **${skill}** (${domain})`).join('\n')}
156
+
157
+ ## Troubleshooting
158
+
159
+ **Skills not appearing in @-mentions?**
160
+ - Ensure files are in \`${config.folder}/\` directory
161
+ - Restart Cursor
162
+ - Check Cursor settings for custom rule paths
163
+
164
+ **Need different skills?**
165
+ Run: \`skillset init\` to reconfigure
166
+
167
+ ---
168
+
169
+ Happy coding with development skills!
170
+ `;
171
+ }
172
+
173
+ /**
174
+ * Generate GitHub Copilot instructions
175
+ */
176
+ function generateCopilotInstructions(config, skillsList) {
177
+ return `# GitHub Copilot - Development Skills
178
+
179
+ This project uses specialized development skills for different aspects of engineering.
180
+
181
+ ## Agent Skills
182
+
183
+ GitHub Copilot automatically recognizes and uses Agent Skills in this directory.
184
+
185
+ ${skillsList.map(({ domain, skill }) => {
186
+ return `### ${skill} (${domain})
187
+
188
+ Specialized skill for ${domain} tasks. See detailed instructions in \`${config.folder}/${skill}/SKILL.md\`
189
+ `;
190
+ }).join('\n')}
191
+
192
+ ## General Development Guidelines
193
+
194
+ When working on this project, follow these principles:
195
+
196
+ ### Code Quality
197
+ - Write clean, maintainable code
198
+ - Follow existing patterns in the codebase
199
+ - Add appropriate comments for complex logic
200
+ - Ensure code is self-documenting where possible
201
+
202
+ ### Testing
203
+ - Write tests for new features
204
+ - Maintain high test coverage
205
+ - Include edge cases in tests
206
+ - Follow testing patterns established in the project
207
+
208
+ ### Documentation
209
+ - Update documentation when adding features
210
+ - Keep README files current
211
+ - Document API changes
212
+ - Add inline documentation for public APIs
213
+
214
+ ## Getting Skill Details
215
+
216
+ For specific guidance on any aspect of development, refer to the detailed skill files:
217
+
218
+ \`\`\`
219
+ ${config.folder}/
220
+ ${skillsList.map(({ domain, skill }) => ` ${skill}/SKILL.md`).join('\n')}
221
+ \`\`\`
222
+
223
+ ---
224
+
225
+ *Generated by SkillSet - https://github.com/patricio0312rev/skillset*
226
+ `;
227
+ }
228
+
229
+ module.exports = {
230
+ generateToolSpecificFiles,
231
+ generateCursorFiles,
232
+ generateCopilotFiles
233
+ };
@@ -0,0 +1,266 @@
1
+ ---
2
+ name: agent-orchestration-planner
3
+ description: Designs multi-step agent workflows with tool usage, retry logic, state management, and budget controls. Provides orchestration diagrams, tool execution order, fallback strategies, and cost limits. Use for "AI agents", "agentic workflows", "multi-step AI", or "autonomous systems".
4
+ ---
5
+
6
+ # Agent Orchestration Planner
7
+
8
+ Design robust multi-step agent systems with tools and error handling.
9
+
10
+ ## Agent Architecture
11
+
12
+ ```
13
+ User Query → Planning → Tool Selection → Tool Execution → Result Synthesis → Response
14
+ ↓ ↓ ↓ ↓
15
+ Memory Retry Logic Validation Cost Tracking
16
+ ```
17
+
18
+ ## Agent Loop Pattern
19
+
20
+ ```python
21
+ from typing import List, Dict, Any
22
+
23
+ class Agent:
24
+ def __init__(self, tools: List[Tool], max_iterations: int = 5):
25
+ self.tools = tools
26
+ self.max_iterations = max_iterations
27
+ self.memory = []
28
+ self.cost_tracker = CostTracker()
29
+
30
+ def run(self, query: str) -> str:
31
+ self.memory.append({"role": "user", "content": query})
32
+
33
+ for iteration in range(self.max_iterations):
34
+ # Decide next action
35
+ action = self.plan_next_action()
36
+
37
+ if action["type"] == "final_answer":
38
+ return action["content"]
39
+
40
+ # Execute tool
41
+ result = self.execute_tool(action["tool"], action["params"])
42
+
43
+ # Track cost
44
+ self.cost_tracker.add(result["cost"])
45
+
46
+ # Check budget
47
+ if self.cost_tracker.exceeds_limit():
48
+ return self.budget_exceeded_response()
49
+
50
+ # Add to memory
51
+ self.memory.append({
52
+ "role": "tool",
53
+ "tool": action["tool"],
54
+ "result": result["data"]
55
+ })
56
+
57
+ return "Max iterations reached"
58
+
59
+ def plan_next_action(self) -> Dict:
60
+ prompt = self.build_planning_prompt()
61
+ response = llm(prompt)
62
+ return parse_action(response)
63
+ ```
64
+
65
+ ## Tool Orchestration
66
+
67
+ ```python
68
+ TOOL_ORDER = {
69
+ "search_web": 1, # Always try search first
70
+ "query_database": 2, # Then database
71
+ "call_api": 3, # Then external APIs
72
+ "generate_content": 4, # Finally generate
73
+ }
74
+
75
+ def select_tools(query: str, available_tools: List[Tool]) -> List[Tool]:
76
+ """Select and order tools based on query"""
77
+ # Use LLM to select relevant tools
78
+ tool_selection_prompt = f"""
79
+ Given this query: "{query}"
80
+
81
+ Which of these tools are needed? {[t.name for t in available_tools]}
82
+
83
+ Return JSON array of tool names in execution order.
84
+ """
85
+
86
+ selected_names = json.loads(llm(tool_selection_prompt))
87
+ selected_tools = [t for t in available_tools if t.name in selected_names]
88
+
89
+ # Sort by predefined order
90
+ selected_tools.sort(key=lambda t: TOOL_ORDER.get(t.name, 999))
91
+
92
+ return selected_tools
93
+ ```
94
+
95
+ ## Retry & Fallback Logic
96
+
97
+ ```python
98
+ def execute_with_retry(tool: Tool, params: Dict, max_retries: int = 3):
99
+ """Execute tool with exponential backoff retry"""
100
+ for attempt in range(max_retries):
101
+ try:
102
+ result = tool.execute(params)
103
+ return {"success": True, "data": result}
104
+ except ToolError as e:
105
+ if attempt == max_retries - 1:
106
+ # Try fallback tool
107
+ fallback = get_fallback_tool(tool.name)
108
+ if fallback:
109
+ return execute_with_retry(fallback, params, 1)
110
+
111
+ return {"success": False, "error": str(e)}
112
+
113
+ # Wait before retry
114
+ time.sleep(2 ** attempt)
115
+
116
+ FALLBACK_TOOLS = {
117
+ "search_web": "query_database",
118
+ "call_api": "use_cached_data",
119
+ }
120
+ ```
121
+
122
+ ## State Management
123
+
124
+ ```python
125
+ class AgentState:
126
+ def __init__(self):
127
+ self.memory = []
128
+ self.tool_results = {}
129
+ self.costs = 0.0
130
+ self.iteration = 0
131
+
132
+ def add_message(self, role: str, content: str):
133
+ self.memory.append({"role": role, "content": content})
134
+
135
+ def add_tool_result(self, tool_name: str, result: Any):
136
+ self.tool_results[tool_name] = result
137
+
138
+ def get_context(self) -> str:
139
+ """Build context from memory for next LLM call"""
140
+ return "\n".join([
141
+ f"{msg['role']}: {msg['content']}"
142
+ for msg in self.memory[-5:] # Last 5 messages
143
+ ])
144
+ ```
145
+
146
+ ## Budget & Cost Controls
147
+
148
+ ```python
149
+ class CostTracker:
150
+ def __init__(self, max_cost: float = 1.0):
151
+ self.max_cost = max_cost
152
+ self.total_cost = 0.0
153
+ self.breakdown = {}
154
+
155
+ def add(self, cost: float, category: str = "llm"):
156
+ self.total_cost += cost
157
+ self.breakdown[category] = self.breakdown.get(category, 0) + cost
158
+
159
+ def exceeds_limit(self) -> bool:
160
+ return self.total_cost >= self.max_cost
161
+
162
+ def remaining(self) -> float:
163
+ return self.max_cost - self.total_cost
164
+
165
+ # Use in agent
166
+ if cost_tracker.exceeds_limit():
167
+ return f"Budget limit reached. Used ${cost_tracker.total_cost:.4f}"
168
+ ```
169
+
170
+ ## Orchestration Diagram
171
+
172
+ ```mermaid
173
+ graph TD
174
+ A[User Query] --> B[Plan Action]
175
+ B --> C{Action Type?}
176
+ C -->|Tool Call| D[Execute Tool]
177
+ C -->|Final Answer| E[Return Response]
178
+ D --> F[Validate Result]
179
+ F -->|Success| G[Update Memory]
180
+ F -->|Failure| H[Retry/Fallback]
181
+ H --> D
182
+ G --> I{Budget OK?}
183
+ I -->|Yes| B
184
+ I -->|No| J[Budget Exceeded]
185
+ J --> E
186
+ ```
187
+
188
+ ## Planning Prompt
189
+
190
+ ```python
191
+ def build_planning_prompt(state: AgentState) -> str:
192
+ return f"""
193
+ You are an agent that can use tools to answer questions.
194
+
195
+ Available tools:
196
+ {json.dumps([t.schema for t in tools], indent=2)}
197
+
198
+ Conversation history:
199
+ {state.get_context()}
200
+
201
+ Based on the conversation, decide your next action:
202
+ 1. Call a tool (specify tool name and parameters)
203
+ 2. Provide final answer
204
+
205
+ If calling a tool, respond with:
206
+ {{"action": "tool_call", "tool": "tool_name", "params": {{...}}}}
207
+
208
+ If providing final answer, respond with:
209
+ {{"action": "final_answer", "content": "your answer"}}
210
+
211
+ Think step by step about what information you need.
212
+ """
213
+ ```
214
+
215
+ ## Multi-Agent Coordination
216
+
217
+ ```python
218
+ class MultiAgentSystem:
219
+ def __init__(self):
220
+ self.agents = {
221
+ "researcher": ResearchAgent(),
222
+ "coder": CodeAgent(),
223
+ "reviewer": ReviewAgent(),
224
+ }
225
+
226
+ def run(self, task: str):
227
+ # Researcher gathers information
228
+ context = self.agents["researcher"].run(task)
229
+
230
+ # Coder generates solution
231
+ code = self.agents["coder"].run(f"{task}\nContext: {context}")
232
+
233
+ # Reviewer validates
234
+ review = self.agents["reviewer"].run(f"Review this code:\n{code}")
235
+
236
+ if review["approved"]:
237
+ return code
238
+ else:
239
+ # Iterate with feedback
240
+ return self.agents["coder"].run(
241
+ f"Fix this code based on feedback:\n{review['feedback']}"
242
+ )
243
+ ```
244
+
245
+ ## Best Practices
246
+
247
+ 1. **Limit iterations**: Prevent infinite loops
248
+ 2. **Budget controls**: Track and limit costs
249
+ 3. **Tool validation**: Verify tool outputs
250
+ 4. **Error handling**: Graceful fallbacks
251
+ 5. **State persistence**: Save progress
252
+ 6. **Observability**: Log all actions
253
+ 7. **Human-in-loop**: Critical decisions
254
+
255
+ ## Output Checklist
256
+
257
+ - [ ] Agent loop implementation
258
+ - [ ] Tool selection logic
259
+ - [ ] Retry & fallback strategies
260
+ - [ ] State management
261
+ - [ ] Cost tracking
262
+ - [ ] Budget limits
263
+ - [ ] Orchestration diagram
264
+ - [ ] Planning prompts
265
+ - [ ] Error handling
266
+ - [ ] Observability/logging