output-formatting

在系统提示词需要为 AI 输出定义格式规范、长度约束、风格指南或反“AI味”策略时调用,用于聊天机器人、CLI、移动助手、设计生成器等场景。非用于纯内容生成或仅指定返回数据格式的场景。

仓库最近推送
GitHub Stars
231
Forks
47
Issues / PRs
0

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "output-formatting":https://skillpi.com/zh/skills/deepskill-d345925502fc9aaca542a42af4a5d9d8232c5badc67aaa3281c972a346a18674。安装前核对上游来源和版本:https://github.com/kangarooking/system-prompt-skills。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

在系统提示词需要为 AI 输出定义格式规范、长度约束、风格指南或反“AI味”策略时调用,用于聊天机器人、CLI、移动助手、设计生成器等场景。非用于纯内容生成或仅指定返回数据格式的场景。

0 下载

介绍来源: third_party · kangarooking · 1.0.0 参考来源

SkillPi 解读

能完成的任务
翻译待完成,请参阅来源文档。
适合谁
翻译待完成,请参阅来源文档。
输入和输出
翻译待完成,请参阅来源文档。
实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
Frontmatter




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:
  - tactical
  - generation
  anti_triggers:
  - brainstorming
  - vague ideation
  - code golf
  - over-engineering
  response_profile:
    verbosity: low
    directive_strength: high
    abstraction_level: operational
  role: implementation
  scope: implementation
  output-format: code
  content-types:
  - code
  - guidance
  - do-dont
  - examples
  related-skills: prompt-engineering, error-handling, test-driven-development



Output Formatting Specialist

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.

TL;DR Checklist

  • [ ] Define target schema or template before generating output
  • [ ] Validate all fields against type constraints and required keys
  • [ ] Escape special characters that break JSON or markdown parsing
  • [ ] Wrap generation in error-handling fallback for malformed output
  • [ ] Log format compliance metrics for debugging pipeline issues
  • [ ] Reject free-text responses when structured data is explicitly requested

When to Use

Use this skill when:

  • Building AI agent pipelines that parse LLM outputs into application logic
  • Generating API responses or configuration files that must be machine-readable
  • Creating test fixtures, mock data, or dataset annotations with strict column types
  • Designing prompt templates that require consistent formatting across multiple runs
  • Integrating external tools (databases, spreadsheets, visualization engines) that reject malformed input

When NOT to Use

Avoid this skill for:

  • Creative writing, narrative generation, or open-ended brainstorming tasks
  • Real-time chat interactions where latency outweighs structural benefits
  • Prototypes where rapid iteration matters more than output reliability
  • Legacy systems without modern parsing libraries (stick to simple CSV or plain text)

Core Workflow

  1. 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.

  2. 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).

  3. 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.

  4. Render Structured Output — Generate the response using template rendering or serialization functions. Checkpoint: Verify escaping rules for strings containing quotes, newlines, or HTML entities.

  5. 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).

  6. Record Format Compliance — Track success/failure rates by schema version and input pattern. Checkpoint: Log validation errors with exact field paths for downstream debugging.


Implementation Patterns

Pattern 1: JSON Schema Validation with Pydantic

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)$")
    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

Pattern 2: Markdown Table Rendering (BAD vs. GOOD)

# ❌ 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)

Pattern 3: Fallback Serialization Strategy

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)

Constraints

MUST DO

  • Define the target schema or template BEFORE generating any content
  • Validate output against the schema using typed parsers (Pydantic, Zod, or equivalent)
  • Escape special characters that break parsers (|, \n, ", {, })
  • Provide clear error messages with field paths when validation fails
  • Log format compliance rates to detect regression in downstream consumption

MUST NOT DO

  • Generate free-text responses when a structured schema is explicitly defined
  • Rely on regex for JSON or YAML parsing — use proper parsers only
  • Suppress validation errors to keep pipelines running — fail fast instead
  • Hardcode column widths or field lengths without dynamic calculation
  • Return mixed-format outputs (e.g., JSON containing unescaped markdown tables)

Output Template

When implementing or reviewing output formatting logic, produce:

  1. Target Schema/Template — Explicit definition of expected structure with types and constraints
  2. Validation Layer — Code snippet showing runtime checks or schema enforcement
  3. Serialization Function — Safe rendering logic with escaping and fallback handling
  4. Compliance Check — Confirmation that output passes linter/schema validator before delivery
  5. Error Handling Path — Documented graceful degradation strategy for malformed generations

Related Skills

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

Live References

Authoritative documentation links for this domain. The model follows markdown links at load time to resolve external references and inline content.

当前收录版本

1.0.0

核对来源版本 ↗

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值85/100

亮点

  • 提供结构化输出生成能力,适用于 AI 代理工作流、API 响应、测试数据生成等高频刚需场景
  • 具有明确的实用价值和广泛受众,能显著提升下游系统处理效率
触发精准90/100

亮点

  • description 明确区分了适用与不适用场景,触发词清晰且边界明确
  • 精准覆盖格式规范、风格指南等核心需求,避免误触
结构规范95/100

亮点

  • 文档结构完整,包含完整的工作流、实现模式、约束条件和输出模板
  • frontmatter 完整,代码示例丰富且规范,单文件长度合理
执行可靠90/100

亮点

  • 提供完整的代码实现模式,包含错误处理、类型检查和转义机制
  • 工具来源明确,覆盖主要异常场景,具备优雅的降级策略
证据可验 (前四项均值)90/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

100 / 100 · skillpi-20261123-no-r3-v1

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

未从主文档识别到上述常见操作,不能据此判断无需权限或没有风险。

文档引用的域名或地址

这些地址可能用于文档链接或示例,不是已批准的联网清单。使用前核对实际目的地及发送的数据。

  • datatracker.ietf.org
  • json-schema.org
  • www.openapis.org
  • yaml.org

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。