☰
OpenProse 设计模式实战:用结构化模式编写健壮、高效、可维护的多智能体程序
2026/10/16 2:40:09 网站建设 项目流程
  • 人工智能
  • 大模型
  • LLM 网关
  • AI Agent
  • 即时通讯

【免费下载链接】openclaw-zero-token

OpenClaw: Use All Major AI Models NO API Token! Claude/ChatGPT/Gemini/DeepSeek/Doubao/Grok/Qwen/Manus/Kimi

项目地址:https://gitcode.com/gh_mirrors/op/openclaw-zero-token
点击查看免费下载

OpenProse 是一门面向 AI 会话的编程语言:每个session语句都会通过 Task 工具真实地派生一个子智能体(subagent),而程序文件本身则描述了如何编排这些智能体。本文基于 OpenProse 官方最佳实践文档 guidance/patterns.md,系统梳理其在健壮性、成本效率、速度、可维护性与自我改进五类诉求上的成熟设计模式,并结合作者仓库内的 prose.md(VM 执行语义)、compiler.md(语法规范)与 examples/ 中 40+ 个示例程序进行源码级印证。读完本文,你将能够按照模式化思维编写、评审和优化.prose多智能体工作流——知道何时并行、何时串行、何时该用哪个模型、如何让程序在失败面前优雅降级。

前置准备:在 OpenClaw 中启用 OpenProse

OpenProse 在仓库中以插件形式提供(extensions/open-prose),其 README.md 说明:捆绑插件默认关闭,需在配置中显式启用并重启 Gateway:

{ "plugins": { "entries": { "open-prose": { "enabled": true } } } }

启用后你将获得/prose斜杠命令、OpenProse VM 语义(.prose程序 + 多智能体编排)以及遥测支持。程序的执行通过prose命令完成:prose run <file.prose>执行本地程序、prose compile <file>校验语法、prose examples列出内置示例。在 OpenClaw 运行时映射中(见 prose.md),上游规范里的 Task 工具对应 OpenClaw 的sessions_spawn,文件 I/O 对应read/write,远程抓取对应web_fetch。

模式总览:五类核心诉求

根据 guidance/patterns.md,每个设计模式都针对具体诉求:健壮性(程序不会失控或静默失败)、成本效率(不浪费 token 与昂贵的模型调用)、速度(缩短墙钟时间)、可维护性(别人能读懂、能修改)、自我改进能力(输出质量可迭代提升)。实践中一个复杂程序通常组合多类模式:结构模式决定骨架,健壮性模式兜底,成本与性能模式优化资源,自我改进与可维护性模式保障质量与长期演进。

一、结构模式(Structural Patterns)

结构模式回答"程序长什么样":如何组织会话、如何复用、如何让数据流转清晰。

parallel-independent-work:无依赖任务并行执行

当任务之间没有数据依赖时,应当并发执行,以最大化吞吐量并最小化墙钟时间:

# Good: Independent research runs in parallel parallel: market = session "Research market trends" tech = session "Research technology landscape" competition = session "Analyze competitor products" session "Synthesize findings" context: { market, tech, competition }

关键收益:合成会话会等待全部分支完成,但总耗时等于最长分支耗时,而非所有分支耗时之和。仓库示例 17-parallel-research.prose 用同一researcher智能体并行研究历史背景、当前状态与未来趋势,再合并为综合研究摘要,是此模式的直接落地。

底层实现上,prose.md 说明:parallel:块通过"在单次响应中发起多个 Task 调用"实现真正的并发,且支持三类 join 策略——"all"(默认,等待所有分支)、"first"(首个完成即返回并取消其余)、"any"(首个成功即返回),以及"any", count: N(等待 N 个成功)。

fan-out-fan-in:集合处理的扇出与汇聚

处理集合时,先用parallel for扇出到并行工作器,再汇聚结果,而不是手工编写多条并行分支:

let topics = ["AI safety", "interpretability", "alignment", "robustness"] parallel for topic in topics: session "Deep dive research on {topic}" session "Create unified report from all research"

