Token导航 LogoToken导航

Agent Skill · 研究检索

schema-first-prompting(模式优先提示)

用于辅助提示词、系统指令、Agent 行为约束和工作流模板的整理。它适合让 Agent 规范任务边界、统一输出格式、拆分操作步骤或优化提示词可复用性。使用时需要保留真实业务约束,不要把示例当硬规则;涉及自动执行、外部工具或高风险操作时,应在提示词中明确确认步骤、权限边界和失败处理方式。

schema-first-prompting 是研究检索类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为需要联网;许可证信息还不明确,第三方扫描已通过,按安装量在研究检索类的 73,675 个 Skill 里排第 62,819。

总安装 326周安装 14GitHub Stars 2下载 114核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:schema-first-prompting(模式优先提示)
来源仓库:https://github.com/agamiko/schema-first-prompting
仓库路径:skills/schema-first-prompting
安装命令:
npx skills add https://github.com/agamiko/schema-first-prompting --skill schema-first-prompting
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/agamiko/schema-first-prompting --skill schema-first-prompting

这个 Skill 是做什么的

研究检索类 Skill 主要解决「找资料、核对事实、把来源整理清楚」的问题,通常会让助手先检索再总结。

用于辅助提示词和工作流模板的整理,适合规范 Agent 行为约束。可统一输出格式、拆分操作步骤或优化提示词复用性。需保留真实业务约束,避免将示例当作硬规则使用。涉及自动执行或外部工具调用时,应在提示词中明确确认步骤和失败处理。

schema-first-prompting 属于研究检索类 Skill,可作为该场景下的辅助能力补充。

来源仓库内路径:skills/schema-first-prompting

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/agamiko/schema-first-prompting --skill schema-…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要需要联网,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

schema-first-prompting 怎么安装?

在终端执行 npx skills add https://github.com/agamiko/schema-first-prompting --skill schema-first-prom…。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

schema-first-prompting 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

schema-first-prompting 需要什么权限?

权限级别是需要联网。该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

schema-first-prompting 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

schema-first-prompting 用的人多吗?

公开数据是累计安装 326 次,近一周安装 14 次,下载 114 次,GitHub 2 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

schema-first-prompting 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理研究检索类任务、又不想每次都手写提示词的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

研究检索类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
find-skills

寻找技能 · Codex、Claude

31,199,81316,486操作浏览器MIT有提醒
self-improving-agent

自我改进 Agent · OpenClaw

16,464,0023,396接触敏感数据MIT-0通过
soultrace

灵魂追踪 · Codex、Claude

7,588,94412需要联网未明确有提醒
self-improving

自我完善 · OpenClaw

6,829,2841,046需要联网MIT-0通过
microsoft-foundry

微软代工厂 · Codex、Claude

6,614,144764调用外部服务未明确有提醒
schema-first-prompting

模式优先提示 · 本页

3262需要联网未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

Schema-First Prompting

Design the Pydantic model first, then write the prompt. The model is the structural contract; the prompt carries only what the schema cannot encode. Be brief, clean, elegant, and internally consistent.

1. Don't say the same thing twice

Schema owns shape — names, types, nesting, constraints. Prompt owns intent — tone, audience, rhetorical rules. If the same fact lives in both places, delete the duplicate.

WhatWhere
Shape, types, limitsPydantic model (Field, validators)
Fixed values from variant/slotCode, after validation
Rhetorical / quality rulesPrompt
Which schema to useCaller (conditional model + prompt)

When the API supports structured output or tool parameters tied to JSON Schema, put structure there. Keep user/system messages to task, context, and behavior.

If native structured output is unsupported and you must inject the schema into the prompt, avoid injecting raw JSON Schema (model_json_schema()), as it is highly token-inefficient. Instead, use type-definition pseudo-code (TypeScript-style interfaces), which can reduce token usage by up to 60% while being clearer to the model's attention mechanism.

The prompt should not restate: field names, types, nesting, required vs optional, defaults, or key enumerations the schema already covers.

