output-formatting

Invoked when system prompts need to define output format specifications, length constraints, style guidelines, or anti-"AI-sounding" strategies for AI outputs, applicable to chatbots, CLI tools, mobile assistants, design generators, etc. Not intended for pure content generation or cases that only specify what data format to return.

Last repository push
GitHub Stars
231
Forks
47
Issues / PRs
0

Installation

Review the source and dependencies with a prompt. A package is available to download.

Install with an AI assistant

Copy the prompt so your assistant can review the pinned revision and dependencies first.

View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "output-formatting" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-d345925502fc9aaca542a42af4a5d9d8232c5badc67aaa3281c972a346a18674. Verify the upstream source and version against https://github.com/kangarooking/system-prompt-skills before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.

Source and setup

github.com

Setup guidance pending

See the original source for supported tools, dependencies, and permissions.

Installation test pending

Invoked when system prompts need to define output format specifications, length constraints, style guidelines, or anti-"AI-sounding" strategies for AI outputs, applicable to chatbots, CLI tools, mobile assistants, design generators, etc. Not intended for pure content generation or cases that only specify what data format to return.

0 Downloads

Introduction source: third_party · kangarooking · 1.0.0 Reference

SkillPi interpretation

Tasks
Enforces deterministic structured output generation (JSON schemas, markdown
Audience
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
Inputs and outputs
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.
Testing
Not tested

Browse files

Browse files at the source ↗

Original SKILL.md

Open original ↗
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.

Current listing version

1.0.0

Verify the source revision ↗

Quality assessment

Out of 100 · Assessment report from SkillPi LAB.

Scenario Value85/100

Highlights

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

Highlights

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

Highlights

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

Highlights

  • 提供完整的代码实现模式,包含错误处理、类型检查和转义机制
  • 工具来源明确,覆盖主要异常场景,具备优雅的降级策略
Evidence Verifiability (mean of the first four)90/100

The arithmetic mean of the first four original scores, rounded to a whole number.

Static text checks

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

No current rules matched the text.

This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.

Permissions and checks before use

Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.

These common operations were not identified in the main document. This does not mean no permissions or risks exist.

Domains or addresses referenced in the document

These addresses may be documentation links or examples, not an approved network allowlist. Verify actual destinations and outgoing data before use.

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

These notices grant no permissions. Your host tool must still confirm file changes, secrets, external transfers or costs as needed.

Security rating and access scope

safe · Static evidence review; not a runtime safety guarantee.

Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.