0Pricing
AI Agents · レッスン

アシスタントから自律エージェントへ

チャットボットから完全自律型までの段階で、それぞれ何が変わるかを学びます。

「アシスタントから自律エージェントへ」はCoddyKit上の無料AI Agentsレッスンです。 これはレッスン1/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはAI Agents学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 AI Agentsコースには全4レッスンが含まれています。

自律性のスペクトラム

AIシステムは、完全な反応型から完全な自律型までのスペクトラム上に存在します。エージェントがこのスペクトラムのどこに位置するかを理解することで、必要なアーキテクチャコンポーネント、人間による監督の必要量、予測すべき失敗モードが決まります。

レベル1:純粋なチャットボット

純粋なチャットボットは、メッセージにテキストで応答します。現在のコンテキストウィンドウを超えるメモリや、ツール、目標、世界に対して行動する能力はありません。すべてのやり取りはステートレスです。人間による監督の必要性は最小限です。生成できるのはテキストだけで、行動はできないためです。

import anthropic

# Level 1: Pure chatbot — single turn, no memory, no tools
def pure_chatbot(user_message: str) -> str:
    client = anthropic.Anthropic(api_key='YOUR_API_KEY')
    response = client.messages.create(
        model='claude-opus-4-5',
        max_tokens=512,
        messages=[{'role': 'user', 'content': user_message}]
    )
    return response.content[0].text

# What it has:
#   - Language understanding
#   - Knowledge from training
# What it lacks:
#   - Memory (no history between sessions)
#   - Tools (cannot access external data)
#   - Goals (no objective to pursue)
#   - Proactivity (only responds, never initiates)

response = pure_chatbot('What is the capital of Australia?')
print(response)

レベル2:ツール拡張型エージェント

ツール拡張型エージェントは、ウェブ検索、データベースクエリ、コード実行、API呼び出しなどの外部機能を追加します。最新のデータが必要な質問にも回答できます。メモリはセッション内で保持される場合があります。人間による監督の必要性は中程度です。データは読み取れますが、アクションは通常、読み取り専用または低リスクだからです。

import anthropic

# Level 2: Tool-augmented agent
def tool_augmented_agent(user_message: str, conversation_history: list) -> str:
    client = anthropic.Anthropic(api_key='YOUR_API_KEY')

    tools = [
        {
            'name': 'search_web',
            'description': 'Search the web for current information',
            'input_schema': {'type': 'object',
                             'properties': {'query': {'type': 'string'}},
                             'required': ['query']}
        }
    ]

    conversation_history.append({'role': 'user', 'content': user_message})

    response = client.messages.create(
        model='claude-opus-4-5',
        max_tokens=1024,
        tools=tools,
        messages=conversation_history
    )

    # Handle tool use...
    return response.content[-1].text if response.stop_reason == 'end_turn' else '[tool called]'

# What changed vs Level 1:
#   + Tools (external data access)
#   + Session memory (conversation history)
# Still lacking:
#   - Persistent cross-session memory
#   - Goals (still reactive)
#   - Proactivity

レベル3:目標指向型エージェント

目標指向型エージェントは、複数のステップにわたって定義された目的を追求し、ツール呼び出しの間で状態を維持します。目標をサブタスクに分解するプランナーを備えています。人間による監督の必要性は大きくなります。現実世界に累積的な影響を及ぼす可能性のある複数ステップのアクションを実行するためです。

# Level 3: Goal-directed agent
class GoalDirectedAgent:
    def __init__(self, goal: str, tools: list, client):
        self.goal = goal
        self.tools = tools
        self.client = client
        self.memory = []  # persistent across steps
        self.plan = self._make_plan()

    def _make_plan(self) -> list:
        response = self.client.messages.create(
            model='claude-opus-4-5', max_tokens=512,
            messages=[{'role': 'user', 'content':
                f'Goal: {self.goal}\n'
                'Create a numbered list of steps to achieve this goal. '
                'Each step should be a single tool call or reasoning step.'
            }]
        )
        return response.content[0].text

    def step(self) -> str:
        # Execute next planned step
        return 'step executed'

