claude-skills/

Anthropic公式スキル・プラグインの日本語ディレクトリ

last sync 22h ago
スキルOfficialdevelopment

📋create-atomic-schema

プラグイン
atomic-agents

説明

Atomic AgentsのagentまたはツールのためのBaseIOSchema入出力ペアを設計・実装します。 docstring、フィールドの説明、バリデーター、エラーバリアントを含みます。 次のような場合に使用: - 「スキーマを作成して」と依頼されたとき - 「入出力スキーマを設計して」と依頼されたとき - 「`IOSchema`を定義して」と依頼されたとき - 「`BaseIOSchema`を実装して」と依頼されたとき - 「agentの出力をモデル化して」と依頼されたとき - `/atomic-agents:create-atomic-schema` を実行したとき

原文を表示

Design and write a `BaseIOSchema` input/output pair for an Atomic Agents agent or tool — docstrings, field descriptions, validators, error variants. Use when the user asks to "create a schema", "design the input/output schema", "define an `IOSchema`", "write a `BaseIOSchema`", "model the agent's output", or runs `/atomic-agents:create-atomic-schema`.

ユースケース

  • スキーマを作成してと依頼されたとき
  • 入出力スキーマを設計してと依頼されたとき
  • `IOSchema`を定義してと依頼されたとき
  • `BaseIOSchema`を実装してと依頼されたとき
  • agentの出力をモデル化してと依頼されたとき

本文(日本語訳)

Atomic Agents スキーマの作成

BaseIOSchema のペア(入力および/または出力)を作成し、agent またはツールと、それを呼び出す側との間のコントラクト(契約)を定義します。フレームワークはすべてのサブクラスに対してdocstringを強制し、Instructor はフィールドの説明を LLM プロンプトに流し込みます。つまり、スキーマはプロンプトの 一部 であり、単なる型定義ではありません。

バリデータ、識別共用体(discriminated unions)、エラーエンベロープなどの詳細については、../framework/references/schemas.md を参照してください。このスキルは実践的なアプローチを提供します: 明確化 → 記述 → 検証。


このスキルと包括的な framework スキルの使い分け

  • このスキル: 特定のスキーマを作成または変更する場合 — 例:「プランナー agent の出力スキーマを設計したい」、「WeatherInput にフィールドを追加したい」、「結果を成功バリアントと失敗バリアントに分割したい」
  • framework スキル: Atomic Agents 全般について質問する場合、またはスキーマの作成以外の作業を行う場合

フェーズ 1 — 明確化

コンテキストから明らかでない点のみを確認します。質問は一度にまとめて行い、一問一答形式にはしないでください。

  1. 呼び出し元AtomicAgent 用か、BaseTool 用か、両方(ツール入力スキーマを出力する agent)か、それともネストされたサブスキーマか?
  2. 方向性 — 入力のみ、出力のみ、または入力/出力のペアか?
  3. フィールド — 呼び出し元が必要とするフィールドと型は何か?(必須 vs オプション、デフォルト値、制約)
  4. 失敗モード — 正当な失敗が起こりうるか? その場合は、例外を投げるのではなく、型付きエラーバリアントを設計する。../framework/references/schemas.md の「Error-schema パターン」を参照。

既存スキーマについての会話が続いている場合は、コンテキストで回答済みの質問はスキップしてください。


フェーズ 2 — 記述

スキーマは、インポート元となる適切な場所に配置します。慣例的な配置場所:

  • <project>/agents/<agent_name>/schemas.py — agent 固有のスキーマ
  • <project>/tools/<tool_name>_tool.py — ツールの I/O はツール本体と同じファイルに配置
  • <project>/schemas/<topic>.py — 複数のコンポーネントで共有するスキーマ

すべてのスキーマに必須の要素

  • BaseModel ではなく BaseIOSchema をサブクラス化する。
  • 空でないクラスdocstringを記述する — フレームワークはインポート時に強制チェックを行います。Instructor がスキーマの description として使用するため、LLM に向けて書いてください。
  • すべての Field(...)description= を付与し、LLM に向けた説明を書く。
  • 閉じた値のセットには Enum よりも先に Literal[...] を使用する — JSON Schema がフラットになり、Instructor にとって扱いやすくなります。

最小テンプレート

from typing import Optional, Literal
from pydantic import Field
from atomic_agents import BaseIOSchema


class WeatherInput(BaseIOSchema):
    """現在の天気情報のリクエスト。"""

    city: str = Field(..., description="都市名。例: 'Brussels' または 'New York'。")
    units: Literal["metric", "imperial"] = Field(
        default="metric",
        description="気温の単位系。",
    )