该模式随集合规模自然扩展,且保持代码 DRY(不因主题数量增加而重复编写分支)。语法上(prose.md),parallel for item in items:是"扇出"原语:所有迭代并发派生、等待全部完成。它正是 Recursive Language Model(RLM)divide-and-conquer 模式的核心构件——见 examples/README.md 对 41-rlm-divide-conquer 的说明:分块、处理、递归聚合。

pipeline-composition:管道组合

使用管道操作符(|)串联变换,每个阶段只承担单一职责,数据流清晰可读:

let candidates = session "Generate 10 startup ideas" let result = candidates | filter: session "Is this idea technically feasible? yes/no" context: item | map: session "Expand this idea into a one-page pitch" context: item | reduce(best, current): session "Compare these two pitches, return the stronger one" context: [best, current]

管道从左到右执行(prose.md):filter保留会话返回真值的项、map逐项变换、reduce成对累加、pmap并发变换。完整示例见 21-pipeline-operations.prose,它先用filter筛选科技类创业想法、再用map扩展为商业计划书、最后reduce聚合为投资组合摘要,并演示了pmap并发研究多个主题。

agent-specialization:智能体专业化

用agent定义具备聚焦专长的智能体。专业化智能体的输出质量优于通用提示词:

agent security-reviewer: model: sonnet prompt: """ You are a security expert. Focus exclusively on: - Authentication and authorization flaws - Injection vulnerabilities - Data exposure risks Ignore style, performance, and other concerns. """ agent performance-reviewer: model: sonnet prompt: """ You are a performance engineer. Focus exclusively on: - Algorithmic complexity - Memory usage patterns - I/O bottlenecks Ignore security, style, and other concerns. """

这与反面模式文档 antipatterns.md 中的mixed-concerns-agent(一个"全能智能体"提示词涵盖安全、性能、文档、测试等所有职责)形成对照。示例 16-parallel-reviews.prose 让同一reviewer模板以不同提示词并行执行安全、性能、风格三类评审;而 29-captains-chair.prose 则定义了 captain(opus,只协调不写码)、researcher(haiku,快速信息收集)、coder(sonnet,实现)、critic(sonnet,持续评审)、tester(sonnet,测试)五个专职角色。

reusable-blocks:可复用块

把重复工作流抽取为带参数的 block——block 就是 OpenProse 的函数:

block review-and-revise(artifact, criteria): let feedback = session "Review {artifact} against {criteria}" session "Revise {artifact} based on feedback" context: feedback # Reuse the pattern do review-and-revise("the architecture doc", "clarity and completeness") do review-and-revise("the API design", "consistency and usability") do review-and-revise("the test plan", "coverage and edge cases")

仓库 26-parameterized-blocks.prose 展示了 block 的完整能力矩阵:多参数调用、block 内条件分支、并行调用 block、block 内嵌 try/catch 与 retry、嵌套 block 调用、block 内嵌循环。执行层面(prose.md),block 调用会推入调用栈帧(含execution_id、参数、局部绑定、返回位置、深度),支持递归与词法作用域解析,默认最大递归深度 100,可用block name(args) (max_depth: 50)按块配置。

二、健壮性模式(Robustness Patterns)

健壮性模式确保程序在面对外部失败、条件不满足、资源约束时仍能受控地终止或恢复。

bounded-iteration:有界迭代

循环务必用max:约束,防止失控执行。即使精心设计的条件也可能永不满足:

# Good: Explicit upper bound loop until **all tests pass** (max: 20): session "Identify and fix the next failing test" # The program will terminate even if tests never fully pass

antipatterns.md 中的unbounded-loop和infinite-refinement正是此模式的反面:loop until **the code is perfect**:没有逃生舱,"完美"可能永远达不到。执行语义(prose.md)为:每次迭代前检查条件,条件满足或达到max:即退出。

graceful-degradation:优雅降级

当部分结果可接受时,使用on-fail: "continue"——能收集多少就收集多少,而不是整体失败:

