design-task について
design-taskは、明確な指示、出力、依存関係、品質チェックを備えたCrewAIタスクを設計するスキルです。構造化出力、ガードレール、非同期実行、人によるレビューなどの設定と実行方法も扱います。
主な機能
- 01タスクの説明と期待する出力の定義
- 02タスクのコンテキストと依存関係の説明
- 03構造化出力とファイル出力への対応
- 04非同期実行と人によるレビューの設定
- 05関数型およびLLMガードレールの説明
活用シーン
- 01明確な基準を備えた調査タスクの設計
- 02選択したタスク結果の後続タスクへの受け渡し
- 03後続タスクの前に出力を検証
- 04重要な結果を人のレビュー用に保留
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ crewaiinc/ skills --skill design-taskインストール後、Claude Code で/design-taskを入力して読み込まれたか確認します。
同梱ファイルreferences/structured-output.md
詳細
CrewAI タスク設計ガイド
エージェントから信頼性の高い高品質な出力を得るための、効果的なタスクの書き方です。
2026-10-01 に crewai 1.15.22 および 1.15.23 に対して検証済みです。 2026-10-01 に実際の LLM を使ってライブテスト済みです。 正確な最新の API 形式(インポート、パラメーター名、構造化出力、ガードレールのシグネチャ)については、check-crewai-api スキルを参照してください。このスキルと内容が異なる場合は、check-crewai-api に従ってください。
80/20 の法則:労力の 80% をタスク設計に、20% をエージェント設計に費やしましょう。 タスクは最も重要な調整手段です。平凡なエージェントでも、適切に設計されたタスクであれば、優秀なエージェントでも、設計の不十分なタスクより良い結果を出せます。
1. 効果的なタスクの構成要素
すべてのタスクには、description(何をどのように行うか)と expected_output(結果がどのような形式か)の 2 つが必要です。どちらも必須です。Task(description=...) だけでは ValidationError ... expected_output Field required が発生します。
Description — 指示
適切な description には、次の内容を含めます。
- 何をするか — 中心となる作業
- どのように行うか — 具体的な手順やアプローチ
- コンテキスト — なぜ重要なのか、何に使われるのか
- 制約 — 対象範囲の制限、避けるべきこと
- 入力 — 利用できるデータやコンテキスト
research_task:
description: >
Conduct thorough research about {topic} for the year {current_year}.
Your research should:
1. Identify the top 5 key trends and breakthroughs
2. For each trend, find at least 2 credible sources
3. Note any controversies or competing viewpoints
4. Assess potential industry impact (high/medium/low)
Focus on developments from the last 6 months.
Do NOT include speculation or unverified claims.
The output will feed into a report for {target_audience}.
expected_output: >
A structured research brief with 5 sections, one per trend.
Each section includes: trend name, 2-3 paragraph summary,
source citations, impact assessment (high/medium/low),
and a confidence level for your findings.
agent: researcher
Expected Output — 成功基準
expected_output は、エージェントに「完了」がどのような状態かを伝えます。次の点を具体的に指定してください。
- 形式 — 箇条書き、段落、JSON、表
- 構成 — セクション、見出し、順序
- 長さ — おおよその語数や項目数
- 品質基準 — 必要な引用、信頼度、指定フィールド
| 不適切な Expected Output | 適切な Expected Output |
|---|---|
A research report | 5 つのセクションからなる構成済みのブリーフ。各セクションには、トレンド名、2~3 段落の概要、出典の引用、影響度評価を含める |
An analysis of the data | 指標名、現在値、過去 30 日間の傾向、推奨アクションを列にした Markdown 表。指標を少なくとも 10 個含める。 |
A blog post | 1,000~1,500 語の技術ブログ記事。タイトル、導入、コード例を含む 3~4 個の主要セクション、次のステップを示す結論を含める。 |
2. 単一目的の原則
1 つのタスクにつき、目的は 1 つです。 複数の操作を 1 つのタスクにまとめてはいけません。
# DON'T - a "god task" with four objectives
research_and_write_task:
description: >
Research {topic}, analyze the findings, write a blog post,
and proofread it for grammar errors.
expected_output: >
A polished blog post about {topic}.
# DO - focused tasks, one objective each
research_task:
description: >
Research {topic} and identify the top 5 key developments.
expected_output: >
A research brief with 5 sections covering key trends.
agent: researcher
writing_task:
description: >
Using the research findings, write a technical blog post about {topic}.
expected_output: >
A 1000-1500 word blog post with introduction, main sections, and conclusion.
agent: writer
# ...and an editing_task with agent: editor
各タスクには明確な目的が 1 つあります。逐次フローではコンテキストが自動的に引き継がれます。
3. タスク設定リファレンス
必須パラメーター
Task(description="...", expected_output="...", agent=researcher) # agent: required for sequential, optional for hierarchical
エージェントが設定されていないタスクを逐次クルーに含めると、Crew(...) で失敗します。エラーは Sequential process error: Agent is missing in the task ... です。
context によるタスクの依存関係
analysis_task = Task(description="Analyze the research findings...", expected_output="...",
agent=analyst, context=[research_task]) # receives only research_task's output
逐次クルーと階層型クルーでルールは同じです。
contextなし — タスクは、それより前に実行されたすべてのタスクの生の出力を受け取ります。context=[a, b]— タスクは、それらのタスクの出力のみを受け取ります。context=[]— タスクは、それ以前の出力を一切受け取りません。
context の項目には、クルー内の先行タスクを指定する必要があります。後続タスクを指定すると、Crew(...) で失敗します(「context dependency on a future task」)。
構造化出力
後続のコードで結果を解析する必要がある場合は、output_pydantic または output_json を使用します。
from pydantic import BaseModel
class ResearchReport(BaseModel):
trends: list[str]
confidence: float
sources: list[str]
research_task = Task(description="...", agent=researcher,
expected_output="A structured report with trends, confidence score, and sources.",
output_pydantic=ResearchReport) # agent's output is parsed into this model
重要: expected_output は常に文字列の説明であり、クラス名ではありません。Pydantic モデルは output_pydantic に指定し、expected_output のテキストでエージェントに含めるフィールドを伝えます。output_pydantic と output_json はどちらか一方だけを設定してください(両方を設定すると Only one output type can be set が発生します)。
構造化出力へのアクセス:
result = crew.kickoff(inputs={...})
last_task_output = result.pydantic # Pydantic model from the LAST task (None if it has no output_pydantic)
all_outputs = result.tasks_output # List of all TaskOutput objects
first_task = all_outputs[0].pydantic # Pydantic from a specific task
assert first_task is not None, "structured output was dropped"
output_pydantic は tasks.yaml ではなく Python で設定してください(セクション 5)。Task(response_format=...) は使用しないでください(無視されます)。また、Task(response_model=...) も使用しないでください(.pydantic は None のままになります)。詳細:structured-output.md。
ファイル出力
Task(..., output_file="output/report.md") は出力を保存します。create_directory(デフォルトは True)を指定すると、存在しないディレクトリが作成されます。書き込まれる内容は出力タイプによって異なります。通常のタスクでは生テキストが、output_pydantic または output_json が設定されている場合はモデルの JSON が保存されます(ファイル名が .md であっても同様です)。構造化タスクの内容を人が読みやすいファイルにしたい場合は、モデルを使わない別の整形タスクを追加し、そのタスクに output_file を指定してください。
非同期実行
pros = Task(..., agent=analyst, async_execution=True)
cons = Task(..., agent=critic, async_execution=True) # a DIFFERENT agent
verdict = Task(..., agent=analyst, context=[pros, cons])
crew = Crew(agents=[analyst, critic], tasks=[pros, cons, verdict])
非同期タスクは待機せずに開始し、連続する非同期タスクは同時に実行されます。次の同期タスクは、開始前に保留中のすべての非同期タスクの完了を待ちます。また、(context がない場合は)それらすべての出力を参照します。参照する出力を選ぶには context=[...] を指定してください。
ルールはすべて強制されます。
- 同時に実行する非同期タスクには、それぞれ別のエージェントを割り当ててください。 同じエージェント上で2つの非同期タスクを実行すると、開始時に
RuntimeError: Executor is already running. Cannot invoke the same executor instance concurrently.が発生します。 - クルーの最後に置ける非同期タスクは1つまでです(
The crew must end with at most one asynchronous task)。結果を収集する同期タスクで終了してください。 - 非同期タスクは、同じ同時実行中の非同期タスクを自身の
contextに指定できません。また、ConditionalTaskを非同期にすることはできません。
人によるレビュー
Task(..., human_input=True) を指定すると、最終確定の前に人によるレビューのため一時停止します。エージェントが回答を生成すると、ターミナルに「Human Feedback Required」パネルが表示され、stdin から1行読み込まれます。フィードバックを入力すると、エージェントは回答を修正して再度確認を求めます。空行(Enter)を入力すると、回答が承認されます。人の承認が必要な重要な出力に使用してください。
対話型の stdin が必要です。CI、サーバー、または stdin が閉じられた状態で実行すると、input() が EOFError を発生させます。これはエージェントの再試行後に起きるため、追加の LLM 呼び出しの料金も発生します。スクリプトから操作するには、回答をパイプで渡してください。printf 'Make it shorter.\n\n' | python run.py(フィードバックを1回送った後、承認します)。ターミナルに依存できない承認ステップについては、build-flow スキルの Flow @human_feedback を参照してください。
通常の会話の続きとして、human_input=True や Flow @human_feedback を使用しないでください。 会話型 Flows では、次のユーザー発話に対して flow.handle_turn(message, session_id=...) を再度呼び出してください。人によるレビューは、特定のタスクまたはステップの出力を、後続の処理に進む前に承認または修正するためのものです。
Markdown の書式設定
Task(..., markdown=True) は、最終回答を必ず Markdown(見出し、太字・斜体、箇条書き、コードスパン、フェンス付きコードブロック)にするよう、タスクのプロンプトに指示を追加します。
コールバック
def log_completion(output: TaskOutput) -> None: # from crewai import TaskOutput
print(f"Task completed: {output.description[:50]}...")
Task(..., callback=log_completion) # called with the TaskOutput after the task and its guardrails finish
4. タスクのガードレール — 品質管理
ガードレールは、タスクの出力が次のステップに渡される前に検証します。検証に失敗すると、エラーがエージェントに返され、guardrail_max_retries(デフォルトは3)までタスクが再試行されます。その後、タスクは Task failed guardrail validation after N retries. Last error: ... を発生させます。
関数ベースのガードレール
from typing import Any
from crewai import Task, TaskOutput
def validate_word_count(output: TaskOutput) -> tuple[bool, Any]:
"""Ensure output is between 500-2000 words."""
word_count = len(output.raw.split())
if word_count < 500:
return (False, f"Output too short ({word_count} words). Expand to at least 500 words.")
if word_count > 2000:
return (False, f"Output too long ({word_count} words). Condense to under 2000 words.")
return (True, output.raw)
Task(..., guardrail=validate_word_count, guardrail_max_retries=3) # max retries (default: 3)
戻り値の形式: (bool, Any)。第1要素は成功/失敗、第2要素は成功時の結果(タスクの生出力になる文字列。通常は output.raw。None は不可)または失敗時のエラーメッセージです。TaskOutput 自体ではなく文字列を返してください。タスクに output_pydantic が設定され、エージェントがツールを持つ場合、ガードレール内では output.pydantic は依然として None です。また、(True, output) とするとその状態が維持されるため、result.pydantic も None になります。一方、(True, output.raw) とすると crewai が変換できます(1.15.22 および 1.15.23 で確認済みです)。戻り値の型は tuple[bool, Any] と注釈するか、注釈を付けないでください。-> bool とすると、Task(...) で If return type is annotated, it must be Tuple[bool, Any] が発生します。非推奨の max_retries ではなく、guardrail_max_retries を使用してください。
LLM ベースのガードレール
Task(..., agent=writer, guardrail="Verify the output contains at least 3 source citations and no speculative claims.")
文字列のガードレールは、タスクのエージェントの LLM を使用した追加の LLM 呼び出しによって検証されます。主観的な品質チェックに適しています。タスクには agent が必要です。指定しない場合、Task(...) は Agent is required to use non-programmatic guardrails を発生させます。
複数のガードレールを連鎖させる
def validate_no_pii(output: TaskOutput) -> tuple[bool, Any]:
if "@" in output.raw:
return (False, "Remove email addresses.")
return (True, output.raw)
Task(..., guardrails=[
validate_word_count, # Function: check length
validate_no_pii, # Function: check for PII
"Ensure the tone is professional and appropriate for a business audience.", # LLM check
])
ガードレールは順番に実行されます。それぞれが前のガードレールの出力を受け取ります(文字列の結果は、次のガードレールの output.raw を置き換えます)。関数ベース(決定論的)と LLM ベース(主観的)のチェックを組み合わせてください。guardrails=[...] と guardrail= の両方を設定した場合、リストのみが使用されます。
5. YAML 設定(推奨)
tasks.yaml
research_task: # full description/expected_output as in section 1
description: >
Conduct thorough research about {topic} for {current_year}.
expected_output: >
A structured research brief with 5 sections.
agent: researcher
analysis_task:
description: >
Analyze the research findings and recommend actions for {target_audience}.
expected_output: >
A prioritized list of 5 recommendations with rationale and expected impact.
agent: analyst
context:
- research_task
report_task:
description: >
Compile a final report combining research and analysis for {target_audience}.
expected_output: >
A polished markdown report with executive summary, findings and recommendations.
agent: writer
output_file: output/report.md
crew.py での接続
from pydantic import BaseModel
from crewai import Agent, Crew, Task
from crewai.project import CrewBase, agent, crew, task
class Recommendations(BaseModel):
items: list[str]
@CrewBase
class ResearchCrew:
agents_config = "config/agents.yaml"
tasks_config = "config/tasks.yaml"
# @agent methods researcher, analyst, writer omitted
@task
def research_task(self) -> Task:
return Task(config=self.tasks_config["research_task"])
@task
def analysis_task(self) -> Task:
# context and agent come from YAML; the model class must be set here in Python
return Task(config=self.tasks_config["analysis_task"], output_pydantic=Recommendations)
@task
def report_task(self) -> Task:
return Task(config=self.tasks_config["report_task"]) # output_file comes from YAML
@crew
def crew(self) -> Crew:
return Crew(agents=self.agents, tasks=self.tasks)
メソッド名は YAML のキーと一致させてください。 YAML の context: エントリは、同じ名前の @task メソッドを呼び出して解決され、agent: は同じ名前の @agent メソッドを呼び出して解決されるため、一致しない場合はクルーの構築時に失敗します。YAML では description、expected_output、agent、context、output_file、human_input、async_execution、markdown が使用できます。output_pydantic、output_json、関数ガードレール、tools は Python メソッドに記述してください。
6. タスクの依存関係とコンテキストの流れ
タスクはリストの順番に実行されます。context を持たないタスクは、それ以前のすべてのタスクの生の出力を受け取ります。
research_task → analysis_task → report_task
↓ ↓ ↓
(none) output 1 output 1 + 2
そのために context= を指定する必要はありません。これは暗黙的に行われます。依存関係を絞り込んだり、形を整えたりするには、これを使用してください。
# Diamond dependency pattern
task_a = Task(...) # Entry point
task_b = Task(..., context=[task_a]) # Depends on A
task_c = Task(..., context=[task_a]) # Also depends on A
task_d = Task(..., context=[task_b, task_c]) # Depends on both B and C
条件付きタスク
from pydantic import BaseModel
from crewai import Task, TaskOutput
from crewai.tasks.conditional_task import ConditionalTask # not crewai.task
class Items(BaseModel):
items: list[str]
gather = Task(description="List data sources for {topic}...", expected_output="A list of sources.",
agent=researcher, output_pydantic=Items) # the condition below reads .pydantic
def needs_more_data(output: TaskOutput) -> bool:
return len(output.pydantic.items) < 10
extra_research = ConditionalTask(description="Fetch additional data sources...", expected_output="...",
agent=researcher,
condition=needs_more_data) # runs only if the previous output has < 10 items
条件には、直前のタスクの TaskOutput が渡されます。スキップされた条件付きタスクも result.tasks_output に表示され、その raw == "" となります。ConditionalTask を最初のタスクにすることはできず、非同期にもできません。また、クルーを条件付きタスクのみで構成することもできません。
7. タスクのツール
タスクには、そのタスクに限りエージェントのデフォルトツールを置き換える独自のツールを設定できます。
from crewai_tools import SerperDevTool, ScrapeWebsiteTool
Task(description="Search for and scrape the top 5 articles about {topic}...", expected_output="...",
agent=researcher, tools=[SerperDevTool(), ScrapeWebsiteTool()]) # task-specific tools
タスクに tools を設定すると、そのタスクでエージェントが使用できるのはそれらのツールのみです。リストは統合されません。エージェントのツールを使用するには、設定を省略してください。
エージェントが通常は持たないツールをタスクに使わせる場合、特定のタスクでエージェントのツールを制限する場合、または同じエージェントにタスクごとに異なるツールセットを使わせる場合は、タスクレベルのツールを使用してください。
8. 変数の補間
再利用可能なタスクには、YAML で {variable} プレースホルダーを使用してください。
research_task:
description: >
Research {topic} trends for {current_year}, targeting {target_audience}.
expected_output: >
A report on {topic} suitable for {target_audience}.
変数はキックオフ時に置換されます:crew.kickoff(inputs={"topic": "AI Agents", "current_year": "2026", "target_audience": "developers"})。
よくある間違い:
inputsに変数がない → キックオフ時にValueError: Missing required template variable ... 'audience' not found in inputs dictionaryが発生します{{ }}の Jinja2 構文を使用する → crewAI では単一の波括弧{ }を使用します。{{topic}}は{AI Agents}として出力されますinputsに未使用の変数がある → エラーにならず、無視されます
9. よくあるタスク設計のミス
| ミス | 影響 | 修正方法 |
|---|---|---|
| 説明が曖昧(「トピックを調査する」) | エージェントの出力が浅く、焦点の定まらないものになります | 具体的な手順、制約、コンテキストを追加します |
| expected_output が曖昧(「レポート」) | エージェントが形式や構成を推測します | 形式、セクション、長さ、品質の基準を指定します |
| 1 つのタスクに複数の目的がある | エージェントがどの目的も十分に達成できません | 目的を絞った単一用途のタスクに分割します |
| チャットの各ターンを Crew タスクとしてモデル化する | タスクはバッチ/ワークフローの単位であり、会話セッションのループではありません | 会話型 Flow を使用し、ユーザーメッセージごとに handle_turn() を呼び出します |
| 後続タスクが、先行タスクの出力を見すぎる、または誤った出力を見る | デフォルトでは、先行するすべての出力が渡されます | context=[prior_task](または context=[])を使用して選択します |
expected_output で Pydantic クラスを参照している | エージェントにはフィールド名ではなく、クラス名の文字列が渡されます | expected_output は人が読める文字列のままにし、モデルには output_pydantic を使用します |
tasks.yaml で output_pydantic を設定している | KeyError が発生するか、モデルが破棄されて .pydantic が None になります | @task メソッドで output_pydantic=Model を設定します |
| 同じエージェントに 2 つの非同期タスクを割り当てている | RuntimeError: Executor is already running | 同時に実行する非同期タスクごとに、別のエージェントを使用します |
CI またはサーバーで human_input=True を使用している | 再試行が無駄に行われた後、EOFError が発生します | 標準入力に回答を渡すか、Flow の @human_feedback を使用します |
| データを扱うタスクにツールがない | エージェントがデータを取得せず、捏造します | タスクまたはエージェントにツールを追加します |
| 重要な出力にガードレールがない | 不適切な出力がチェックされずに後続へ渡されます | 関数または LLM のガードレールを追加します |
構造化タスクでガードレールが (True, output) を返す | 実行が成功しても result.pydantic が None になります | (True, output.raw) を返し、.pydantic が None でないことをアサートします |
expected_output またはガードレールが厳しすぎる | Task failed guardrail validation になるまでエージェントが再試行します | 具体的かつ達成可能な条件にし、早く失敗するよう guardrail_max_retries を小さくします |
| 説明がバックストーリーと重複している | トークンが無駄になり、エージェントが混乱します | 説明=何をするか、バックストーリー=何者か、と分けます |
10. タスク設計チェックリスト
タスクを実行する前に、以下を確認してください。
- 説明に、内容、方法、コンテキスト、制約が含まれている
- 期待される出力に、形式、構成、品質の基準が指定されている
- 目的が単一 — タスクごとに明確な目的が 1 つある
- エージェントが割り当てられている(逐次実行の Crew および文字列のガードレールで必須)
- 依存関係 — デフォルト(先行するすべての出力)が適切でない場合、
contextで設定されている - ツール — 外部データが必要なタスクにツールが用意されている
- 構造化出力が Python で設定され、
.pydanticが None でないことをアサートしている - ガードレールが重要な出力に設定され、
(bool, value)を返している - 非同期タスクがそれぞれ別のエージェントで実行され、その後に同期タスクが続く
- 変数 — YAML の変数が
inputs辞書のキーと一致している - 期待される出力が達成可能 — 複雑にする前に、簡単な実行でテストしている
参考資料
特定のトピックについて詳しくは、以下を参照してください。
- 構造化出力 - LLM、Agent、Task、Crew の各レベルにおける
output_pydantic、output_json、response_model、response_format
関連するスキル:
- check-crewai-api - crewai 1.15.x の最新のインポート、パラメーター名、構造化出力、ガードレールの形式
- getting-started — プロジェクトのひな形作成、適切な抽象化の選択、Flow アーキテクチャ
- design-agent — エージェントの Role-Goal-Backstory フレームワーク、パラメーターの調整、ツールの割り当て、メモリーとナレッジの設定
- build-flow - Flow の状態、ルーター、
@human_feedback - test-crewai-project - スタブ LLM を使用したオフラインでのガードレールとタスク接続のテスト
- connect-tools-and-mcp - タスクに追加するツールと、使用可能な
crewai_toolsの名前 - ask-docs - これらのスキルで扱われていない質問について、CrewAI の最新ドキュメントに問い合わせる