# What changed vs Level 2:
#   + Goal: has an objective to pursue
#   + Planning: decomposes goal into sub-tasks
#   + Persistent memory across steps
# Still lacking:
#   - Self-directed (still initiated by human)
#   - Self-improvement

if __name__ == '__main__':
    class FakeContent:
        def __init__(self, text):
            self.text = text

    class FakeResponse:
        def __init__(self, text):
            self.content = [FakeContent(text)]

    class FakeMessages:
        def create(self, **kwargs):
            return FakeResponse('1. Search web for topic\n2. Summarize findings\n3. Draft report')

    class FakeClient:
        def __init__(self):
            self.messages = FakeMessages()

    agent = GoalDirectedAgent(goal='Write a market report', tools=[], client=FakeClient())
    print('Goal:', agent.goal)
    print('Plan:')
    print(agent.plan)

レベル4:自己主導型エージェント

自己主導型エージェントは、自らサブ目標を設定し、関連するイベントがないか環境を監視し、人間からの指示なしにアクションを開始します。長期メモリと世界モデルを備え、状況が変化した場合には再計画できます。人間による監督の必要性は高くなります。自律的にアクションを開始するためです。

import time

# Level 4: Self-directed agent (simplified sketch)
class SelfDirectedAgent:
    def __init__(self, mission: str, client):
        self.mission = mission
        self.client = client
        self.goals_queue = []
        self.long_term_memory = []
        self.running = False

    def start(self):
        self.running = True
        self._generate_initial_goals()
        while self.running:
            self._observe_environment()
            self._prioritise_goals()
            if self.goals_queue:
                goal = self.goals_queue.pop(0)
                self._pursue_goal(goal)
            time.sleep(60)  # autonomous monitoring loop

    def _observe_environment(self):
        # Agent monitors for events without being asked
        print('Observing environment...')

    def _generate_initial_goals(self):
        # Agent decomposes its mission into actionable goals
        self.goals_queue = ['Monitor inbox', 'Check project status']

    def _prioritise_goals(self):
        # Agent re-orders goals based on new observations
        pass

    def _pursue_goal(self, goal: str):
        print(f'Pursuing: {goal}')

if __name__ == '__main__':
    agent = SelfDirectedAgent(mission='Manage my inbox proactively', client=None)
    agent._generate_initial_goals()
    print('Initial goals:', agent.goals_queue)
    agent._observe_environment()
    goal = agent.goals_queue.pop(0)
    agent._pursue_goal(goal)

各レベルで変わる点:メモリ

自律性のレベルが高くなるほど、メモリ要件も増加します。レベル1ではコンテキストウィンドウ(セッションメモリ)のみを使用します。レベル2では永続的なセッション履歴が追加されます。レベル3では構造化されたタスク状態が追加されます。レベル4では、エピソード記憶(何が起きたか)、意味記憶(エージェントが知っていること)、手続き記憶(物事の進め方)が必要になります。

MEMORY_BY_LEVEL = {
    'L1_chatbot': {
        'scope': 'context_window_only',
        'persistence': 'none',
        'implementation': 'messages list in current API call'
    },
    'L2_tool_augmented': {
        'scope': 'session',
        'persistence': 'in-memory (lost on restart)',
        'implementation': 'conversation_history list'
    },
    'L3_goal_directed': {
        'scope': 'task',
        'persistence': 'persists for task duration',
        'implementation': 'SQLite or Redis with task state'
    },
    'L4_self_directed': {
        'scope': 'long_term',
        'persistence': 'indefinite',
        'implementation': 'vector DB (episodic) + structured DB (semantic) + prompt cache (procedural)'
    }
}

for level, info in MEMORY_BY_LEVEL.items():
    print(f'{level}: {info["implementation"]}')

各レベルで変わる点:計画

計画の要件も自律性に応じて拡大します。レベル1には計画がありません。レベル2では単一ステップの推論を行う場合があります。レベル3では複数ステップの計画(Chain of Thought、ReAct)を使用します。レベル4では、失敗時に再計画する階層型計画が必要になります。