parallel (on-fail: "continue"): primary = session "Query primary data source" backup = session "Query backup data source" cache = session "Check local cache" # Continue with whatever succeeded session "Merge available data" context: { primary, backup, cache }

对应失败策略全集(prose.md):"fail-fast"(默认,任一错误立即失败)、"continue"(等待全部完成再报告错误)、"ignore"(把失败当作成功)。注意反面模式ignored-errors警告:对"扣款""发货"这类关键操作使用on-fail: "ignore"会掩盖必须暴露的问题——失败策略要与业务重要性匹配。

retry-with-backoff:指数退避重试

外部服务会瞬时失败。用指数退避重试应对限流和临时宕机:

session "Call external API" retry: 5 backoff: "exponential"

关键路径应把重试与兜底结合:

try: session "Call primary API" retry: 3 backoff: "exponential" catch: session "Use fallback data source"

prose.md 定义重试机制:失败后最多重试 N 次、尝试之间施加退避延迟、全部重试失败则传播错误。backoff取值none、linear、exponential(compiler.md)。23-retry-with-backoff.prose 覆盖了全部组合:简单重试、指数退避、线性退避、带 context 的重试、try/catch 兜底、并行主备数据库重试、循环内分批重试。

error-context-capture:错误上下文捕获

捕获错误上下文以便智能恢复。错误变量为诊断或修复会话提供信息:

try: session "Deploy to production" catch as err: session "Analyze deployment failure and suggest fixes" context: err session "Attempt automatic remediation" context: err

catch as err:将错误对象绑定到变量并作为 context 传递(compiler.md 中"Error variable"特性)。反面模式catch-and-swallow提醒:空 catch 会让错误消失而无恢复、无日志、无可见性——至少应记录错误并执行兜底流程,不可恢复时throw重新抛出。完整语法示例见 22-error-handling.prose:基本 try/catch 恢复、带错误变量、try/catch/finally 资源清理、嵌套错误处理(内层throw重新抛出给外层)、并行块内各自 try/catch。

defensive-context:防御式上下文校验

在昂贵操作之前验证假设。廉价检查可避免浪费大量计算:

let prereqs = session "Check all prerequisites: API keys, permissions, dependencies" if **prerequisites are not met**: session "Report missing prerequisites and exit" context: prereqs throw "Prerequisites not satisfied" # Expensive operations only run if prereqs pass session "Execute main workflow"

这与 12-secure-agent-permissions.prose 体现的安全实践一脉相承:在授权智能体执行敏感操作前先验证输入与权限。**...**是"裁量条件"标记(discretion),由 VM 智能评估而非字面解析(prose.md)。

三、成本效率模式(Cost Efficiency Patterns)

成本效率模式的核心洞察:模型能力应与任务复杂度匹配,上下文应最小化,不必要的迭代应尽早终止。

model-tiering:模型分级

将模型能力与任务复杂度匹配。原文档给出了两张核心对照表,完整继承如下:

ModelBest ForExamples
Sonnet 4.5Orchestration, control flow, coordinationVM execution, captain's chair, workflow routing
Opus 4.5Hard/difficult work requiring deep reasoningComplex analysis, strategic decisions, novel problem-solving
HaikuSimple, self-evident tasks (use sparingly)Classification, summarization, formatting

关键洞察:Sonnet 4.5 擅长_编排_智能体与管理控制流——它是 OpenProse VM 本身以及协调工作的"船长"智能体的理想模型。Opus 4.5 应保留给真正困难的智力工作。Haiku 可处理简单任务,但在质量关键场景应谨慎使用。

任务到模型的详细映射:

Task TypeModelRationale
Orchestration, routing, coordinationSonnetFast, good at following structure
Investigation, debugging, diagnosisSonnetStructured analysis, checklist-style work
Triage, classification, categorizationSonnetClear criteria, deterministic decisions
Code review, verification (checklist)SonnetFollowing defined review criteria
Simple implementation, fixesSonnetApplying known patterns
Complex multi-file synthesisOpusNeeds to hold many things in context
Novel architecture, strategic planningOpusRequires creative problem-solving
Ambiguous problems, unclear requirementsOpusNeeds to reason through uncertainty