Keep in the prompt: intent and tone, constraints the schema cannot encode ("no proper nouns from the input", "at most 50 words"), inputs and template variables, conditional blocks via variables — not by asking the model to "ignore" a section.

No contradictions

If a field says max_length=5, the prompt must not say "3–8 items." Pydantic constraints are exact; the model reads prompt numbers as vibes. Contradictions create hidden bugs worse than either version alone.

Template variables for branches

USER_PROMPT = """You are extracting a plan.

{extra_instructions}

Source text:
{source}
"""
# Caller sets extra_instructions="" or extra_instructions=RISKS_BLOCK when using PlanWithRisks.

The model never sees instructions for a branch that is not in the schema.

Review checklist

When reviewing a prompt/model pair, verify:

  • Names match: prompt uses the same field and concept names as the schema.
  • Constraints match: counts, limits, optionality, and branch behavior are identical.
  • Responsibilities match: prompt asks only for what the schema expects; schema models only what the LLM must produce.
  • Assumptions explicit: model capability requirements, input shape expectations, and downstream consumer needs are documented or obvious from context.

2. Put reasoning first

Field order in a schema is not cosmetic. Autoregressive models commit to tokens left to right, so if your schema puts decision before reasoning, the model fills in an answer before it thinks.

  • Reasoning / chain-of-thought fields first — before the target data they inform.
  • High-level decisions before details — tone or strategy before body_text.
  • Independent fields before dependent ones — if B depends on A, A comes first.

A dedicated reasoning field in a nested model can improve quality for that step. It costs tokens — use it when the task is hard, not on every leaf. Do not duplicate the same instruction in the prompt if the field description already states how to reason.

3. Don't ask for what you already know

If a value can be derived from a lookup table, variant, or existing metadata, keep it out of the schema. The LLM should only touch fields that require reading the input and making a judgment.

Derive fixed values in code

If a value is fixed once you know the variant or slot, derive it with a mapping, match, or helper — not by asking the model.

Use separate models, not optional fields

Do not use risk_section: RiskAssessment | None plus prompt prose saying "omit when low-risk." That asks the model to make a structural decision you already know the answer to. Select a different root model before the LLM call.

class RiskAssessment(BaseModel):
    summary: str
    severity: Literal["low", "medium", "high"]

class PlanWithRisks(BaseModel):
    outline: OutlineSection
    summary: str = Field(description="Closing summary.")
    risk_section: RiskAssessment

class PlanWithoutRisks(BaseModel):
    outline: OutlineSection
    summary: str = Field(description="Closing summary.")
    # risk_section does not exist on this model at all

What belongs in the schema

IncludeExclude
Text, labels, lists the model must authorValues derived from variant/slot
Structure the model must chooseDefaults your code will apply
Fields downstream truly consume"Helper" fields merged in after validation

4. Design for how LLMs work

A schema is an interface to a language model. Design around what the model is good and bad at, not what looks clean in an ORM.

Separate LLM models from API and DB models

LLM extraction shapes, API request/response types, and persistence rows have different fields and invariants. One "god model" for all layers leaks fields across boundaries. Keep scratchpad and reasoning fields for the LLM that users and databases should never see.

Ask for decisions, not estimates

LLMs are poor at absolute numeric values — millisecond durations, pixel coordinates, precise word counts. They are much better at categorical decisions: which severity level, which item ranks first, which bin. Reframe numbers as choices wherever possible. If you must ask for a number, keep the range small and well-defined in the field description.

Match structure to task difficulty

If a task is easy, do not add reasoning fields or scaffolding "just in case." Extra fields cost tokens and can *reduce* quality by forcing justification. If a task is hard (multi-entity extraction, long-range consistency), invest in reasoning fields and break the work into steps. The right amount of structure depends on observed difficulty, not importance.

Scope the context per step

Dumping an entire manuscript into one call and asking for a complex nested output is a recipe for degraded quality in the tail. Break large pipelines into focused steps, each with its own schema, where the input is scoped to what that step needs. Use prompt caching for shared context (style guides, instructions), but restart the generation context for each step so the model's attention is fresh. This is not just a cost optimization — it directly improves output quality on later fields.

