prompt-architecture
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePrompt Architecture
Prompt Architecture
Part of Agent Skills™ by googleadsagent.ai™
属于 Agent Skills™ 的一部分,由 googleadsagent.ai™ 提供
Description
描述
Prompt Architecture is the structural engineering of agent instructions. Where casual prompt writing produces fragile, inconsistent results, architectural prompt design creates deterministic, high-performance agent behaviors that hold up under adversarial conditions and scale across thousands of invocations. This skill distills the prompt engineering methodology developed within the googleadsagent.ai™ platform, where Buddy™ handles complex Google Ads analysis through meticulously layered prompt structures.
The fundamental principle is that prompts are not strings — they are programs. A well-architected prompt has a clear execution model: system-level invariants establish the agent's identity and constraints, user-level instructions define the current task, and assistant-level priming shapes the output format and reasoning trajectory. Each layer serves a distinct purpose and must be engineered independently before composition.
Advanced prompt architecture incorporates constraint propagation, output schema enforcement, chain-of-thought scaffolding, and dynamic few-shot example selection. These techniques eliminate the "prompt lottery" problem where identical inputs produce wildly varying output quality across runs.
Prompt Architecture 是 Agent 指令的结构工程。随意的 Prompt 编写会产生脆弱且不一致的结果,而架构化的 Prompt 设计则可构建确定性、高性能的 Agent 行为,使其在对抗性条件下依然稳定,并可扩展至数千次调用。本 Skill 提炼了 googleadsagent.ai™ 平台内部开发的 Prompt Engineering 方法论;在该平台中,Buddy™ 通过精心分层构建的 Prompt 结构处理复杂的 Google Ads 分析。
其基本原则是:Prompt 不是字符串,而是程序。架构良好的 Prompt 拥有清晰的执行模型:系统级不变量确立 Agent 的身份和约束,用户级指令定义当前任务,Assistant 级预置则塑造输出格式和推理轨迹。每个层级都承担不同职责,必须先独立设计,再组合起来。
高级 Prompt 架构包含约束传播、输出 Schema 强制执行、Chain-of-Thought 脚手架和动态 Few-Shot 示例选择等技术。这些技术消除了“Prompt Lottery”问题,即相同输入在不同运行中会产出质量悬殊的结果。
Use When
适用场景
- Agent outputs are inconsistent across invocations with the same input
- You need deterministic formatting (JSON, structured reports, specific schemas)
- Complex multi-step reasoning requires explicit chain-of-thought scaffolding
- The agent must adhere to strict behavioral constraints (safety, tone, scope)
- Few-shot examples are needed to establish domain-specific patterns
- You are designing system prompts for production deployment at scale
- Agent 在相同输入的不同调用中输出不一致
- 需要确定性格式(JSON、结构化报告、特定 Schema)
- 复杂的多步推理需要显式的 Chain-of-Thought 脚手架
- Agent 必须遵循严格的行为约束(安全性、语气、范围)
- 需要 Few-Shot 示例来建立特定领域的模式
- 正在为大规模生产部署设计 System Prompt
How It Works
工作原理
mermaid
graph TD
A[System Layer] --> B[Identity & Constraints]
A --> C[Output Schema Definition]
A --> D[Tool Definitions]
B --> E[Prompt Assembly]
C --> E
D --> E
F[User Layer] --> G[Task Specification]
F --> H[Dynamic Few-Shot Examples]
G --> E
H --> E
I[Assistant Layer] --> J[Reasoning Primer]
I --> K[Format Enforcement]
J --> E
K --> E
E --> L[Validation Gate]
L -->|Pass| M[Agent Execution]
L -->|Fail| N[Prompt Revision]
N --> EThe three-layer architecture ensures separation of concerns. The system layer defines who the agent is and what it can do — this layer rarely changes across invocations. The user layer carries the task-specific payload and any dynamically selected examples. The assistant layer provides a "running start" that primes the model's generation trajectory. The validation gate checks assembled prompts against structural rules before execution, catching malformed or conflicting instructions.
mermaid
graph TD
A[System Layer] --> B[Identity & Constraints]
A --> C[Output Schema Definition]
A --> D[Tool Definitions]
B --> E[Prompt Assembly]
C --> E
D --> E
F[User Layer] --> G[Task Specification]
F --> H[Dynamic Few-Shot Examples]
G --> E
H --> E
I[Assistant Layer] --> J[Reasoning Primer]
I --> K[Format Enforcement]
J --> E
K --> E
E --> L[Validation Gate]
L -->|Pass| M[Agent Execution]
L -->|Fail| N[Prompt Revision]
N --> E三层架构确保关注点分离。系统层定义 Agent 是谁以及它能做什么——该层在不同调用之间很少变化。用户层承载特定于当前任务的载荷,以及动态选择的示例。Assistant 层提供一个“起步引导”,用于预置模型的生成轨迹。验证关卡会在执行前依据结构规则检查组装后的 Prompt,从而发现格式错误或相互冲突的指令。
Implementation
实现
Three-Layer Prompt Builder:
typescript
interface PromptLayer {
role: "system" | "user" | "assistant";
sections: PromptSection[];
}
interface PromptSection {
name: string;
content: string;
priority: number;
tokenBudget: number;
}
function assemblePrompt(layers: PromptLayer[], maxTokens: number): Message[] {
const messages: Message[] = [];
for (const layer of layers) {
const sections = layer.sections
.sort((a, b) => b.priority - a.priority)
.reduce((acc, section) => {
const currentTokens = countTokens(acc.map(s => s.content).join("\n"));
if (currentTokens + section.tokenBudget <= maxTokens * 0.4) {
acc.push(section);
}
return acc;
}, [] as PromptSection[]);
messages.push({
role: layer.role,
content: sections.map(s => s.content).join("\n\n"),
});
}
return messages;
}Constrained Output Enforcement:
python
SCHEMA_ENFORCEMENT_PROMPT = """
You MUST respond with valid JSON matching this exact schema:
{schema}
Rules:
- Every field is required unless marked optional
- String fields must not exceed {max_length} characters
- Numeric fields must be within specified ranges
- Do not include fields not in the schema
- Do not wrap the JSON in markdown code blocks
Begin your response with the opening brace {{.
"""
def build_constrained_prompt(schema: dict, task: str) -> list[dict]:
return [
{"role": "system", "content": SCHEMA_ENFORCEMENT_PROMPT.format(
schema=json.dumps(schema, indent=2),
max_length=500
)},
{"role": "user", "content": task},
{"role": "assistant", "content": "{"} # Prime the generation
]Dynamic Few-Shot Selection:
python
class FewShotSelector:
def __init__(self, examples: list[dict], embedder):
self.examples = examples
self.embedder = embedder
self.embeddings = [embedder.encode(ex["input"]) for ex in examples]
def select(self, query: str, k: int = 3) -> list[dict]:
query_emb = self.embedder.encode(query)
similarities = [
cosine_similarity(query_emb, emb) for emb in self.embeddings
]
top_indices = sorted(
range(len(similarities)),
key=lambda i: similarities[i],
reverse=True
)[:k]
return [self.examples[i] for i in top_indices]
def format_examples(self, examples: list[dict]) -> str:
parts = []
for ex in examples:
parts.append(f"Input: {ex['input']}\nOutput: {ex['output']}")
return "\n\n---\n\n".join(parts)三层 Prompt 构建器:
typescript
interface PromptLayer {
role: "system" | "user" | "assistant";
sections: PromptSection[];
}
interface PromptSection {
name: string;
content: string;
priority: number;
tokenBudget: number;
}
function assemblePrompt(layers: PromptLayer[], maxTokens: number): Message[] {
const messages: Message[] = [];
for (const layer of layers) {
const sections = layer.sections
.sort((a, b) => b.priority - a.priority)
.reduce((acc, section) => {
const currentTokens = countTokens(acc.map(s => s.content).join("\n"));
if (currentTokens + section.tokenBudget <= maxTokens * 0.4) {
acc.push(section);
}
return acc;
}, [] as PromptSection[]);
messages.push({
role: layer.role,
content: sections.map(s => s.content).join("\n\n"),
});
}
return messages;
}受约束输出强制执行:
python
SCHEMA_ENFORCEMENT_PROMPT = """
You MUST respond with valid JSON matching this exact schema:
{schema}
Rules:
- Every field is required unless marked optional
- String fields must not exceed {max_length} characters
- Numeric fields must be within specified ranges
- Do not include fields not in the schema
- Do not wrap the JSON in markdown code blocks
Begin your response with the opening brace {{.
"""
def build_constrained_prompt(schema: dict, task: str) -> list[dict]:
return [
{"role": "system", "content": SCHEMA_ENFORCEMENT_PROMPT.format(
schema=json.dumps(schema, indent=2),
max_length=500
)},
{"role": "user", "content": task},
{"role": "assistant", "content": "{"} # Prime the generation
]动态 Few-Shot 选择:
python
class FewShotSelector:
def __init__(self, examples: list[dict], embedder):
self.examples = examples
self.embedder = embedder
self.embeddings = [embedder.encode(ex["input"]) for ex in examples]
def select(self, query: str, k: int = 3) -> list[dict]:
query_emb = self.embedder.encode(query)
similarities = [
cosine_similarity(query_emb, emb) for emb in self.embeddings
]
top_indices = sorted(
range(len(similarities)),
key=lambda i: similarities[i],
reverse=True
)[:k]
return [self.examples[i] for i in top_indices]
def format_examples(self, examples: list[dict]) -> str:
parts = []
for ex in examples:
parts.append(f"Input: {ex['input']}\nOutput: {ex['output']}")
return "\n\n---\n\n".join(parts)Best Practices
最佳实践
- Separate identity from instructions — the system prompt's first paragraph should define who the agent is; subsequent sections define what it does. Identity persists; instructions vary.
- Use XML tags for section boundaries — ,
<task>,<constraints>tags create unambiguous section delimiters that models parse reliably.<examples> - Place constraints before instructions — models attend more strongly to information appearing earlier in the system prompt; put non-negotiable rules first.
- Prime the assistant turn — prefilling the assistant message with the opening tokens of the desired format (e.g., for JSON,
{for markdown) dramatically improves format compliance.## Analysis - Version and A/B test prompts — treat prompts as code artifacts with version control, automated evaluation, and regression testing across model versions.
- Minimize redundancy across layers — if the system prompt defines output format, the user prompt should not restate it; redundancy wastes tokens and can introduce contradictions.
- Calibrate temperature to task type — use 0.0-0.3 for deterministic extraction, 0.5-0.7 for analytical reasoning, 0.8-1.0 for creative generation.
- Test with adversarial inputs — verify that the prompt architecture holds when users provide malformed, contradictory, or injection-laden inputs.
- 将身份与指令分离 — System Prompt 的第一段应定义 Agent 是谁;后续章节定义它做什么。身份定义保持稳定,指令则随任务变化。
- 使用 XML 标签标记章节边界 — 、
<task>、<constraints>标签可创建清晰无歧义的章节分隔符,模型能够可靠地解析。<examples> - 将约束置于指令之前 — 模型对 System Prompt 中较早出现的信息关注度更高;因此应把不可协商的规则放在最前面。
- 预置 Assistant 轮次 — 使用所需格式的开头 Token 预填 Assistant 消息(例如 JSON 使用 ,Markdown 使用
{),可显著提升格式遵循率。## Analysis - 对 Prompt 进行版本控制和 A/B 测试 — 将 Prompt 视为代码制品,配合版本控制、自动评估和跨模型版本的回归测试。
- 尽量减少各层之间的冗余 — 如果 System Prompt 已定义输出格式,User Prompt 就不应重复说明;冗余会浪费 Token,还可能引入矛盾。
- 根据任务类型校准 temperature — 确定性提取使用 0.0-0.3,分析型推理使用 0.5-0.7,创意生成使用 0.8-1.0。
- 使用对抗性输入进行测试 — 当用户提供格式错误、互相矛盾或包含注入攻击的输入时,验证 Prompt 架构是否仍能保持稳固。
Platform Compatibility
平台兼容性
| Feature | Claude Code | Cursor | Codex | Gemini CLI |
|---|---|---|---|---|
| System prompt layering | ✅ Full | ✅ Rules + Skills | ✅ Instructions | ✅ System prompts |
| Assistant prefill | ✅ Native | ⚠️ Limited | ❌ Not supported | ⚠️ Limited |
| Few-shot injection | ✅ Full | ✅ Full | ✅ Full | ✅ Full |
| XML section tags | ✅ Preferred | ✅ Supported | ✅ Supported | ✅ Supported |
| Temperature control | ✅ API param | ⚠️ Model default | ✅ API param | ✅ API param |
| 特性 | Claude Code | Cursor | Codex | Gemini CLI |
|---|---|---|---|---|
| System Prompt 分层 | ✅ 完整支持 | ✅ Rules + Skills | ✅ Instructions | ✅ System Prompts |
| Assistant 预填充 | ✅ 原生支持 | ⚠️ 有限 | ❌ 不支持 | ⚠️ 有限 |
| Few-Shot 注入 | ✅ 完整支持 | ✅ 完整支持 | ✅ 完整支持 | ✅ 完整支持 |
| XML 章节标签 | ✅ 首选 | ✅ 支持 | ✅ 支持 | ✅ 支持 |
| temperature 控制 | ✅ API 参数 | ⚠️ 模型默认值 | ✅ API 参数 | ✅ API 参数 |
Mythos Preview Reference
Mythos Preview 参考
Anthropic’s Mythos Preview write-up shows that a short, single-paragraph task prompt can drive long, complex autonomous work when the harness is right: they launch an isolated container with the project, invoke Claude Code with Mythos Preview, give roughly one paragraph (e.g., ask the model to find a security issue), and let the agent run—reading code, experimenting, and iterating without step-by-step human steering.
That pattern is a useful reference when you want high autonomy without over-specifying every tool call in the prompt. Treat the paragraph as the goal and constraints; rely on the runtime (tools, environment, verification) for execution detail. Source: Mythos Preview.
Anthropic 的 Mythos Preview 文章表明,当运行框架(harness)配置得当时,简短的单段任务 Prompt 可以驱动漫长而复杂的自主工作:他们会启动一个装载项目的隔离容器,调用启用了 Mythos Preview 的 Claude Code,仅提供大约一段文字的提示(例如,要求模型查找安全问题),然后让 Agent 自行运行——读取代码、进行实验并不断迭代,无需人类逐步引导。
如果希望在高自主性的同时避免过度指定 Prompt 中的每一次工具调用,这一模式可作为有用参考。将该段落视为目标与约束;具体执行细节则依赖运行时(工具、环境、验证)。来源:Mythos Preview。
Related Skills
相关 Skills
- Cognitive Scaffolding - Attention-zone placement that determines where prompt layers achieve maximum model focus
- Context Engineering - Token budget management that constrains prompt layer sizes and triggers compression
- Anthropic Tool Mastery - Tool definition design that operates within the prompt architecture's system layer
- Verification Loops - Output validation that enforces the schema constraints defined in the prompt architecture
- Cognitive Scaffolding - 确定 Prompt 层级何处可获得模型最高关注度的注意力区域布局
- Context Engineering - 约束 Prompt 层级大小并触发压缩的 Token 预算管理
- Anthropic Tool Mastery - 在 Prompt Architecture 系统层内运行的工具定义设计
- Verification Loops - 强制执行 Prompt Architecture 中所定义 Schema 约束的输出验证
Keywords
关键词
prompt-architecture, system-prompt, few-shot, chain-of-thought, constrained-generation, output-format, prompt-layering, instruction-hierarchy, temperature-tuning, agent-skills
© 2026 googleadsagent.ai™ | Agent Skills™ | MIT License
prompt-architecture, system-prompt, few-shot, chain-of-thought, constrained-generation, output-format, prompt-layering, instruction-hierarchy, temperature-tuning, agent-skills
© 2026 googleadsagent.ai™ | Agent Skills™ | MIT License