经验法则:如果你能为任务写出 checklist,Sonnet 就能完成;如果任务需要真正的创造力或要在模糊性中导航,用 Opus。

完整的分级编排示例(含持久化智能体):

agent captain: model: sonnet # Orchestration and coordination persist: true # Execution-scoped (dies with run) prompt: "You coordinate the team and review work" agent researcher: model: opus # Hard analytical work prompt: "You perform deep research and analysis" agent formatter: model: haiku # Simple transformation (use sparingly) prompt: "You format text into consistent structure" agent preferences: model: sonnet persist: user # User-scoped (survives across projects) prompt: "You remember user preferences and patterns" # Captain orchestrates, specialists do the hard work session: captain prompt: "Plan the research approach" let findings = session: researcher prompt: "Investigate the technical architecture" resume: captain prompt: "Review findings and determine next steps" context: findings

该示例同时展示了persist的两种作用域(prose.md):persist: true是执行级(随运行销毁),persist: user是用户级(跨项目存活),另有persist: project项目级与自定义路径。session:与resume:的关键区别在于:前者忽略已有记忆全新开始,后者加载记忆继续推进。仓库 29-captains-chair.prose 与 34-content-pipeline.prose 是分级落地的教科书:captain/editor 用 opus/sonnet 做编排与评审,researcher 用 opus 做深度研究,social-strategist 用 sonnet 生成社交文案。反面模式opus-for-everything警告:用 Opus 做二分类是显著的成本浪费,简单任务应匹配 Haiku。

context-minimization:上下文最小化

只传递相关上下文。大上下文会拖慢处理并推高成本:

# Bad: Passing everything session "Write executive summary" context: [raw_data, analysis, methodology, appendices, references] # Good: Pass only what's needed let key_findings = session "Extract key findings from analysis" context: analysis session "Write executive summary" context: key_findings

反面模式context-bloat与spaghetti-context均指向同一教训:把整个代码库、全部文档、完整 git 历史塞给一个只改 README 拼写错误的会话,既慢又贵还容易让模型被无关信息干扰。值得强调的是,OpenProse 的 context 传递本身是按引用而非按值的(prose.md):VM 只追踪绑定文件位置,子智能体按需自行读取,这使中间值可以任意大而不撑爆 VM 上下文。

early-termination:提前终止

目标达成即退出循环,不要做无谓迭代:

# The condition is checked each iteration loop until **solution found and verified** (max: 10): session "Generate potential solution" session "Verify solution correctness" # Exits immediately when condition is met, not after max iterations

反面模式fixed-observation-window展示了同主题的变体:固定循环 30 次观察,即使第 2 次迭代就发现了致命错误也继续空耗。

early-signal-exit:信号驱动提前退出

观察或监控场景中,一旦获得确定答案立即退出,不必等待完整观察窗口:

# Good: Exit on signal let observation = session: observer prompt: "Watch the stream. Signal immediately if you detect a blocking error." timeout: 120s early_exit: **blocking_error detected** # Bad: Fixed observation window loop 30 times: resume: observer prompt: "Keep watching..." # Even if error was obvious at iteration 2

这尊重信号到达的时机,而非等待任意超时。反面模式fixed-observation-window的建议同样适用:loop until **blocking error OR completion**或用early_exit。

defaults-over-prompts:默认值优先于提示

标准配置使用常量或环境变量,仅在真正可变时才提示:

# Good: Sensible defaults const API_URL = "https://api.example.com" const TEST_PROGRAM = "# Simple test\nsession 'Hello'" # Slower: Prompting for known values let api_url = input "Enter API URL" # Usually the same value let program = input "Enter test program" # Usually the same value

经验法则:如果 90% 的运行都使用同一个值,就硬编码它,需要时通过 CLI 参数让用户覆盖。反面模式excessive-user-checkpoints也强调:每次input都是一次等待用户往返的延迟,答案可预测 90% 时不应打断流程——仅在真正模糊(低置信度诊断)或不可逆操作(生产部署)时才询问。

