📝 OpenClaw Agent输出格式化

世界上有一种输出叫结构化输出,它就像AI的承诺——我不仅给你答案,我还给你一个你能直接用的格式...

"帮我分析一下竞品",AI甩过来一堆文字,我花20分钟才整理成表格。下次我问同样的问题,又是20分钟。我怀疑这个AI是故意浪费我的时间...

📋 功能介绍

🎯 核心能力

💡 为什么需要格式化输出?

想象你在餐厅点菜,服务员说:"给你煮了点东西,有肉有菜有汤"——你懵了。但如果服务员端来一盘摆好的菜,你立刻明白。

AI也一样。格式化输出就是把AI的"煮好的东西"变成"摆好的菜":

🚀 使用方法

1. JSON Schema输出

# 定义输出Schema
agents:
  competitor-analyzer:
    model: claude-sonnet-4
    
    # 强制JSON输出
    output:
      type: json
      schema:
        type: object
        properties:
          competitors:
            type: array
            items:
              type: object
              properties:
                name: { type: string }
                strength: { type: string }
                weakness: { type: string }
                market_share: { type: number }
          summary:
            type: string
          recommendation:
            type: string
        required: [competitors, summary]

2. Markdown格式化输出

# Markdown输出配置
agents:
  report-generator:
    output:
      type: markdown
      
      # 自定义Markdown模板
      template: |
        # {{title}}
        
        **生成时间**: {{timestamp}}
        
        ## 分析结果
        
        {{content}}
        
        ## 建议
        
        {{recommendations}}
        
        ---
        *由 {{agent_name}} 生成*

3. 表格格式化

# 表格输出配置
agents:
  data-analyzer:
    output:
      type: table
      
      # 表格列定义
      columns:
        - name: 产品名称
          key: product_name
          width: 30%
          
        - name: 价格
          key: price
          format: currency  # 自动格式化为 ¥123.45
          
        - name: 评分
          key: rating
          format: rating-stars  # ★★★★☆
          
        - name: 状态
          key: status
          format: badge  # [上架] [下架]

4. 多格式输出

# 同时输出多种格式
agents:
  universal-analyzer:
    output:
      type: multi
      
      formats:
        - type: json      # 给程序用
          schema: ./schemas/analysis.json
          
        - type: markdown  # 给人看
          template: ./templates/report.md
          
        - type: html      # 直接展示
          template: ./templates/report.html

✨ 最佳实践

💡 Schema设计技巧
⚠️ 常见问题
📝 实战示例
# 竞品分析Agent - 完整配置
agents:
  competitor-bot:
    name: 竞品分析师
    
    tools:
      - web_search
      - web_fetch
      
    prompt: |
      你是一个竞品分析专家。
      
      分析用户指定的产品,对比其竞争对手。
      
      输出必须遵循以下JSON Schema:
      {
        "competitors": [
          {"name": "产品名", "features": ["特性列表"], "pricing": "价格描述"}
        ],
        "comparison_table": {
          "headers": ["维度", "我们", "竞品A", "竞品B"],
          "rows": [["功能", "✓", "✓", "✗"]]
        },
        "summary": "一句话总结"
      }
      
    output:
      type: json
      schema: ./schemas/competitor-analysis.json
      validate: true  # 验证输出符合Schema

💻 代码示例

Python调用

from openclaw import Agent
from openclaw.output import JSONSchema, MarkdownTemplate

# 定义JSON Schema
schema = JSONSchema({
    "type": "object",
    "properties": {
        "items": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "price": {"type": "number"},
                    "description": {"type": "string"}
                }
            }
        },
        "total": {"type": "number"}
    }
})

# 创建Agent
agent = Agent(
    name="product-analyzer",
    output=schema  # 强制JSON输出
)

# 执行
result = agent.run("分析这个电商页面的所有产品")

# 输出已经是结构化数据
products = result.items
total = result.total

# 直接存入数据库
db.insert_batch(products)

自定义输出格式化器

from openclaw.output import OutputFormatter

class CSVFormatter(OutputFormatter):
    """CSV格式化输出"""
    
    def format(self, data: dict) -> str:
        # 假设数据是表格格式
        headers = data.get('headers', [])
        rows = data.get('rows', [])
        
        # 生成CSV
        lines = [','.join(headers)]
        for row in rows:
            lines.append(','.join(str(cell) for cell in row))
        
        return '\n'.join(lines)

# 注册格式化器
agent = Agent(
    name="data-exporter",
    output=CSVFormatter()
)

result = agent.run("导出这些数据")
# 输出直接是CSV格式,可直接下载

输出验证

# 验证输出符合Schema
agent = Agent(
    name="structured-agent",
    output=JSONSchema(schema),
    validate_output=True,  # 启用验证
    retry_on_invalid=2     # 验证失败重试2次
)

try:
    result = agent.run("分析数据")
except OutputValidationError as e:
    print(f"输出不符合Schema: {e}")
    # 可以获取原始输出
    raw = e.raw_output

格式转换

from openclaw.output import convert

# JSON → Markdown
json_data = {"items": [{"name": "产品A", "price": 99}]}
markdown = convert(json_data, to="markdown")

# Markdown → HTML
html = convert(markdown, to="html")

# JSON → CSV
csv = convert(json_data, to="csv")

# 多格式同时转换
multi = convert(json_data, to=["json", "markdown", "html", "csv"])
# multi = {"json": "...", "markdown": "...", "html": "...", "csv": "..."}

🔗 相关链接

📊 输出格式对比

格式 适用场景 优点 缺点
JSON 程序处理、数据库 结构化、易解析 不直观
Markdown 文档、报告 可读性强、易编辑 无强结构
HTML 网页展示 直接渲染、样式丰富 解析复杂
CSV 表格数据导出 Excel兼容、简单 仅二维数据