1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

エージェントが自動でエージェントを生成する——Claude Code で実装した Meta-Builder

1
Posted at

TL;DR

複数事業を同時運用する際、ボトルネックの判定から対応エージェントの生成、実行まで自動化するシステム「Meta-Builder」をClaudeで実装できます。このアーキテクチャにより、意思決定が自動化され、優先度の調整が週単位で自動追従するようになります。


はじめに:複数事業運用での意思決定のボトルネック

複数事業を同時運用していると、毎週ボトルネックが変わります。今週は集客、来週は技術負債、その次はマーケティング、という具合です。

従来のアプローチだと、以下のループが人間の手作業になっていました。

  1. メトリクスとシグナルを確認
  2. 「今週のボトルネックは何か」を判断
  3. そのボトルネックに対応するエージェント指示を書き直す
  4. 実行する

この意思決定ループ自体が、経営リソースの消費になっていたのです。

この記事では、この判定と指示生成を自動化する「Meta-Builder」の実装パターンを紹介します。


ボトルネック判定の3層設計

Meta-Builderの核は、判定ロジックの多層化です。単純な「数値が閾値を超えたら〇〇」という設計では、季節要因や事業フェーズで精度がぶれます。

レイヤー1:定量的シグナル

売上成長率、顧客獲得コスト、ユーザー流失率などのメトリクスを収集します。ここで重要なのは「絶対値」ではなく「相対的な変化」を見ることです。

// 過去4週のトレンドに対する今週の変化を計算
function calculateRelativeChange(currentWeek, pastFourWeeks) {
  const average = pastFourWeeks.reduce((a, b) => a + b, 0) / 4;
  return ((currentWeek - average) / average) * 100;
}

const metrics = {
  sales_growth_rate: calculateRelativeChange(
    currentWeek.sales,
    pastFourWeeks.sales
  ),
  cac_trend: calculateRelativeChange(
    currentWeek.cac,
    pastFourWeeks.cac
  ),
  churn_rate: calculateRelativeChange(
    currentWeek.churn,
    pastFourWeeks.churn
  )
};

レイヤー2:定性的シグナル

メトリクスに出ない問題をキャッチします。SlackのメッセージやGitHubのIssueから、ブロッカーに値するキーワードや感情を自動抽出します。

async function extractQualitativeSignals(slackMessages, githubIssues) {
  const message = await client.messages.create({
    model: "claude-opus-4-7",
    max_tokens: 1024,
    system: `Extract bottleneck indicators from team communication.
Return JSON with: {
  signal: string,
  severity: 1-10,
  evidence: string,
  category: "technical" | "people" | "process"
}`,
    messages: [
      {
        role: "user",
        content: `Slack: ${JSON.stringify(slackMessages)}
GitHub Issues: ${JSON.stringify(githubIssues)}
What are the implicit blockers?`
      }
    ]
  });

  return JSON.parse(message.content[0].text);
}

レイヤー3:ドメイン知識による重み付け

「配信本数が減った」と「バグ報告が増えた」は、事業フェーズによって重要度が異なります。これは人間が決めるべき部分ですが、テーブル化して判定ロジックに組み込みます。

{
  "growth_phase": {
    "scale": 1.5,
    "quality": 0.8,
    "retention": 1.2
  },
  "stable_phase": {
    "scale": 0.8,
    "quality": 1.5,
    "retention": 1.3
  },
  "maintenance_phase": {
    "scale": 0.5,
    "quality": 1.0,
    "retention": 1.8
  }
}

実装ステップ1:判定エージェントの実装

定量的・定性的シグナルをまとめて、ボトルネック判定を実行するエージェントを実装します。

const Anthropic = require("@anthropic-ai/sdk");

const client = new Anthropic();

async function detectBottleneck(businessData, signals, weightingTable) {
  const prompt = `
You are a bottleneck detection system for multi-business operations.
Analyze the following data comprehensively.

Quantitative Metrics: ${JSON.stringify(businessData.metrics)}
Qualitative Signals: ${JSON.stringify(signals)}
Business Phase: ${businessData.phase}
Weighting Table: ${JSON.stringify(weightingTable[businessData.phase])}

Output JSON with:
{
  "bottleneck": "marketing" | "engineering" | "product" | "operations",
  "severity": 1-10,
  "confidence": 0-100,
  "key_signals": [string, ...],
  "reasoning": string,
  "recommended_action": string
}
`;

  const message = await client.messages.create({
    model: "claude-opus-4-7",
    max_tokens: 1024,
    messages: [
      {
        role: "user",
        content: prompt
      }
    ]
  });

  return JSON.parse(message.content[0].text);
}

実装ステップ2:エージェント生成テンプレートの設計

判定結果が出たら、そのボトルネック向けのエージェント指示を自動組み立てします。ここで大事なのは、コンテキスト情報を構造化して注入することです。