5. Start with the tightest schema that works

Begin with the simplest schema that could work. Add reasoning fields, submodels, and constraints only when the output proves they are needed. Complexity should be earned by failure, not anticipated by speculation.

The prompt suggests; the schema enforces.

Bad: "please make sure the list has 3–5 items." Good: min_length=3, max_length=5 in the model.


Schema shape

One model per shape

Each distinct output shape gets its own model. Optional fields that only apply to some shapes are a smell — use a discriminated union or separate models (see section 3).

Discriminated unions

Fixed slots — when the parent model has named fields, the field name tells you the shape. Do not add a kind inside each child that repeats what the field name says.

class OutlineSection(BaseModel):
    title: str = Field(description="Section heading.")
    bullets: list[str] = Field(default_factory=list, max_length=8)

class DocumentPlan(BaseModel):
    outline: OutlineSection
    summary: str = Field(description="Closing summary: 2-3 sentences.")

Tagged union — when a single value must be one of several shapes, you need a discriminator for deserialization:

from typing import Annotated, Literal, Union

from pydantic import BaseModel, Field

class SearchStep(BaseModel):
    kind: Literal["search"] = "search"
    query: str

class AnswerStep(BaseModel):
    kind: Literal["answer"] = "answer"
    text: str

Step = Annotated[
    Union[SearchStep, AnswerStep],
    Field(discriminator="kind"),
]

class Plan(BaseModel):
    steps: list[Step]

kind is the wire-format tag the model must emit so the union parses. Do not mirror it as a second field (action, step_type).

Avoid single-string wrappers

Every nested model should earn its keep by adding real structure, clearer validation, or a stable reusable concept. A BaseModel with one str field adds nesting without structure — use a plain field with Field(description=...) on the parent. Keep a dedicated model when there are at least two meaningful fields, or when you are grouping a stable sub-object at a known serialization boundary that will genuinely grow. "Will grow" means there is a concrete next field on the roadmap — not a hypothetical one.

# Bad — wrapper adds nothing
class ClosingSummary(BaseModel):
    text: str = Field(description="2-3 sentences.")

class Report(BaseModel):
    closing: ClosingSummary

# Good
class Report(BaseModel):
    closing: str = Field(description="Closing summary: 2-3 sentences.")

Skip schemas entirely for single values

If the entire task resolves to a single string, number, or boolean, do not use structured output or a Pydantic model. Forcing the model to return {"translated_text": "Bonjour"} wastes tokens on JSON formatting, keys, and whitespace, and adds latency with no structural benefit.

When you only need one value, use a normal text completion and a prompt that pins the shape of the answer (for example, “return only the French translation”). Use schemas when the output must tie together multiple fields, enforce relationships, or support downstream validation.

Bad — unnecessary overhead:

class Translation(BaseModel):
    translated_text: str

# LLM outputs: {"translated_text": "Bonjour"}  # 11+ tokens on the wire

Good — plain text:

# No schema. Prompt: "Return ONLY the French translation and nothing else."
# LLM outputs: "Bonjour"  # ~2 tokens

Base classes

Extract a shared base only when several shared fields justify it. One duplicated field across two models is clearer than a _Base with a single line.