class WeatherOutput(BaseIOSchema):
    """都市の現在の天気情報。"""

    status: Literal["ok", "error"] = Field(..., description="処理結果コード。")
    temperature_c: Optional[float] = Field(
        default=None, description="status='ok' のときの気温(摂氏)。"
    )
    summary: Optional[str] = Field(
        default=None, description="status='ok' のときの人間が読みやすい概要。"
    )
    error: Optional[str] = Field(
        default=None, description="status='error' のときの失敗メッセージ。"
    )

バリデータを追加するタイミング

  • フィールドレベル: 正規化(小文字化、トリム、enum 変換)および単一フィールドの検証
  • モデルレベル (@model_validator(mode="after")): フィールド間のルール(start ≤ end、相互排他フラグなど)

バリデーションエラーは Instructor のリトライを引き起こし、parse:error フックを発火させます — これはバグではなく、意図された機能です。エラーを握り潰してはいけません。

識別共用体(discriminated unions)を使うタイミング

呼び出し元が複数の結果の形状をもれなく処理しなければならない場合は、膨らんだ単一スキーマよりも共用体を優先してください:

class SearchSuccess(BaseIOSchema):
    """検索の成功結果。"""
    kind: Literal["ok"] = "ok"
    results: list[str] = Field(..., description="一致したアイテム。")

class SearchFailure(BaseIOSchema):
    """検索が完了できなかった場合。"""
    kind: Literal["error"] = "error"
    code: Literal["rate_limited", "no_results", "upstream_error"] = Field(
        ..., description="機械が読み取り可能な失敗コード。"
    )
    message: str = Field(..., description="人間が読みやすい失敗理由。")

class SearchOutput(BaseIOSchema):
    """検索結果 — 成功または型付き失敗。"""
    result: SearchSuccess | SearchFailure = Field(..., description="処理結果。")

各バリアントの kind ディスクリミネータにより、Pydantic は曖昧さなく共用体を解決できます。


フェーズ 3 — 検証

スキーマのインポートと model_json_schema() によるラウンドトリップを簡易チェックします:

uv run python -c "from <project>.<module> import WeatherInput, WeatherOutput; print(WeatherInput.model_json_schema()['title'])"

インポート時に ValueError("… must have a non-empty docstring …") が発生した場合は、docstring を追加してください。フィールドの JSON Schema に description が含まれていない場合は、該当する Field(...)description= を追加してください。


フェーズ 4 — 引き渡し

以下をユーザーに伝えてください:

  • スキーマの配置場所とインポート方法
  • 次のステップ:
    • agent への組み込み → create-atomic-agent スキル
    • ツールへの組み込み → create-atomic-tool スキル
    • 同じドメインに依存するコンテキストプロバイダの追加 → create-atomic-context-provider スキル

一目見たら拒否すべきアンチパターン

  • BaseIOSchema の代わりに素の BaseModel を使用する — docstring の強制チェックと、Instructor が依存する JSON Schema オーバーライドが失われます。
  • クラスdocstringの欠落 — フレームワークがインポート時に例外を発生させます。
  • description= のない Field(...) — Instructor がそのフィールドについて LLM に何も伝えられません。
  • デフォルト値のない Optional[str] — 必須かつnullable という設定は、ほとんどの場合意図した動作ではありません。
  • フィールドの型に dictAny、または object を使用する — LLM が何でも生成でき、Pydantic が検証できません。
  • 「agent をより堅牢にするため」として ValidationError をキャッチする — そうするのではなく、フィールドの制約や説明を修正してください。

より詳細な内容 — スキーマの合成、ネストされたスキーマ、本番環境での識別共用体、バリデータの注意点 — については、../framework/references/schemas.md を参照してください。

原文(English)を表示

Create an Atomic Agents Schema

Author a BaseIOSchema pair (input and/or output) that becomes the contract between an agent or tool and its caller. The framework enforces docstrings on every subclass, and Instructor flows field descriptions into the LLM prompt — so the schema is part of the prompt, not just typing.

For deep material (validators, discriminated unions, error envelopes), the authority is ../framework/references/schemas.md. This skill is the action-oriented path: clarify → write → validate.

When this fires vs the umbrella framework skill

  • This skill: the user is creating or modifying a specific schema — e.g. "design the output schema for the planner agent", "add a field to WeatherInput", "split the result into success and failure variants".
  • framework skill: the user is asking about Atomic Agents in general or doing something other than authoring schemas.

Phase 1 — Clarify

