计划执行与检查节点
executing-plans
按既定实施计划完成工作,保持过程检查和反馈。
output-formatting【效率与协作】Enforces deterministic structured output generation (JSON schemas, markdown tables, templated responses) for reliable downstream processing in AI agent workflows.
独立 GitHub 快照 · 自动分类 · 以原作者文档为准
name: output-formatting description: Enforces deterministic structured output generation (JSON schemas, markdown tables, templated responses) for reliable downstream processing in AI agent workflows. license: MIT compatibility: opencode metadata: version: "1.0.0" domain: coding triggers: output formatting, structured output, json schema, response templating, deterministic output, data validation, prompt engineering archetypes:
Enforces deterministic structured output generation to ensure downstream systems receive predictable, parseable data. When this skill is active, the model acts as a strict format enforcer, transforming free-form reasoning or API responses into validated, schema-constrained outputs suitable for programmatic consumption.
Use this skill when:
Avoid this skill for:
Analyze Consumption Requirements — Identify who/what will consume the output and what schema it expects. Checkpoint: Confirm required fields, data types, nullability rules, and max lengths before drafting templates.
Select Output Format — Choose between JSON Schema, Markdown Tables, YAML Config, or strict CSV based on downstream constraints. Checkpoint: Validate that the selected format aligns with existing pipeline tooling (e.g., pandas for CSV, Pydantic for JSON).
Construct Validation Layer — Implement runtime checks using typed parsers or schema validators. Checkpoint: Ensure validation runs BEFORE output is returned to the caller; fail fast on type mismatches.
Render Structured Output — Generate the response using template rendering or serialization functions. Checkpoint: Verify escaping rules for strings containing quotes, newlines, or HTML entities.
Sanitize & Normalize — Remove trailing commas, fix casing inconsistencies, normalize whitespace.
Checkpoint: Run output through a linter or format checker (e.g., black, prettier, JSON linters).
Record Format Compliance — Track success/failure rates by schema version and input pattern. Checkpoint: Log validation errors with exact field paths for downstream debugging.
Use typed models to enforce structure before serialization. This catches type mismatches early and provides clear error messages.
from pydantic import BaseModel, Field, ValidationError
from typing import Optional
import json
class StructuredOutput(BaseModel):
"""Strict output schema for downstream consumption."""
status: str = Field(..., pattern=r"^(success|failure|pending)quot;)
timestamp_ms: int = Field(..., gt=0)
metadata: dict[str, str] = Field(default_factory=dict)
payload: list[dict[str, float]] | None = None
def to_json(self, indent: int = 2) -> str:
"""Serialize to JSON with guaranteed escaping and formatting."""
return self.model_dump_json(indent=indent)
def render_response(
status: str,
timestamp_ms: int,
metadata: Optional[dict[str, str]] = None,
payload: Optional[list[dict[str, float]]] = None
) -> str:
"""Generate validated JSON output or raise ValidationError."""
try:
out = StructuredOutput(
status=status,
timestamp_ms=timestamp_ms,
metadata=metadata or {},
payload=payload
)
return out.to_json()
except ValidationError as e:
raise RuntimeError(f"Format validation failed: {e.errors()[0]['msg']}") from e
# ❌ BAD — Manual string concatenation breaks on edge cases, missing alignment, no escaping
def bad_table(rows):
header = "Column A | Column B\n"
body = "\n".join([f"{r['a']} | {r['b']}" for r in rows])
return f"{header}\n{body}"
# ✅ GOOD — Safe, aligned, escapes pipes and newlines, uses standard library
def good_table(rows: list[dict[str, str]], columns: list[str]) -> str:
"""Render a pipe-aligned markdown table with automatic column width calculation."""
if not rows:
return ""
# Calculate max widths per column
col_widths = {col: len(col) for col in columns}
for row in rows:
for col in columns:
val_len = len(str(row.get(col, "")))
col_widths[col] = max(col_widths[col], val_len)
def escape(val: str) -> str:
return str(val).replace("|", "\\|").replace("\n", " ")
header = "| " + " | ".join(c for c in columns) + " |"
separator = "|" + "|".join("-" * (col_widths[c] + 2) for c in columns) + "|"
body_lines = [
"| " + " | ".join(escape(str(row.get(c, ""))) for c in columns) + " |"
for row in rows
]
return "\n".join([header, separator] + body_lines)
When structured generation fails, degrade gracefully instead of crashing the pipeline.
import json
from typing import Any
def safe_serialize(data: Any, fallback_format: str = "json") -> str:
"""Attempt structured serialization; fall back to string representation on failure."""
try:
if fallback_format == "json":
return json.dumps(data, default=str, ensure_ascii=False)
elif fallback_format == "csv":
if isinstance(data, list) and all(isinstance(r, dict) for r in data):
headers = data[0].keys()
lines = [",".join(headers)]
for row in data:
lines.append(",".join(str(v) for v in row.values()))
return "\n".join(lines)
except Exception as e:
# Graceful degradation — never swallow errors silently
return f"ERROR:[serialization_failed] {e}"
return str(data)
|, \n, ", {, })When implementing or reviewing output formatting logic, produce:
| Skill | Purpose |
|---|---|
prompt-engineering | Designs input prompts that naturally yield well-formatted outputs |
error-handling | Provides patterns for catching and reporting format validation failures |
test-driven-development | Ensures output templates are covered by regression test suites |
Authoritative documentation links for this domain. The model follows markdown links at load time to resolve external references and inline content.