PLANNING_BY_LEVEL = {
    'L1': 'None — single response',
    'L2': 'Single-step tool selection (which tool to call now)',
    'L3': 'Multi-step plan (goal -> ordered sub-tasks -> tool calls)',
    'L4': 'Hierarchical plan (mission -> goals -> tasks -> actions) + replan on failure'
}

# L3 multi-step planning example:
def plan_goal(goal: str, client) -> list:
    import anthropic
    response = client.messages.create(
        model='claude-opus-4-5', max_tokens=512,
        messages=[{'role': 'user', 'content':
            f'Break this goal into 3-5 concrete steps:\nGoal: {goal}\n'
            'Return JSON: {"steps": [{"step": int, "action": str, "tool": str}]}'
        }]
    )
    import json
    return json.loads(response.content[0].text)

for lvl, desc in PLANNING_BY_LEVEL.items():
    print(f'{lvl}: {desc}')

レベル別の人間による監督要件

自律性が高まるにつれて、人間による監督メカニズムの必要性も高まります。レベル1ではほとんど必要ありません。レベル4では、承認ゲート、アクションログ、中断メカニズム、異常検知を備えた明示的な監督アーキテクチャが必要です。

OVERSIGHT_BY_LEVEL = {
    'L1_chatbot': [
        'None required (output only)'
    ],
    'L2_tool_augmented': [
        'Review tool permissions (read-only vs write)',
        'Audit logs of tool calls'
    ],
    'L3_goal_directed': [
        'Human approval before irreversible actions',
        'Plan review before execution starts',
        'Progress checkpoints',
        'Full audit trail'
    ],
    'L4_self_directed': [
        'Human approval before high-impact actions',
        'Real-time action streaming to oversight dashboard',
        'Emergency stop mechanism',
        'Anomaly detection on goal drift',
        'Regular review of long-term memory state',
        'Corrigibility: agent must accept shutdown'
    ]
}

for level, requirements in OVERSIGHT_BY_LEVEL.items():
    print(f'{level}:')
    for req in requirements:
        print(f'  - {req}')

プロアクティブ性:重要な転換点

アシスタントから自律型エージェントへの最も根本的な変化は、プロアクティブ性です。アシスタントは待機します。エージェントは行動を開始します。つまり、エージェントは環境を監視し、関連するイベントを認識し、指示を受けることなく行動するタイミングを判断する必要があります。

# Proactive monitoring pattern
import asyncio
from datetime import datetime

class ProactiveMonitor:
    def __init__(self, agent_fn, check_fn, interval_seconds: int = 60):
        self.agent_fn = agent_fn
        self.check_fn = check_fn
        self.interval = interval_seconds

    async def run(self):
        print(f'Proactive monitor started, checking every {self.interval}s')
        while True:
            try:
                events = await self.check_fn()
                for event in events:
                    print(f'[{datetime.utcnow().isoformat()}] Event: {event}')
                    await self.agent_fn(event)
            except Exception as e:
                print(f'Monitor error: {e}')
            await asyncio.sleep(self.interval)

# Example: agent monitors for new emails every 5 minutes
# and proactively drafts replies or flags urgent ones
async def example_setup():
    monitor = ProactiveMonitor(
        agent_fn=lambda e: print(f'Agent handling: {e}'),
        check_fn=lambda: [],  # replace with real inbox check
        interval_seconds=300
    )
    # await monitor.run()

if __name__ == '__main__':
    import asyncio

    async def demo():
        async def check_fn():
            return ['New email from boss@example.com']

        async def agent_fn(event):
            print(f'Agent drafting reply for: {event}')

        monitor = ProactiveMonitor(agent_fn=agent_fn, check_fn=check_fn, interval_seconds=1)
        try:
            await asyncio.wait_for(monitor.run(), timeout=0.3)
        except asyncio.TimeoutError:
            pass

    asyncio.run(demo())

レベル別のエラー回復