Ask only what is not already obvious from context. Bundle into one message; do not interrogate one-at-a-time.

  1. Caller — is this for an AtomicAgent, a BaseTool, both (an agent that emits a tool-input schema), or a nested sub-schema?
  2. Direction — input only, output only, or a paired Input/Output?
  3. Fields — what fields does the caller need, with which types? (Required vs optional, defaults, constraints.)
  4. Failure modes — can this legitimately fail? If yes, plan a typed error variant rather than raising. See ../framework/references/schemas.md → "Error-schema pattern".

If the user is mid-conversation about an existing schema, skip questions answered in context.

Phase 2 — Write

Place schema(s) where they will be imported from. Conventional locations:

  • <project>/agents/<agent_name>/schemas.py — agent-owned schemas
  • <project>/tools/<tool_name>_tool.py — tool I/O lives next to the tool
  • <project>/schemas/<topic>.py — schemas shared across multiple components

Required ingredients on every schema

  • Subclass BaseIOSchema (not BaseModel).
  • A non-empty class docstring — the framework raises at import otherwise. Write it for the LLM, because Instructor uses it as the schema's description.
  • Every Field(...) carries a description= written for the LLM.
  • Use Literal[...] for closed sets before reaching for Enum — flatter JSON Schema, easier for Instructor.

Minimal template

from typing import Optional, Literal
from pydantic import Field
from atomic_agents import BaseIOSchema


class WeatherInput(BaseIOSchema):
    """A request for current weather conditions."""

    city: str = Field(..., description="City name, e.g. 'Brussels' or 'New York'.")
    units: Literal["metric", "imperial"] = Field(
        default="metric",
        description="Unit system for the temperature.",
    )


class WeatherOutput(BaseIOSchema):
    """Current weather conditions for a city."""

    status: Literal["ok", "error"] = Field(..., description="Outcome code.")
    temperature_c: Optional[float] = Field(
        default=None, description="Temperature in Celsius when status='ok'."
    )
    summary: Optional[str] = Field(
        default=None, description="Human-readable summary when status='ok'."
    )
    error: Optional[str] = Field(
        default=None, description="Failure message when status='error'."
    )

When to add validators

  • Field-level for normalization (lowercase, strip, enum coercion) and single-field validation.
  • Model-level (@model_validator(mode="after")) for cross-field rules (start ≤ end, mutually exclusive flags).

Validation errors trigger Instructor retries and fire the parse:error hook — they're a feature, not a failure path. Do not swallow them.

When to use discriminated unions

If the caller must exhaustively handle multiple result shapes, prefer a union over an inflated single schema:

class SearchSuccess(BaseIOSchema):
    """Successful search result."""
    kind: Literal["ok"] = "ok"
    results: list[str] = Field(..., description="Matching items.")

class SearchFailure(BaseIOSchema):
    """Search could not complete."""
    kind: Literal["error"] = "error"
    code: Literal["rate_limited", "no_results", "upstream_error"] = Field(
        ..., description="Machine-readable failure code."
    )
    message: str = Field(..., description="Human-readable failure reason.")

class SearchOutput(BaseIOSchema):
    """Search outcome — success or typed failure."""
    result: SearchSuccess | SearchFailure = Field(..., description="Outcome.")

The kind discriminator on each variant lets Pydantic resolve the union without ambiguity.

Phase 3 — Verify

Smoke-check the schema imports cleanly and round-trips through model_json_schema():

uv run python -c "from <project>.<module> import WeatherInput, WeatherOutput; print(WeatherInput.model_json_schema()['title'])"

If the import raises ValueError("… must have a non-empty docstring …"), add the docstring. If a field's JSON schema is missing a description, add description= to its Field(...).

Phase 4 — Hand off

Tell the user:

  • Where the schema lives and what to import.
  • Next step in their flow:
    • Wiring it into an agent → create-atomic-agent skill.
    • Wiring it into a tool → create-atomic-tool skill.
    • Adding a context provider that depends on the same domain → create-atomic-context-provider skill.

Anti-patterns to refuse on sight

  • Plain BaseModel instead of BaseIOSchema — loses docstring enforcement and the JSON-schema overrides Instructor depends on.
  • Missing class docstring — framework raises at import.
  • Field(...) without description= — Instructor has nothing to tell the model about the field.
  • Optional[str] with no default — required-but-nullable, which is rarely the intent.
  • dict, Any, or object as a field type — the LLM produces anything and Pydantic cannot validate.
  • Catching ValidationError to "make the agent more robust" — fix the field constraints or descriptions instead.

For deeper material — composition, nested schemas, discriminated unions in production, validator gotchas — load ../framework/references/schemas.md.

原文・著作権は Anthropic および各プラグイン作者に帰属します。日本語訳は Claude API による自動翻訳です。