一键导入
agent-design-patterns
Authoritative reference for agent architecture selection, multi-agent orchestration, tool design, memory systems, and failure mode prevention
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
Authoritative reference for agent architecture selection, multi-agent orchestration, tool design, memory systems, and failure mode prevention
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
Expert reference for application security — OWASP Top 10 mitigations, auth/authz, secrets management, cryptography, input validation, dependency hygiene, and secure-by-default code patterns
Expert reference for token counting, prompt compression, cost estimation, and quality preservation when optimizing prompts for Claude models
Experimentation design and A/B testing standards for product teams
Expert reference for digital accessibility — WCAG conformance, ARIA, and inclusive design patterns
Expert reference for evaluating LLM systems, RAG pipelines, and AI features in production
Machine learning engineering patterns for model selection, feature engineering, training pipelines, evaluation, and production deployment.
| name | agent-design-patterns |
| description | Authoritative reference for agent architecture selection, multi-agent orchestration, tool design, memory systems, and failure mode prevention |
| version | 1 |
max_iterations=20 for research agents, max_iterations=10 for task agents. No exception. Uncapped loops will exhaust token budgets and produce runaway costs.description field, enum constraints where applicable, and explicit required arrays. The LLM cannot reliably guess intent from parameter names alone.error_code, message, and retry_hint. Unstructured stack traces cause hallucinated recovery attempts.Send API for fan-out.{"answer": "...", "confidence": 0.65}.Observe (tool call) → Orient (context update) → Decide (reasoning) → Act (next tool call). Every agent loop is an OODA loop. Design for fast, cheap Observe steps and expensive, rare Act steps. Batch observations; minimize irreversible actions.
A tool schema is a contract between the LLM and the runtime. Violations on either side cause failures. The LLM is the caller; the tool is the callee. The schema is the interface definition. Treat tool design with the same rigor as API design — versioning, deprecation, error contracts included.
In-context (fastest, ephemeral) → Episodic/vector (semantic retrieval, persists across sessions) → Semantic/KG (structured relational, best for entity-heavy domains) → Procedural (fine-tuned weights, most durable but most expensive to update). Escalate up the hierarchy only when the lower tier cannot serve the use case.
Three root causes cover >90% of agent failures: (1) Context poisoning — bad data enters the reasoning trace and cascades. (2) Action amplification — a small misunderstanding triggers a large irreversible action. (3) Loop entrenchment — the agent repeats the same failing strategy because it cannot detect its own stuckness. Design explicit detection for each: input validation for (1), approval gates for (2), duplicate-action detectors for (3).
| Term | Definition |
|---|---|
| ReAct | Reasoning + Acting pattern; agent alternates Thought/Action/Observation steps in a single loop |
| Plan-and-Execute | Two-phase pattern: planner generates a step list, separate executor runs each step |
| Reflexion | Agent evaluates and critiques its own output, iterates up to N times for quality improvement |
| CAMEL | Communicative Agents for Mind Exploration; role-assigned agents negotiate toward a shared goal |
| Supervisor-Worker | Orchestration topology where a controller agent dispatches tasks to stateless specialist agents |
| Tool Schema | JSON Schema definition attached to a function; governs what parameters the LLM may pass |
| Episodic Memory | Vector store of past interaction summaries, retrieved by semantic similarity at session start |
| Trajectory Eval | Evaluation of the sequence of actions/tool calls taken, not just the final output |
| HITL | Human-in-the-Loop; a mandatory pause for human approval before irreversible tool execution |
| Token Budget | Maximum tokens available across the full agent context window; requires active management |
| Stuck Detection | Logic that identifies repeated identical tool calls or zero-progress iterations and breaks the loop |
| Procedural Memory | Capability encoded in model weights via fine-tuning; durable but costly to update |
Bad:
{
"name": "search",
"description": "Search for things",
"parameters": {
"query": {"type": "string"}
}
}
Fix: Every tool description must state what the tool returns, when to use it, and what it cannot do.
{
"name": "web_search",
"description": "Search the public web for recent information. Returns top 5 results with title, URL, and 200-char snippet. Use for current events, documentation lookup. Do NOT use for internal company data.",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "The search query. Be specific. Max 200 characters."
},
"num_results": {
"type": "integer",
"description": "Number of results to return. Default 5, max 10.",
"default": 5
}
},
"required": ["query"]
}
}
Bad:
while not task_complete:
result = agent.step()
Fix:
MAX_ITERATIONS = 20
for i in range(MAX_ITERATIONS):
result = agent.step()
if result.is_complete:
break
if i > 0 and result.action == prev_action:
raise AgentStuckError(f"Repeated action at iteration {i}")
prev_action = result.action
else:
raise AgentMaxIterationsError("Exceeded 20 iterations without completion")
Bad:
try:
result = call_api(params)
except Exception as e:
return str(e) # "ConnectionRefusedError: [Errno 111] Connection refused"
Fix:
try:
result = call_api(params)
except requests.Timeout:
return {"error_code": "TIMEOUT", "message": "API timed out after 10s", "retry_hint": "Retry once after 5s"}
except requests.HTTPError as e:
return {"error_code": f"HTTP_{e.response.status_code}", "message": "API returned error", "retry_hint": "Check query parameters"}
Bad:
def read_document(path: str) -> str:
return open(path).read() # Returns 50,000 tokens
Fix:
def read_document(path: str, max_tokens: int = 4000) -> dict:
content = open(path).read()
tokens = tokenize(content)
if len(tokens) > max_tokens:
truncated = detokenize(tokens[:max_tokens])
return {"content": truncated, "truncated": True, "total_tokens": len(tokens)}
return {"content": content, "truncated": False, "total_tokens": len(tokens)}
Bad:
def delete_records(ids: list[str]) -> dict:
db.delete_many(ids)
return {"deleted": len(ids)}
Fix:
def delete_records(ids: list[str], confirmed: bool = False) -> dict:
if not confirmed:
return {
"requires_confirmation": True,
"message": f"About to delete {len(ids)} records. Set confirmed=true to proceed.",
"preview": ids[:5]
}
db.delete_many(ids)
audit_log.write(action="delete", ids=ids, actor=current_user())
return {"deleted": len(ids)}
Bad: "Use LangChain agents for your use case."
Good: "The task requires parallel document processing across 6 independent files, each needing retrieval and synthesis. Use LangGraph with Plan-and-Execute: the planner emits 6 Send events to a document_analyst worker node, results fan-in to a synthesis node. Set max_iterations=10 per worker. Use Chroma for episodic memory if sessions persist beyond 1 hour."
Bad schema: {"name": "get_data", "description": "Gets data", "parameters": {"id": {"type": "string"}}}
Good schema: Explicit description of return value format, error conditions, when-not-to-use guidance, all parameters described, required array set, enum constraints on categorical parameters.
Bad: "Store everything in the context window for simplicity."
Good: Conversation history > 20 turns: summarize to episodic vector store (500-token summaries, cosine similarity retrieval at session start). Entity facts: semantic KG (Neo4j or Zep). Learned procedures: fine-tune — not context.
max_iterations set (research: 20, task: 10, debate: 5 rounds)description on every parameter and required array declaredconfirmed=true parameter