race-for-speed:速度竞赛

当任何有效结果都够用时,并行竞赛多种方案,取第一个成功者:

parallel ("first"): session "Try algorithm A" session "Try algorithm B" session "Try algorithm C" # Continues as soon as any approach completes session "Use winning result"

对应 join 策略"first"(首个完成即返回并取消其余)。19-advanced-parallel.prose 用三种检索途径竞赛最快结果,并演示了"any", count: 2(从 4 个 headline 候选里取前两个完成者)等组合。

batch-similar-work:同类工作批量处理

将相似操作分组以摊薄开销。一次带结构化输出的会话胜过多次小会话:

# Inefficient: Many small sessions for file in files: session "Analyze {file}" # Efficient: Batch analysis session "Analyze all files and return structured findings for each" context: files

反面模式unnecessary-iteration与redundant-computation是此模式的两面:能一次完成的事不要循环("描述 apple/banana/cherry"三次会话不如一次),相同研究不要重复三次——先算一次,再让多个评审并行消费同一份研究成果。

四、自我改进模式(Self-Improvement Patterns)

自我改进模式让程序通过反馈回路逐步逼近质量目标。

self-verification-in-prompt:提示词内自验证

对原本需要独立验证器的任务,把验证作为提示词的最后一步,省去一次往返同时保持严谨:

# Good: Combined work + self-verification agent investigator: model: sonnet prompt: """Diagnose the error. 1. Examine code paths 2. Check logs and state 3. Form hypothesis 4. BEFORE OUTPUTTING: Verify your evidence supports your conclusion. Output only if confident. If uncertain, state what's missing.""" # Slower: Separate verifier agent let diagnosis = session: researcher prompt: "Investigate the error" let verification = session: verifier prompt: "Verify this diagnosis" # Extra round-trip context: diagnosis

何时该用独立验证器?需要真正对抗性审查(不同视角)时;而一致性自检,把验证烘进提示词即可。

iterative-refinement:迭代精炼

用反馈回路渐进改进输出,每次迭代建立在前一次之上:

let draft = session "Create initial draft" loop until **draft meets quality bar** (max: 5): let critique = session "Critically evaluate this draft" context: draft draft = session "Improve draft based on critique" context: [draft, critique] session "Finalize and publish" context: draft

仓库中有多处落地:34-content-pipeline.prose 用持久化editor智能体在loop until **the article meets publication standards** (max: 4)内循环"评审→修订";40-rlm-self-refine.prose 把迭代精炼实现为递归 block(evaluator 打分 0-100,if **score >= 85**即输出,否则 refiner 改进后递归降深度)。反面模式infinite-refinement提醒:退出条件必须是可达到的("修复所有已知 bug"而非"零 bug"),并警惕收益递减。

multi-perspective-review:多视角评审

综合前收集多元视角,不同透镜捕捉不同问题:

parallel: user_perspective = session "Evaluate from end-user viewpoint" tech_perspective = session "Evaluate from engineering viewpoint" business_perspective = session "Evaluate from business viewpoint" session "Synthesize feedback and prioritize improvements" context: { user_perspective, tech_perspective, business_perspective }

adversarial-validation:对抗性验证

用一个智能体挑战另一个的工作,对抗压力提升健壮性:

let proposal = session "Generate proposal" let critique = session "Find flaws and weaknesses in this proposal" context: proposal let defense = session "Address each critique with evidence or revisions" context: [proposal, critique] session "Produce final proposal incorporating valid critiques" context: [proposal, critique, defense]

consensus-building:共识构建

关键决策要求独立评估者之间达成一致:

parallel: eval1 = session "Independently evaluate the solution" eval2 = session "Independently evaluate the solution" eval3 = session "Independently evaluate the solution" loop until **evaluators agree** (max: 3): session "Identify points of disagreement" context: { eval1, eval2, eval3 } parallel: eval1 = session "Reconsider position given other perspectives" context: { eval1, eval2, eval3 } eval2 = session "Reconsider position given other perspectives" context: { eval1, eval2, eval3 } eval3 = session "Reconsider position given other perspectives" context: { eval1, eval2, eval3 } session "Document consensus decision" context: { eval1, eval2, eval3 }