Field design

  • Mutable defaults: default_factory=list, never [].
  • Descriptions: Field(description=...) is good practice — it guides the model and ships with JSON Schema. Each description should add new information: constraints, how this field differs from a sibling, edge cases, or rhetorical rules the name cannot carry. Do not paraphrase the field name (summary: str plus description "Summary of the document" adds nothing). Prefer a concrete bound or shape hint ("Closing summary: 2–3 sentences."). Avoid internal jargon; long or subtle rules belong in the description so they travel with the schema.
  • Dead fields: if nothing produces or consumes a field, drop it. Drop "legacy" aliases too.
  • Names: short, specific, readable in code and JSON Schema. Prefer names that describe the actual concept, not the implementation accident. Avoid vague names like data, info, payload, value, type2, or misc. Avoid ornamental naming: if BannerCopy says it, do not name a field banner_copy_text_value. Keep siblings parallel — quote_text / quote_source, not quoteAttributionLine. Rename awkward names early; small schema names spread into prompts, validators, logs, tests, and downstream code.
  • Nullable vs empty: use str | None = None when missing differs from empty. Under strict constrained decoding, omitted keys are not allowed — all fields must be marked as required, using nullable types (["string", "null"]) for optional values while keeping the key in required.
  • Closed sets: for Enum or Literal, include an escape hatch (OTHER, UNKNOWN) when the model must say "none of the above."
  • Bounded extras: open-ended dict[str, str] invites huge blobs. Prefer list[SmallObject] (or (key, value) tuples) with max_items plus a short description of the cap. Note that max_items is stripped during strict-mode sanitization for OpenAI, so keep Python-side validation.
  • Entity relationships: model IDs explicitly (parent_id, friend_ids: list[int]), not free-text names. Downstream code should not parse prose for links.
  • Known structure: nested models, max_length / max_items, enums or Literal where the LLM must pick from a closed set. However, some providers' strict modes forbid validation keywords — see strict mode section below.
  • Unknown structure: dict[str, Any], loose list[dict[str, Any]] — use only where the content is genuinely open-ended. A known concept should not be dict[str, Any].

Strict mode and validation

Provider-specific strict mode

Not all providers handle JSON Schema validation keywords the same way. Know what your target supports before relying on field-level constraints.

Write your Pydantic models with full validation (max_length, ge, le, max_items, etc.). Then apply a provider-specific sanitizer only where required. This gives you one authoritative model with the tightest constraints, and a thin adapter layer per provider.

OpenAI (strict=True): forbids maxLength, maxItems, minimum, maximum, and similar validation keywords in JSON Schema. Sending a model with Field(ge=0, le=150) results in an immediate 400 error. additionalProperties must be false; empty dictionary annotations (dict[str, Any]) will cause immediate failure. Implement a schema sanitizer that strips these constraints from the JSON Schema before sending, while keeping the unmodified Pydantic model for Python-side validation.

Anthropic (tool use): accepts standard JSON Schema validation keywords including maxLength, minLength, pattern, minimum, maximum, minItems, and maxItems. Pydantic models with Field(ge=0, le=150) or Field(max_length=500) work as-is. However, the model may still occasionally violate soft constraints, so keep Python-side validation as a safety net.

Sanitizers

LLM completions are untrusted input. Do not assume the model returns clean JSON — raw text may include markdown fences or leading prose. Extract JSON (or use the provider's native structured output) before model_validate / model_validate_json.

Sanitizers and validators are complementary: pre-parse cleanup vs. post-parse rules.

Do: coerce None → "", list → joined string where needed, strip overlong strings, pop() keys that are not on the model (LLM hallucinated extras).

Don't: re-implement defaults or Literal enforcement the validator already applies; keep dead branches for old shapes.

Validation feedback loop

When model_validate() fails due to hallucinations or missed constraints, do not simply drop the data. Catch the Pydantic ValidationError and feed the exact error message (e.g., "Value error, Name must contain a space") back to the LLM in a new user prompt, commanding it to self-correct its previous output. Libraries like Instructor automate this retry loop by catching validation errors and returning them directly to the model alongside the original completion payload.

Production

Prompts are artifacts, not immortal strings. Separate fixed wording from runtime data. Track changes in source control — when behavior shifts, you need a diff and a rollback story. Before changing a schema or prompt, define what "better" means — specific fields that should improve, edge cases that should now pass, or metrics that should move. Verify against these criteria after the change. Keep a small golden set of inputs with expected or acceptable outputs; rerun when the model or prompt changes. Subjective tasks still need criteria: length, must-include fields, forbidden patterns. Log latency, token use, and validation failures per prompt version so regressions surface before users report them.

平台分布

Codex

35.95%
按下载量换算41

Claude

32.28%
按下载量换算37

Cursor

19.86%
按下载量换算23

Gemini CLI

8.99%
按下载量换算10

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills