agentic-ai-prompt-research
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAgentic AI Prompt Research
Agentic AI 提示词研究
Skill by ara.so — AI Agent Skills collection.
This project documents reconstructed prompt patterns and architectural designs from modern agentic AI coding assistants. It provides educational insights into how systems like Claude Code assemble dynamic prompts, coordinate multiple agents, manage security, and handle context windows.
由 ara.so 提供的技能 — AI Agent 技能合集。
本项目记录了从现代智能AI编码助手中重构的提示词模式与架构设计。它深入解析了像Claude Code这类系统如何组装动态提示词、协调多Agent、管理安全以及处理上下文窗口等内容,具有教育参考价值。
What This Project Provides
本项目提供的内容
A collection of 30+ documented patterns covering:
- Core Identity: Main system prompts, simple mode, default agent instructions, security boundaries
- Orchestration: Coordinator prompts, multi-agent communication protocols
- Specialized Agents: Verification, exploration, agent creation, configuration agents
- Security: Permission explainers, auto-approval classifiers, risk assessment
- Context Management: Conversation compaction, memory selection, session search
- Skills: Reusable multi-agent workflows (simplify, skillify, stuck, remember)
All patterns are based on behavioral observation and reverse engineering, not leaked proprietary code.
包含30余种已记录的模式,涵盖:
- 核心身份:主系统提示词、简易模式、默认Agent指令、安全边界
- 编排协调:协调者提示词、多Agent通信协议
- 专用Agent:验证、探索、Agent创建、配置Agent
- 安全机制:权限解释器、自动审批分类器、风险评估
- 上下文管理:对话压缩、记忆选择、会话搜索
- 技能模块:可复用的多Agent工作流(简化、技能化、故障排查、记忆管理)
所有模式均基于行为观察与逆向工程,并非泄露的专有代码。
Installation
安装步骤
bash
undefinedbash
undefinedClone the repository
Clone the repository
git clone https://github.com/Leonxlnx/agentic-ai-prompt-research.git
cd agentic-ai-prompt-research
git clone https://github.com/Leonxlnx/agentic-ai-prompt-research.git
cd agentic-ai-prompt-research
Browse the prompts directory
Browse the prompts directory
ls prompts/
No build or installation required — this is a documentation and research repository.ls prompts/
无需构建或安装——这是一个文档与研究类仓库。Repository Structure
仓库结构
prompts/
├── 01_main_system_prompt.md # Dynamic prompt assembly
├── 02_simple_mode.md # Minimal operation mode
├── 03_default_agent_prompt.md # Base agent instructions
├── 04_cyber_risk_instruction.md # Security boundaries
├── 05_coordinator_system_prompt.md # Multi-agent orchestration
├── 06_teammate_prompt_addendum.md # Agent communication
├── 07_verification_agent.md # Adversarial testing
├── 08_explore_agent.md # Read-only exploration
├── 09_agent_creation_architect.md # Dynamic agent generation
├── 10_statusline_setup_agent.md # Terminal configuration
├── 11_permission_explainer.md # Risk assessment
├── 12_yolo_auto_mode_classifier.md # Security classification
├── 13_tool_prompts.md # Tool-specific instructions
├── 14_tool_use_summary.md # Action summarization
├── 15_session_search.md # Semantic search
├── 16_memory_selection.md # Context selection
├── 17_auto_mode_critique.md # Classifier review
├── 18_proactive_mode.md # Autonomous operation
├── 19_simplify_skill.md # Code review pattern
├── 20_session_title.md # Title generation
├── 21_compact_service.md # Context compression
├── 22_away_summary.md # Session recaps
├── 23_chrome_browser_automation.md # Browser integration
├── 24_memory_instruction.md # Memory hierarchy
├── 25_skillify.md # Skill creation workflow
├── 26_stuck_skill.md # Diagnostic patterns
├── 27_remember_skill.md # Memory management
├── 28_update_config_skill.md # Configuration updates
├── 29_agent_summary.md # Progress updates
└── 30_prompt_suggestion.md # Follow-up predictionprompts/
├── 01_main_system_prompt.md # Dynamic prompt assembly
├── 02_simple_mode.md # Minimal operation mode
├── 03_default_agent_prompt.md # Base agent instructions
├── 04_cyber_risk_instruction.md # Security boundaries
├── 05_coordinator_system_prompt.md # Multi-agent orchestration
├── 06_teammate_prompt_addendum.md # Agent communication
├── 07_verification_agent.md # Adversarial testing
├── 08_explore_agent.md # Read-only exploration
├── 09_agent_creation_architect.md # Dynamic agent generation
├── 10_statusline_setup_agent.md # Terminal configuration
├── 11_permission_explainer.md # Risk assessment
├── 12_yolo_auto_mode_classifier.md # Security classification
├── 13_tool_prompts.md # Tool-specific instructions
├── 14_tool_use_summary.md # Action summarization
├── 15_session_search.md # Semantic search
├── 16_memory_selection.md # Context selection
├── 17_auto_mode_critique.md # Classifier review
├── 18_proactive_mode.md # Autonomous operation
├── 19_simplify_skill.md # Code review pattern
├── 20_session_title.md # Title generation
├── 21_compact_service.md # Context compression
├── 22_away_summary.md # Session recaps
├── 23_chrome_browser_automation.md # Browser integration
├── 24_memory_instruction.md # Memory hierarchy
├── 25_skillify.md # Skill creation workflow
├── 26_stuck_skill.md # Diagnostic patterns
├── 27_remember_skill.md # Memory management
├── 28_update_config_skill.md # Configuration updates
├── 29_agent_summary.md # Progress updates
└── 30_prompt_suggestion.md # Follow-up predictionKey Architectural Patterns
关键架构模式
1. Dynamic Prompt Assembly
1. 动态提示词组装
The system assembles prompts from modular components:
┌─────────────────────────────────────┐
│ Cacheable Prefix (stable) │
│ - Identity & safety rules │
│ - Permission configuration │
│ - Code style preferences │
│ - Tool usage patterns │
├─────────────────────────────────────┤ ← Cache boundary
│ Dynamic Suffix (per-session) │
│ - Available agents/skills │
│ - Memory file contents │
│ - Environment context │
│ - Active MCP servers │
└─────────────────────────────────────┘Example pattern from :
01_main_system_prompt.mdmarkdown
undefined系统通过模块化组件组装提示词:
┌─────────────────────────────────────┐
│ Cacheable Prefix (stable) │
│ - Identity & safety rules │
│ - Permission configuration │
│ - Code style preferences │
│ - Tool usage patterns │
├─────────────────────────────────────┤ ← Cache boundary
│ Dynamic Suffix (per-session) │
│ - Available agents/skills │
│ - Memory file contents │
│ - Environment context │
│ - Active MCP servers │
└─────────────────────────────────────┘来自 的示例模式:
01_main_system_prompt.mdmarkdown
undefinedCore identity established first
Core identity established first
You are Claude Code, an agentic AI coding assistant...
You are Claude Code, an agentic AI coding assistant...
Tool preferences defined
Tool preferences defined
When editing files, prefer multi_file_edit for batching...
When editing files, prefer multi_file_edit for batching...
Security boundaries set
Security boundaries set
Never execute commands that could compromise user data...
Never execute commands that could compromise user data...
Dynamic sections injected
Dynamic sections injected
[AVAILABLE_AGENTS: verification, explore, statusline_setup]
[MEMORY_FILES: .claude/project_rules.md, .claude/preferences.md]
[ENVIRONMENT: OS=linux, SHELL=bash, CWD=/home/user/project]
undefined[AVAILABLE_AGENTS: verification, explore, statusline_setup]
[MEMORY_FILES: .claude/project_rules.md, .claude/preferences.md]
[ENVIRONMENT: OS=linux, SHELL=bash, CWD=/home/user/project]
undefined2. Multi-Agent Coordination
2. 多Agent协调
Coordinator Pattern ():
05_coordinator_system_prompt.mdmarkdown
undefined协调者模式 ():
05_coordinator_system_prompt.mdmarkdown
undefinedPhased Workflow
Phased Workflow
- Planning Phase: Break task into subtasks
- Delegation Phase: Assign workers with specific contexts
- Synthesis Phase: Merge results and resolve conflicts
- Planning Phase: Break task into subtasks
- Delegation Phase: Assign workers with specific contexts
- Synthesis Phase: Merge results and resolve conflicts
Worker Communication
Worker Communication
- Workers receive: task description, relevant files, constraints
- Workers return: results, confidence score, blockers
- Coordinator decides: accept, retry, escalate
**Implementation approach:**
```python- Workers receive: task description, relevant files, constraints
- Workers return: results, confidence score, blockers
- Coordinator decides: accept, retry, escalate
**实现思路:**
```pythonConceptual multi-agent orchestration
Conceptual multi-agent orchestration
class AgentCoordinator:
def execute_task(self, user_request: str):
# Phase 1: Planning
subtasks = self.plan(user_request)
# Phase 2: Delegation
workers = [
self.spawn_agent("worker", task=t, context=self.get_context(t))
for t in subtasks
]
results = [w.execute() for w in workers]
# Phase 3: Synthesis
return self.merge_results(results)
def spawn_agent(self, agent_type: str, task: str, context: dict):
# Load base prompt + agent-specific addendum
base_prompt = self.load_prompt("03_default_agent_prompt.md")
agent_prompt = self.load_prompt(f"{agent_type}_prompt.md")
return Agent(
system_prompt=f"{base_prompt}\n\n{agent_prompt}",
task=task,
context=context
)undefinedclass AgentCoordinator:
def execute_task(self, user_request: str):
# Phase 1: Planning
subtasks = self.plan(user_request)
# Phase 2: Delegation
workers = [
self.spawn_agent("worker", task=t, context=self.get_context(t))
for t in subtasks
]
results = [w.execute() for w in workers]
# Phase 3: Synthesis
return self.merge_results(results)
def spawn_agent(self, agent_type: str, task: str, context: dict):
# Load base prompt + agent-specific addendum
base_prompt = self.load_prompt("03_default_agent_prompt.md")
agent_prompt = self.load_prompt(f"{agent_type}_prompt.md")
return Agent(
system_prompt=f"{base_prompt}\n\n{agent_prompt}",
task=task,
context=context
)undefined3. Security Classification
3. 安全分类
Multi-stage auto-approval ():
12_yolo_auto_mode_classifier.mdpython
class SecurityClassifier:
def classify_tool_call(self, tool: str, args: dict) -> str:
"""Returns: 'safe', 'unsafe', or 'uncertain'"""
# Stage 1: Fast predefined rules
if tool == "bash" and "rm -rf" in args.get("command", ""):
return "unsafe"
if tool == "read_file" and not self.accesses_sensitive_path(args["path"]):
return "safe"
# Stage 2: User-defined overrides
for rule in self.user_classifier_rules:
result = rule.evaluate(tool, args)
if result != "uncertain":
return result
# Stage 3: Extended reasoning (slower)
return self.llm_classify_with_reasoning(tool, args)
def accesses_sensitive_path(self, path: str) -> bool:
sensitive = ["/etc/passwd", "~/.ssh", ".env"]
return any(s in path for s in sensitive)User-configurable rules ():
.claude/auto_mode_rules.mdyaml
rules:
- pattern: "read_file:docs/**"
verdict: safe
reason: "Documentation is always safe to read"
- pattern: "bash:git push *"
verdict: unsafe
reason: "Always confirm before pushing code"
- pattern: "edit_file:**/test_*.py"
verdict: safe
reason: "Test file edits are low-risk"多阶段自动审批 ():
12_yolo_auto_mode_classifier.mdpython
class SecurityClassifier:
def classify_tool_call(self, tool: str, args: dict) -> str:
"""Returns: 'safe', 'unsafe', or 'uncertain'"""
# Stage 1: Fast predefined rules
if tool == "bash" and "rm -rf" in args.get("command", ""):
return "unsafe"
if tool == "read_file" and not self.accesses_sensitive_path(args["path"]):
return "safe"
# Stage 2: User-defined overrides
for rule in self.user_classifier_rules:
result = rule.evaluate(tool, args)
if result != "uncertain":
return result
# Stage 3: Extended reasoning (slower)
return self.llm_classify_with_reasoning(tool, args)
def accesses_sensitive_path(self, path: str) -> bool:
sensitive = ["/etc/passwd", "~/.ssh", ".env"]
return any(s in path for s in sensitive)用户可配置规则 ():
.claude/auto_mode_rules.mdyaml
rules:
- pattern: "read_file:docs/**"
verdict: safe
reason: "Documentation is always safe to read"
- pattern: "bash:git push *"
verdict: unsafe
reason: "Always confirm before pushing code"
- pattern: "edit_file:**/test_*.py"
verdict: safe
reason: "Test file edits are low-risk"4. Memory Hierarchy
4. 记忆层级
Loading order ():
24_memory_instruction.mdpython
class MemoryLoader:
def load_context(self, project_path: str) -> str:
"""Load memory files in priority order (earliest = lowest priority)"""
layers = [
# 1. Enterprise/managed configuration
self.load_if_exists("/etc/claude/enterprise_policy.md"),
# 2. User global preferences
self.load_if_exists("~/.claude/global_preferences.md"),
# 3. Project-level shared instructions
self.load_if_exists(f"{project_path}/.claude/project_rules.md"),
# 4. Project rules directory (supports includes)
*self.load_directory(f"{project_path}/.claude/rules/"),
# 5. Local overrides (private, gitignored)
self.load_if_exists(f"{project_path}/.claude/local_overrides.md"),
]
# Later layers override earlier ones
return self.merge_with_precedence(layers)
def merge_with_precedence(self, layers: list[str]) -> str:
"""Handle conflicting instructions by priority"""
merged = {}
for layer in layers:
directives = self.parse_directives(layer)
merged.update(directives) # Later overwrites earlier
return self.serialize(merged)Transitive includes:
markdown
<!-- project_rules.md -->加载顺序 ():
24_memory_instruction.mdpython
class MemoryLoader:
def load_context(self, project_path: str) -> str:
"""Load memory files in priority order (earliest = lowest priority)"""
layers = [
# 1. Enterprise/managed configuration
self.load_if_exists("/etc/claude/enterprise_policy.md"),
# 2. User global preferences
self.load_if_exists("~/.claude/global_preferences.md"),
# 3. Project-level shared instructions
self.load_if_exists(f"{project_path}/.claude/project_rules.md"),
# 4. Project rules directory (supports includes)
*self.load_directory(f"{project_path}/.claude/rules/"),
# 5. Local overrides (private, gitignored)
self.load_if_exists(f"{project_path}/.claude/local_overrides.md"),
]
# Later layers override earlier ones
return self.merge_with_precedence(layers)
def merge_with_precedence(self, layers: list[str]) -> str:
"""Handle conflicting instructions by priority"""
merged = {}
for layer in layers:
directives = self.parse_directives(layer)
merged.update(directives) # Later overwrites earlier
return self.serialize(merged)传递性引用:
markdown
<!-- project_rules.md -->Project Rules
Project Rules
@include ./rules/code_style.md
@include ./rules/testing_requirements.md
<!-- Conditional inclusion -->
@include ./rules/python_specific.md if file_extension == ".py"
undefined@include ./rules/code_style.md
@include ./rules/testing_requirements.md
<!-- Conditional inclusion -->
@include ./rules/python_specific.md if file_extension == ".py"
undefined5. Context Window Management
5. 上下文窗口管理
Compaction strategy ():
21_compact_service.mdpython
class ContextCompactor:
def compact_conversation(self, messages: list[dict]) -> list[dict]:
"""Summarize old messages to fit within context window"""
# Keep recent messages verbatim
recent_cutoff = len(messages) - 10
recent = messages[recent_cutoff:]
old = messages[:recent_cutoff]
# Identify which old messages to keep fully
important = self.filter_important(old) # Tool uses, errors, decisions
# Summarize the rest
summaries = self.batch_summarize(
[m for m in old if m not in important],
max_tokens_per_summary=150
)
return summaries + important + recent
def filter_important(self, messages: list[dict]) -> list[dict]:
"""Keep tool uses, errors, and key decisions"""
important = []
for msg in messages:
if msg.get("tool_use"):
important.append(msg)
elif "error" in msg.get("content", "").lower():
important.append(msg)
elif msg.get("flagged_as_important"):
important.append(msg)
return important压缩策略 ():
21_compact_service.mdpython
class ContextCompactor:
def compact_conversation(self, messages: list[dict]) -> list[dict]:
"""Summarize old messages to fit within context window"""
# Keep recent messages verbatim
recent_cutoff = len(messages) - 10
recent = messages[recent_cutoff:]
old = messages[:recent_cutoff]
# Identify which old messages to keep fully
important = self.filter_important(old) # Tool uses, errors, decisions
# Summarize the rest
summaries = self.batch_summarize(
[m for m in old if m not in important],
max_tokens_per_summary=150
)
return summaries + important + recent
def filter_important(self, messages: list[dict]) -> list[dict]:
"""Keep tool uses, errors, and key decisions"""
important = []
for msg in messages:
if msg.get("tool_use"):
important.append(msg)
elif "error" in msg.get("content", "").lower():
important.append(msg)
elif msg.get("flagged_as_important"):
important.append(msg)
return important6. Specialized Agent Patterns
6. 专用Agent模式
Verification Agent ():
07_verification_agent.mdmarkdown
undefined验证Agent ():
07_verification_agent.mdmarkdown
undefinedYour Role
Your Role
You are an adversarial testing agent. After another agent implements a feature,
your job is to break it.
You are an adversarial testing agent. After another agent implements a feature,
your job is to break it.
Testing Strategy
Testing Strategy
- Read the implementation - Understand what was built
- Generate test cases - Focus on edge cases and error conditions
- Execute tests - Run them and document failures
- Report findings - Clear reproduction steps
- Read the implementation - Understand what was built
- Generate test cases - Focus on edge cases and error conditions
- Execute tests - Run them and document failures
- Report findings - Clear reproduction steps
Test Categories
Test Categories
- Boundary conditions (empty input, max values)
- Error handling (invalid input, network failures)
- Race conditions (concurrent access)
- Security (injection, unauthorized access)
- Boundary conditions (empty input, max values)
- Error handling (invalid input, network failures)
- Race conditions (concurrent access)
- Security (injection, unauthorized access)
Constraints
Constraints
- Read-only access to implementation
- Create test files in directory
tests/ - Use project's testing framework
- No modifications to implementation code
**Explore Agent** (`08_explore_agent.md`):
```markdown- Read-only access to implementation
- Create test files in directory
tests/ - Use project's testing framework
- No modifications to implementation code
**探索Agent** (`08_explore_agent.md`):
```markdownYour Role
Your Role
You explore codebases to answer questions. You have read-only access.
You explore codebases to answer questions. You have read-only access.
Available Tools
Available Tools
- : Read any file
read_file - : Browse directory structure
list_directory - : Semantic code search
search_code - : Pattern matching across files
grep
- : Read any file
read_file - : Browse directory structure
list_directory - : Semantic code search
search_code - : Pattern matching across files
grep
Constraints
Constraints
- NEVER use edit_file or write_file
- NEVER use bash to modify files
- Focus on understanding, not changing
- NEVER use edit_file or write_file
- NEVER use bash to modify files
- Focus on understanding, not changing
Exploration Strategy
Exploration Strategy
- Start broad (directory structure, README)
- Identify entry points (main files, key modules)
- Follow dependencies
- Document findings concisely
undefined- Start broad (directory structure, README)
- Identify entry points (main files, key modules)
- Follow dependencies
- Document findings concisely
undefined7. Skill Patterns
7. 技能模式
Simplify Skill () - Multi-agent parallel review:
19_simplify_skill.mdpython
class SimplifySkill:
"""Spawn multiple agents to review code in parallel"""
def execute(self, target_files: list[str]):
# Spawn review agents in parallel
agents = [
self.spawn_agent("reviewer", {
"file": f,
"focus": "complexity",
"constraints": "suggest simplifications, not rewrites"
})
for f in target_files
]
# Collect suggestions
suggestions = [a.execute() for a in agents]
# Coordinator merges and deduplicates
return self.merge_suggestions(suggestions)Skillify Skill () - Interview-based skill creation:
25_skillify.mdmarkdown
undefined简化技能 () - 多Agent并行评审:
19_simplify_skill.mdpython
class SimplifySkill:
"""Spawn multiple agents to review code in parallel"""
def execute(self, target_files: list[str]):
# Spawn review agents in parallel
agents = [
self.spawn_agent("reviewer", {
"file": f,
"focus": "complexity",
"constraints": "suggest simplifications, not rewrites"
})
for f in target_files
]
# Collect suggestions
suggestions = [a.execute() for a in agents]
# Coordinator merges and deduplicates
return self.merge_suggestions(suggestions)技能化技能 () - 基于访谈的技能创建:
25_skillify.mdmarkdown
undefinedProcess
Process
-
Interview user about the skill they want to create
- What problem does it solve?
- What tools/agents are needed?
- What are success criteria?
-
Generate skill specificationyaml
name: custom-skill-name description: One-line description triggers: [list of natural language triggers] agents: [required agent types] tools: [required tool access] workflow: [step-by-step process] -
Write skill implementation as markdown file
-
Test skill with sample scenarios
-
Save to
.claude/skills/custom-skill-name.md
undefined-
Interview user about the skill they want to create
- What problem does it solve?
- What tools/agents are needed?
- What are success criteria?
-
Generate skill specificationyaml
name: custom-skill-name description: One-line description triggers: [list of natural language triggers] agents: [required agent types] tools: [required tool access] workflow: [step-by-step process] -
Write skill implementation as markdown file
-
Test skill with sample scenarios
-
Save to
.claude/skills/custom-skill-name.md
undefinedUsage Examples
使用示例
Building a Custom Agent System
构建自定义Agent系统
python
undefinedpython
undefinedUsing patterns from this research to build your own agent
Using patterns from this research to build your own agent
import anthropic
class CustomAgentSystem:
def init(self, api_key: str):
self.client = anthropic.Anthropic(api_key=api_key)
self.prompts = self.load_prompt_library()
def load_prompt_library(self) -> dict:
"""Load reconstructed prompts from this repository"""
return {
"coordinator": open("prompts/05_coordinator_system_prompt.md").read(),
"default_agent": open("prompts/03_default_agent_prompt.md").read(),
"security": open("prompts/04_cyber_risk_instruction.md").read(),
}
def create_coordinator(self, task: str) -> str:
"""Create a coordinator agent for a complex task"""
system_prompt = f"""{self.prompts['default_agent']}
{self.prompts['coordinator']}
{self.prompts['security']}
Available sub-agents: explore, verification, implementation
Current task: {task}
"""
response = self.client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=4000,
system=system_prompt,
messages=[{"role": "user", "content": task}]
)
return response.content[0].textundefinedimport anthropic
class CustomAgentSystem:
def init(self, api_key: str):
self.client = anthropic.Anthropic(api_key=api_key)
self.prompts = self.load_prompt_library()
def load_prompt_library(self) -> dict:
"""Load reconstructed prompts from this repository"""
return {
"coordinator": open("prompts/05_coordinator_system_prompt.md").read(),
"default_agent": open("prompts/03_default_agent_prompt.md").read(),
"security": open("prompts/04_cyber_risk_instruction.md").read(),
}
def create_coordinator(self, task: str) -> str:
"""Create a coordinator agent for a complex task"""
system_prompt = f"""{self.prompts['default_agent']}
{self.prompts['coordinator']}
{self.prompts['security']}
Available sub-agents: explore, verification, implementation
Current task: {task}
"""
response = self.client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=4000,
system=system_prompt,
messages=[{"role": "user", "content": task}]
)
return response.content[0].textundefinedImplementing Auto-Approval Logic
实现自动审批逻辑
python
import re
class ToolApprovalSystem:
def __init__(self):
# Based on 12_yolo_auto_mode_classifier.md
self.safe_patterns = [
(r"read_file", lambda args: not self._is_sensitive(args["path"])),
(r"list_directory", lambda args: True),
(r"search_code", lambda args: True),
]
self.unsafe_patterns = [
(r"bash:rm -rf", lambda args: True),
(r"bash:sudo", lambda args: True),
(r"edit_file:.env", lambda args: True),
(r"bash:git push", lambda args: True),
]
def classify(self, tool: str, args: dict) -> str:
"""Returns: 'approve', 'reject', or 'ask_user'"""
tool_str = f"{tool}:{args.get('command', args.get('path', ''))}"
# Check unsafe patterns first
for pattern, condition in self.unsafe_patterns:
if re.search(pattern, tool_str) and condition(args):
return "reject"
# Check safe patterns
for pattern, condition in self.safe_patterns:
if re.search(pattern, tool_str) and condition(args):
return "approve"
# Uncertain - ask user
return "ask_user"
def _is_sensitive(self, path: str) -> bool:
sensitive = [".env", ".ssh", "password", "secret", "/etc/"]
return any(s in path.lower() for s in sensitive)python
import re
class ToolApprovalSystem:
def __init__(self):
# Based on 12_yolo_auto_mode_classifier.md
self.safe_patterns = [
(r"read_file", lambda args: not self._is_sensitive(args["path"])),
(r"list_directory", lambda args: True),
(r"search_code", lambda args: True),
]
self.unsafe_patterns = [
(r"bash:rm -rf", lambda args: True),
(r"bash:sudo", lambda args: True),
(r"edit_file:.env", lambda args: True),
(r"bash:git push", lambda args: True),
]
def classify(self, tool: str, args: dict) -> str:
"""Returns: 'approve', 'reject', or 'ask_user'"""
tool_str = f"{tool}:{args.get('command', args.get('path', ''))}"
# Check unsafe patterns first
for pattern, condition in self.unsafe_patterns:
if re.search(pattern, tool_str) and condition(args):
return "reject"
# Check safe patterns
for pattern, condition in self.safe_patterns:
if re.search(pattern, tool_str) and condition(args):
return "approve"
# Uncertain - ask user
return "ask_user"
def _is_sensitive(self, path: str) -> bool:
sensitive = [".env", ".ssh", "password", "secret", "/etc/"]
return any(s in path.lower() for s in sensitive)Memory System Implementation
记忆系统实现
python
import os
from pathlib import Path
class MemorySystem:
def __init__(self, project_root: str):
self.project_root = Path(project_root)
self.memory_dir = self.project_root / ".claude"
def load_all_context(self) -> str:
"""Load memory files in precedence order"""
memory_files = [
Path.home() / ".claude" / "global_preferences.md",
self.memory_dir / "project_rules.md",
*self.memory_dir.glob("rules/*.md"),
self.memory_dir / "local_overrides.md",
]
context_parts = []
for file_path in memory_files:
if file_path.exists():
content = file_path.read_text()
# Process includes
content = self._process_includes(content, file_path.parent)
context_parts.append(f"## From {file_path.name}\n\n{content}")
return "\n\n".join(context_parts)
def _process_includes(self, content: str, base_dir: Path) -> str:
"""Handle @include directives"""
import re
def replace_include(match):
include_path = match.group(1)
full_path = base_dir / include_path
if full_path.exists():
return full_path.read_text()
return f"<!-- Include not found: {include_path} -->"
return re.sub(r'@include\s+(.+)', replace_include, content)
def save_memory(self, name: str, content: str):
"""Save a new memory file"""
self.memory_dir.mkdir(exist_ok=True)
(self.memory_dir / f"{name}.md").write_text(content)python
import os
from pathlib import Path
class MemorySystem:
def __init__(self, project_root: str):
self.project_root = Path(project_root)
self.memory_dir = self.project_root / ".claude"
def load_all_context(self) -> str:
"""Load memory files in precedence order"""
memory_files = [
Path.home() / ".claude" / "global_preferences.md",
self.memory_dir / "project_rules.md",
*self.memory_dir.glob("rules/*.md"),
self.memory_dir / "local_overrides.md",
]
context_parts = []
for file_path in memory_files:
if file_path.exists():
content = file_path.read_text()
# Process includes
content = self._process_includes(content, file_path.parent)
context_parts.append(f"## From {file_path.name}\n\n{content}")
return "\n\n".join(context_parts)
def _process_includes(self, content: str, base_dir: Path) -> str:
"""Handle @include directives"""
import re
def replace_include(match):
include_path = match.group(1)
full_path = base_dir / include_path
if full_path.exists():
return full_path.read_text()
return f"<!-- Include not found: {include_path} -->"
return re.sub(r'@include\s+(.+)', replace_include, content)
def save_memory(self, name: str, content: str):
"""Save a new memory file"""
self.memory_dir.mkdir(exist_ok=True)
(self.memory_dir / f"{name}.md").write_text(content)Common Patterns for AI Agent Builders
AI Agent构建者通用模式
1. Modular Prompt Assembly
1. 模块化提示词组装
Don't hardcode monolithic prompts. Use composition:
python
def build_agent_prompt(role: str, context: dict) -> str:
return "\n\n".join([
load_prompt("base_identity"),
load_prompt(f"role_{role}"),
load_prompt("security_boundaries"),
format_dynamic_context(context),
])不要硬编码庞大的提示词,采用组合方式:
python
def build_agent_prompt(role: str, context: dict) -> str:
return "\n\n".join([
load_prompt("base_identity"),
load_prompt(f"role_{role}"),
load_prompt("security_boundaries"),
format_dynamic_context(context),
])2. Tool Call Batching
2. 工具调用批处理
Reduce round-trips by batching related operations:
python
undefined通过批量处理相关操作减少往返次数:
python
undefinedInstead of: read file1, read file2, read file3
Instead of: read file1, read file2, read file3
Prefer: read multiple files in one call
Prefer: read multiple files in one call
{
"tool": "multi_file_read",
"files": ["file1.py", "file2.py", "file3.py"]
}
undefined{
"tool": "multi_file_read",
"files": ["file1.py", "file2.py", "file3.py"]
}
undefined3. Progressive Disclosure
3. 渐进式披露
Start simple, add complexity as needed:
python
if context_window_usage < 0.5:
# Full verbose mode
system_prompt = build_full_prompt()
else:
# Compact mode with summarized history
system_prompt = build_simple_prompt()从简单模式开始,根据需要逐步增加复杂度:
python
if context_window_usage < 0.5:
# Full verbose mode
system_prompt = build_full_prompt()
else:
# Compact mode with summarized history
system_prompt = build_simple_prompt()4. Adversarial Validation
4. 对抗性验证
Always use a separate agent to verify work:
python
def implement_and_verify(task: str):
# Agent 1: Implementation
implementation = implementation_agent.execute(task)
# Agent 2: Verification (adversarial)
verification = verification_agent.test(implementation)
if verification.passed:
return implementation
else:
return implementation_agent.fix(verification.issues)始终使用独立Agent验证工作成果:
python
def implement_and_verify(task: str):
# Agent 1: Implementation
implementation = implementation_agent.execute(task)
# Agent 2: Verification (adversarial)
verification = verification_agent.test(implementation)
if verification.passed:
return implementation
else:
return implementation_agent.fix(verification.issues)Configuration Patterns
配置模式
Project-Level Configuration
项目级配置
markdown
<!-- .claude/project_rules.md -->markdown
<!-- .claude/project_rules.md -->Code Style
Code Style
- Use TypeScript strict mode
- Prefer functional components
- Maximum line length: 100 characters
- Use TypeScript strict mode
- Prefer functional components
- Maximum line length: 100 characters
Testing Requirements
Testing Requirements
- All public functions must have unit tests
- Minimum coverage: 80%
- Use Jest for testing
- All public functions must have unit tests
- Minimum coverage: 80%
- Use Jest for testing
Auto-Approval Rules
Auto-Approval Rules
@include ./rules/auto_approve.yaml
@include ./rules/auto_approve.yaml
Memory Organization
Memory Organization
@include ./rules/memory_structure.md
undefined@include ./rules/memory_structure.md
undefinedUser-Level Preferences
用户级偏好
markdown
<!-- ~/.claude/global_preferences.md -->markdown
<!-- ~/.claude/global_preferences.md -->Output Style
Output Style
- Be concise
- Use emojis for status indicators
- Prefer markdown tables for structured data
- Be concise
- Use emojis for status indicators
- Prefer markdown tables for structured data
Tool Preferences
Tool Preferences
- Use multi_file_edit over single edit_file
- Prefer ripgrep over grep when available
- Always confirm before git push
undefined- Use multi_file_edit over single edit_file
- Prefer ripgrep over grep when available
- Always confirm before git push
undefinedTroubleshooting
故障排查
Issue: Prompt Assembly Not Working
问题:提示词组装失效
Symptom: Dynamic context not appearing in agent responses
Solution: Check cache boundaries and invalidation:
python
undefined症状: 动态上下文未出现在Agent响应中
解决方案: 检查缓存边界与失效机制:
python
undefinedEnsure dynamic content comes AFTER cache boundary
Ensure dynamic content comes AFTER cache boundary
prompt = f"""
{CACHEABLE_PREFIX}
--- CACHE BOUNDARY ---
{dynamic_context} # This must change per session
"""
undefinedprompt = f"""
{CACHEABLE_PREFIX}
--- CACHE BOUNDARY ---
{dynamic_context} # This must change per session
"""
undefinedIssue: Security Classifier Too Restrictive
问题:安全分类器过于严格
Symptom: Safe operations being blocked
Solution: Add project-specific overrides:
yaml
undefined症状: 安全操作被拦截
解决方案: 添加项目级覆盖规则:
yaml
undefined.claude/auto_mode_rules.yaml
.claude/auto_mode_rules.yaml
rules:
- pattern: "bash:npm install" verdict: safe reason: "Package installation is safe in this project"
undefinedrules:
- pattern: "bash:npm install" verdict: safe reason: "Package installation is safe in this project"
undefinedIssue: Context Window Overflow
问题:上下文窗口溢出
Symptom: Errors about exceeding token limits
Solution: Implement compaction earlier:
python
if total_tokens > MAX_TOKENS * 0.7:
messages = compact_old_messages(messages)症状: 出现超出令牌限制的错误
解决方案: 提前实现压缩机制:
python
if total_tokens > MAX_TOKENS * 0.7:
messages = compact_old_messages(messages)Issue: Agent Coordination Failures
问题:Agent协调失败
Symptom: Sub-agents producing conflicting results
Solution: Use explicit coordination protocol:
markdown
undefined症状: 子Agent产生冲突结果
解决方案: 使用明确的协调协议:
markdown
undefinedCoordinator Instructions
Coordinator Instructions
When spawning sub-agents:
- Assign non-overlapping file scopes
- Provide explicit merge strategy
- Define conflict resolution rules
undefinedWhen spawning sub-agents:
- Assign non-overlapping file scopes
- Provide explicit merge strategy
- Define conflict resolution rules
undefinedResources
参考资源
- Full pattern documentation: Browse directory
prompts/ - Research discussions: Check project issues and PRs
- Related projects:
- MCP (Model Context Protocol) for tool integration
- LangChain for agent frameworks
- Autogen for multi-agent systems
- 完整模式文档:浏览 目录
prompts/ - 研究讨论:查看项目Issue与PR
- 相关项目:
- MCP (Model Context Protocol) 用于工具集成
- LangChain 用于Agent框架
- Autogen 用于多Agent系统
Best Practices
最佳实践
- Start with simple mode - Use minimal prompts for straightforward tasks
- Layer complexity gradually - Add specialized agents only when needed
- Test security boundaries - Always validate auto-approval rules
- Monitor context usage - Implement compaction before hitting limits
- Version your prompts - Track changes to system prompts over time
- Validate with adversarial testing - Use verification agents liberally
- Document agent behaviors - Keep notes on what works and what doesn't
This research provides architectural patterns, not prescriptive solutions. Adapt these patterns to your specific use case and constraints.
- 从简单模式开始:针对简单任务使用最小化提示词
- 逐步增加复杂度:仅在需要时添加专用Agent
- 测试安全边界:始终验证自动审批规则
- 监控上下文使用:在达到限制前实现压缩机制
- 版本化提示词:跟踪系统提示词的变更历史
- 通过对抗性测试验证:大量使用验证Agent
- 记录Agent行为:记录有效与无效的实现方案
本研究提供架构模式,而非规定性解决方案。请根据具体用例与约束调整这些模式。