五、可维护性模式(Maintainability Patterns)

可维护性模式决定程序能否被他人(或三个月后的你)理解与修改。

descriptive-agent-names:按角色命名

按角色而非实现命名智能体,名字应传达意图:

# Good: Role-based naming agent code-reviewer: agent technical-writer: agent>agent json-extractor: model: haiku prompt: """ Extract structured data from text. Input: Unstructured text containing entity information Output: JSON object with fields: name, date, amount, status If a field cannot be determined, use null. Never invent information not present in the input. """

separation-of-concerns:关注点分离

每个会话只做一件事并做好。组合简单会话,而非创建复杂会话:

# Good: Single responsibility per session let data = session "Fetch and validate input data" let analysis = session "Analyze data for patterns" context: data let recommendations = session "Generate recommendations from analysis" context: analysis session "Format recommendations as report" context: recommendations # Bad: God session session "Fetch data, analyze it, generate recommendations, and format a report"

反面模式god-session给出了完整拆解示范:把"读全部代码、找安全问题、找性能瓶颈、查风格违规、生成报告、给出修复建议、按严重度排序、制定修复计划"的巨型会话,分解为并行安全/性能/风格三个聚焦会话再汇聚。

explicit-context-flow:显式上下文流

通过显式 context 传递让数据流可见,避免依赖隐式对话历史:

# Good: Explicit flow let step1 = session "First step" let step2 = session "Second step" context: step1 let step3 = session "Third step" context: [step1, step2] # Bad: Implicit flow (relies on conversation state) session "First step" session "Second step using previous results" session "Third step using all previous"

反面模式implicit-dependencies直指要害:依赖对话历史记住"项目名 Acme、截止周五",在重构中极其脆弱;显式context才是可移植的契约。

六、性能模式(Performance Patterns)

性能模式在保证正确性的前提下追求响应速度与资源利用率的平衡。

lazy-evaluation:惰性求值

把昂贵操作推迟到真正需要其结果时。不要计算可能用不上的东西:

session "Assess situation" if **detailed analysis needed**: # Expensive operations only when necessary parallel: deep_analysis = session "Perform deep analysis" model: opus historical = session "Gather historical comparisons" session "Comprehensive report" context: { deep_analysis, historical } else: session "Quick summary" model: haiku

反面模式eager-over-computation展示了反面:并行预计算简单/详细/深度三种分析,却只在choice中用到一种。

progressive-disclosure:渐进披露

先快、便宜的操作起步,仅在需要时升级到昂贵操作:

# Tier 1: Fast screening (haiku) let initial = session "Quick assessment" model: haiku if **needs deeper review**: # Tier 2: Moderate analysis (sonnet) let detailed = session "Detailed analysis" model: sonnet context: initial if **needs expert review**: # Tier 3: Deep reasoning (opus) session "Expert-level analysis" model: opus context: [initial, detailed]

work-stealing:工作窃取

用parallel ("any", count: N)从工作池中以最快速度获取 N 个结果:

# Get 3 good ideas as fast as possible from 5 parallel attempts parallel ("any", count: 3, on-fail: "ignore"): session "Generate creative solution approach 1" session "Generate creative solution approach 2" session "Generate creative solution approach 3" session "Generate creative solution approach 4" session "Generate creative solution approach 5" session "Select best from the first 3 completed"

反面模式over-parallelization提供边界:100 个并行会话可能压垮系统、协调开销超过并行收益——分批处理(每批 10 个并行 for)是更稳的做法;premature-parallelization则提醒微小任务并行是过度设计。

七、组合模式(Composition Patterns)

组合模式把多个基础模式编织成更高级的编排结构。

workflow-template:工作流模板

创建编码完整工作流模式的 block,用不同参数实例化:

block research-report(topic, depth): let research = session "Research {topic} at {depth} level" let analysis = session "Analyze findings about {topic}" context: research let report = session "Write {depth}-level report on {topic}" context: [research, analysis] # Instantiate for different needs do research-report("market trends", "executive") do research-report("technical architecture", "detailed") do research-report("competitive landscape", "comprehensive")