function generateAgentPrompt(bottleneck, businessContext) {
  const basePrompt = `
Business: ${businessContext.name}
Phase: ${businessContext.phase}
Current Status: ${JSON.stringify(businessContext.metrics)}
Constraints: ${businessContext.constraints.join(", ")}
Success Metrics: ${businessContext.successMetrics.join(", ")}
`;

  const rolePrompts = {
    marketing: `
Role: Marketing Strategist for ${businessContext.name}
Bottleneck: ${bottleneck.reasoning}

Task: Generate 3 actionable marketing experiments for the next 2 weeks.
Each experiment must satisfy:
- Executable without additional headcount
- Budget: $${businessContext.marketingBudget}
- Measurable result within 2 weeks
- Specific channel or audience target

Format: 
1. Experiment name
2. Success metric & target
3. Weekly timeline
4. Resource requirement
5. Risk assessment
`,
    engineering: `
Role: Technical Lead for ${businessContext.name}
Current Bottleneck: ${bottleneck.reasoning}
Tech Stack: ${businessContext.techStack.join(", ")}
Team Size: ${businessContext.teamSize}

Task: Create a prioritized technical improvement plan.
Prioritize by: impact on ${bottleneck.recommended_action}
Timeline: This week (5 days)

For each item:
- Specific PR/task description
- Estimated effort (hours)
- Expected impact
- Risk mitigation
`,
    product: `
Role: Product Manager for ${businessContext.name}
Bottleneck: ${bottleneck.reasoning}
Recent User Feedback: ${businessContext.userFeedback}

Task: Design a focused product improvement plan.
Focus: Solving the identified bottleneck
Timeline: 2 weeks

Deliverable:
- Current state analysis (why the bottleneck exists)
- Root cause (user behavior, technical limitation, market gap)
- Solution option (prioritized by feasibility)
- Implementation roadmap
`
  };

  return basePrompt + rolePrompts[bottleneck.bottleneck];
}

実装ステップ3:自動検証と反復

生成したエージェント指示を実行し、その出力を自動評価して実行可能性を判定します。

async function executeAndEvaluate(agentPrompt, businessContext) {
  // Step 1: エージェント実行
  const agentOutput = await client.messages.create({
    model: "claude-opus-4-7",
    max_tokens: 2000,
    messages: [
      {
        role: "user",
        content: agentPrompt
      }
    ]
  });

  const solution = agentOutput.content[0].text;

  // Step 2: 出力の検証
  const evaluation = await client.messages.create({
    model: "claude-opus-4-7",
    max_tokens: 512,
    system: `Evaluate solution feasibility.
Assess:
1. Is this immediately executable? (Yes/No)
2. Actionability score (1-10)
3. Realistic assumptions? (List any risky assumptions)
4. Resource requirements match constraints? (Yes/No)
5. Recommended adjustments?

Output JSON: {
  executable: boolean,
  score: number,
  risks: [string],
  adjustments: [string]
}`,
    messages: [
      {
        role: "user",
        content: `Solution:\n${solution}\n\nBusiness Context:\n${JSON.stringify(businessContext)}`
      }
    ]
  });

  const evaluationResult = JSON.parse(evaluation.content[0].text);

  // Step 3: 検証に基づいた判断
  if (!evaluationResult.executable || evaluationResult.score < 6) {
    console.log("Solution requires refinement. Adjustments:", evaluationResult.adjustments);
    // フィードバックを含めて再実行
    return await executeAndEvaluate(
      agentPrompt + "\n\nFeedback from evaluation:\n" + JSON.stringify(evaluationResult.adjustments),
      businessContext
    );
  }

  return {
    solution: solution,
    evaluation: evaluationResult,
    status: "approved"
  };
}

実装ステップ4:定期実行の設定

Claude APIの定期実行機能を使って、毎日決まった時刻にMeta-Builderを動作させます。

// 定期実行用エントリーポイント
async function dailyMetaBuilderRoutine() {
  try {
    // 1. メトリクス収集(外部API・DB等から)
    const businessData = await fetchBusinessMetrics();
    
    // 2. シグナル抽出
    const signals = await extractQualitativeSignals(
      await fetchSlackMessages(),
      await fetchGitHubIssues()
    );
    
    // 3. ボトルネック判定
    const bottleneck = await detectBottleneck(
      businessData,
      signals,
      weightingTable
    );
    
    // 4. エージェント生成
    const prompt = generateAgentPrompt(bottleneck, businessData.context);
    
    // 5. 実行と検証
    const result = await executeAndEvaluate(prompt, businessData.context);
    
    // 6. 結果を記録・通知
    await saveResult({
      date: new Date(),
      bottleneck: bottleneck,
      solution: result.solution,
      evaluation: result.evaluation
    });
    
    return result;
  } catch (error) {
    console.error("Meta-Builder routine failed:", error);
    throw error;
  }
}

つまづきポイント

1. フィードバックループの無視

エージェント生成後に「出力が本当に実行可能か」という検証ステップを入れることが重須です。スキップすると、抽象的で使い物にならない指示が生成されます。

2. メトリクスデータの鮮度

判定用の数値が1週間古いデータだと、判定精度が大きく落ちます。毎日更新される情報源を決めておく必要があります。

3. コンテキスト情報の過不足

「ボトルネックに対応するエージェント」は、事業の基本情報(ターゲット層、現在の月次売上、制約条件)を持たない状態では動きません。テンプレートに組み込むコンテキスト粒度を事前に設計しておきましょう。

4. レイヤー3の重み付けテーブルの硬直化

事業フェーズが急速に変わる場合、重み付けテーブルが陳腐化します。3ヶ月ごとのレビューを仕組みに入れておくことをお勧めします。


まとめ

Meta-Builderの導入により、複数事業の優先順位調整が自動化されます。判定とエージェント生成を分離し、各層に適切な粒度の判定ロジックを配置することで、安定した意思決定システムが実現できます。

実装のポイント:

  • 定量的シグナル: 相対的な変化を見る
  • 定性的シグナル: Claude APIで自動抽出
  • ドメイン知識: テーブル化して参照
  • エージェント生成: テンプレート+コンテキスト注入
  • 検証: 常に実行可能性を確認

このアーキテクチャにより、意思決定が自動化され、エンジニアの脳リソースがボトルネック解決に集中できるようになります。


さらに詳しい実装手順はnoteで公開中

この記事では実装の概要を紹介しました。実装の完全手順・プロンプト全文・複数事業での運用ノウハウは以下のnoteで公開しています。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?