エラー回復の要件も拡大します。チャットボットは謝罪するだけです。ツールエージェントはツール呼び出しを再試行します。目標指向型エージェントは、失敗したステップを回避するように再計画します。自己主導型エージェントは、エラーを自律的に検出、分類、エスカレーションし、将来同じ失敗を避けられるよう世界モデルを更新します。

# Error recovery strategies by autonomy level

def chatbot_error_recovery(error: Exception) -> str:
    return 'I\'m sorry, I encountered an error. Please try again.'

def tool_agent_error_recovery(tool_name: str, error: Exception, retries: int) -> str:
    if retries < 3:
        return f'Retrying {tool_name} ({retries+1}/3)'
    return f'Tool {tool_name} unavailable after 3 retries, skipping'

def goal_agent_error_recovery(failed_step: dict, plan: list, client) -> list:
    import anthropic, json
    client_obj = anthropic.Anthropic(api_key='YOUR_API_KEY')
    response = client_obj.messages.create(
        model='claude-opus-4-5', max_tokens=256,
        messages=[{'role': 'user', 'content':
            f'Step failed: {failed_step}\nRemaining plan: {plan}\n'
            'Revise the remaining plan to work around the failure. Return JSON plan.'
        }]
    )
    return json.loads(response.content[0].text)

print('Error recovery patterns defined for each autonomy level')

適切なレベルの選択

すべてのユースケースにレベル4が必要なわけではありません。まず要件を満たす最低限のレベルから始め、必要な場合にのみ複雑さを追加してください。自律性が高いほど、複雑さと監督の負担が増し、予期しない動作が発生する可能性も高まります。

def recommend_autonomy_level(requirements: dict) -> str:
    needs_realtime = requirements.get('realtime_data', False)
    needs_multistep = requirements.get('multi_step_tasks', False)
    needs_unsupervised = requirements.get('runs_unsupervised', False)
    needs_initiative = requirements.get('initiates_actions', False)

    if needs_initiative and needs_unsupervised:
        return 'L4_self_directed (high oversight required)'
    if needs_multistep:
        return 'L3_goal_directed (plan review recommended)'
    if needs_realtime:
        return 'L2_tool_augmented (audit logs required)'
    return 'L1_chatbot (minimal oversight)'

# Examples:
print(recommend_autonomy_level({
    'realtime_data': True, 'multi_step_tasks': False,
    'runs_unsupervised': False, 'initiates_actions': False
}))
print(recommend_autonomy_level({
    'realtime_data': True, 'multi_step_tasks': True,
    'runs_unsupervised': True, 'initiates_actions': True
}))

理解度チェック

レベル3の目標指向型エージェントと、レベル4の自己主導型エージェントの間で、最も根本的に異なる能力は何ですか。

まとめ:アシスタントから自律型エージェントへ

すばらしいです。ここまでで学んだことは次のとおりです。

  • L1チャットボット:反応型、テキストのみ、メモリなし、監督不要
  • L2ツール拡張型:セッションメモリ、ツール呼び出し、中程度の監督
  • L3目標指向型:複数ステップの計画、タスク範囲のメモリ、承認ゲート
  • L4自己主導型:プロアクティブ、長期メモリ、階層型計画、高度な監督
  • 目安:要件を満たす最低限のレベルから始めます

次は、世界モデルと予測計画について学びます。エージェントが行動前にどのようにシミュレーションするかを扱います。

よくある質問

「アシスタントから自律エージェントへ」レッスンは無料ですか?

はい。「アシスタントから自律エージェントへ」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、AI Agentsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 AI Agentsコースには全4レッスンが含まれています。

「アシスタントから自律エージェントへ」で何を学びますか?

チャットボットから完全自律型までの段階で、それぞれ何が変わるかを学びます。 ブラウザで直接実行するハンズオンコードでAI Agentsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

AI Agentsを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのAI Agentsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン1/4です。

「アシスタントから自律エージェントへ」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このAI Agentsレッスンでコードを書いて実行できますか?

はい。すべてのAI Agentsレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. アシスタントから自律エージェントへ
  2. ワールドモデルと予測的プランニング
  3. 自律エージェントにおけるアライメントの課題
  4. 研究の最前線:AGI とその先
← AI Agentsに戻る