middleware-pattern:中间件模式

用横切关注点(日志、计时、校验)包裹会话:

block with-validation(task, validator): let result = session "{task}" let valid = session "{validator}" context: result if **validation failed**: throw "Validation failed for: {task}" do with-validation("Generate SQL query", "Check SQL for injection vulnerabilities") do with-validation("Generate config file", "Validate config syntax")

circuit-breaker:熔断器

反复失败后停止尝试、快速失败,防止级联故障:

let failures = 0 let max_failures = 3 loop while **service needed and failures < max_failures** (max: 10): try: session "Call external service" # Reset on success failures = 0 catch: failures = failures + 1 if **failures >= max_failures**: session "Circuit open - using fallback" throw "Service unavailable"

八、可观测性模式(Observability Patterns)

可观测性模式让长流程可调试、可监控。

checkpoint-narration:检查点叙述

长工作流中发出进度标记,便于调试与监控:

session "Phase 1: Data Collection" # ... collection work ... session "Phase 2: Analysis" # ... analysis work ... session "Phase 3: Report Generation" # ... report work ... session "Phase 4: Quality Assurance" # ... QA work ...

34-content-pipeline.prose 即为范本:以 Phase 1 并行研究、Phase 2 综合、Phase 3 初稿、Phase 4 编辑循环、Phase 5 社交变体、Phase 6 打包六个检查点组织全程。

structured-output-contracts:结构化输出契约

请求可被可靠解析和验证的结构化输出:

agent structured-reviewer: model: sonnet prompt: """ Always respond with this exact JSON structure: { "verdict": "pass" | "fail" | "needs_review", "issues": [{"severity": "high"|"medium"|"low", "description": "..."}], "suggestions": ["..."] } """ let review = session: structured-reviewer prompt: "Review this code for security issues"

反面模式vague-discretion在此同样适用:loop until **the output is good enough**无法评估,而"响应包含带全部必填字段的合法 JSON"这类可观察条件才是可执行的标准。

模式选型:没有银弹,只有约束匹配

原文档的总结给出了清晰的组合思路——最有效的 OpenProse 程序组合以下模式:

  1. 结构:并行化独立工作,用 block 复用
  2. 健壮性:约束循环、处理错误、重试瞬时失败
  3. 效率:模型分级、最小化上下文、尽早终止
  4. 质量:迭代、多视角、对抗性验证
  5. 可维护性:清晰命名、关注点分离、显式数据流

但模式选择取决于你的具体约束:快速原型优先速度而非健壮性;生产工作流优先可靠性而非成本;研究探索优先彻底性而非效率。评审.prose程序时可对照反面模式清单自查(antipatterns.md 末尾的问题清单):独立工作能否并行化?循环是否有界?错误是否被处理?上下文是否最小且显式?模型是否与任务复杂度匹配?智能体是否聚焦且可复用?陌生人能否看懂这段代码?

编写新程序时,可同时加载 guidance/patterns.md 与 guidance/antipatterns.md 两份指导文件(SKILL.md 明确这两个文件仅用于创作而非运行),并以 examples/ 中的 40+ 个程序为参照模板——从 01-hello-world.prose 起步,到 29-captains-chair.prose 这样的完整编排系统,让模式成为你编排 AI 智能体的默认思维框架。

  • 人工智能
  • 大模型
  • LLM 网关
  • AI Agent
  • 即时通讯

【免费下载链接】openclaw-zero-token

OpenClaw: Use All Major AI Models NO API Token! Claude/ChatGPT/Gemini/DeepSeek/Doubao/Grok/Qwen/Manus/Kimi

项目地址:https://gitcode.com/gh_mirrors/op/openclaw-zero-token
点击查看免费下载
上一篇:3步掌握暗黑2存档编辑器:从入门到精通的完整实战指南
下一篇:英雄联盟玩家终极指南:如何用League Akari打造全自动游戏体验

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询