0
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?

AIエージェントとは何か|自律的に動くAIの仕組みをPythonで実装しながら理解する【Claude API】

0
Posted at

はじめに

「AIエージェント」という言葉を最近よく聞きませんか?

ChatGPTやClaudeに質問して回答をもらう——これはAIアシスタントです。

AIエージェントは一歩進んで、自分で考え、自分でツールを使い、自分で問題を解決するAIです。

本記事では、AIエージェントの仕組みを解説し、PythonとClaude APIで動くエージェントを実装します。


AIアシスタントとAIエージェントの違い

AIアシスタント(従来):
ユーザー → 質問 → AI → 回答 → ユーザー
(1往復で終わり)

AIエージェント:
ユーザー → 目標 → AI → 計画
                    ↓
             ツール実行(検索・計算・API呼び出し)
                    ↓
             結果を評価・次のアクションを決定
                    ↓
             目標達成まで繰り返す → ユーザーに報告

AIエージェントの4つのコンポーネント

┌────────────────────────────────────────┐
│             AIエージェント              │
│                                        │
│  ┌──────────┐     ┌──────────────┐   │
│  │  Brain   │────▶│ Tool Calling │   │
│  │ (LLM)   │◀────│  (行動実行)  │   │
│  └──────────┘     └──────────────┘   │
│       ↕                   ↕           │
│  ┌──────────┐     ┌──────────────┐   │
│  │ Memory   │     │  Planning    │   │
│  │(記憶保持)│     │  (計画立案)  │   │
│  └──────────┘     └──────────────┘   │
└────────────────────────────────────────┘
コンポーネント 役割 実装例
Brain(LLM) 推論・判断 Claude / GPT-4
Memory(記憶) 過去の情報を保持 会話履歴・ベクトルDB
Planning(計画) タスクを分解・順序付け ReAct・Chain of Thought
Tool Calling(行動) 外部システムを操作 検索・計算・DB・API

ReActパターン:エージェントの思考サイクル

最も広く使われるエージェントの思考パターンが**ReAct(Reasoning + Acting)**です。

Thought(考える):
  "ユーザーは最新のPD試験情報を知りたい。まずWebを検索しよう"

Action(行動する):
  web_search("PD試験 2026 最新情報")

Observation(観察する):
  "検索結果: シラバスVer.0.2が2026年7月に公開された..."

Thought(また考える):
  "情報が得られた。次は試験スケジュールも調べよう"

Action(再度行動):
  web_search("PD試験 開始時期 2027")

...(目標達成まで繰り返す)

Final Answer(最終回答):
  "PD試験は2027年度夏秋に正式開始予定です。シラバムVer.0.2は..."

Pythonで実装:シンプルなエージェント

import anthropic
import json
from datetime import datetime

client = anthropic.Anthropic()

# ── ツールの定義 ──────────────────────────────────
tools = [
    {
        "name": "web_search",
        "description": "インターネットで情報を検索します(デモ用)",
        "input_schema": {
            "type": "object",
            "properties": {
                "query": {"type": "string", "description": "検索クエリ"}
            },
            "required": ["query"]
        }
    },
    {
        "name": "get_datetime",
        "description": "現在の日時を取得します",
        "input_schema": {
            "type": "object",
            "properties": {},
            "required": []
        }
    },
    {
        "name": "calculate",
        "description": "数式を計算します",
        "input_schema": {
            "type": "object",
            "properties": {
                "expression": {"type": "string", "description": "計算式(例: 2 + 3 * 4)"}
            },
            "required": ["expression"]
        }
    }
]

# ── ツールの実行 ──────────────────────────────────
def execute_tool(name: str, inputs: dict) -> str:
    if name == "web_search":
        query = inputs["query"]
        # 実際の実装ではBrave Search APIなどを使用
        return f"[検索結果(デモ)] '{query}' の検索結果: PD試験は2027年度夏秋開始予定。シラバスVer.0.2は2026年7月公開済み。"

    elif name == "get_datetime":
        return datetime.now().strftime("%Y年%m月%d日 %H:%M")

    elif name == "calculate":
        expr = inputs["expression"]
        try:
            result = eval(expr, {"__builtins__": {}})
            return f"{expr} = {result}"
        except Exception as e:
            return f"計算エラー: {e}"

    return f"未知のツール: {name}"


# ── エージェントのメインループ ─────────────────────
class SimpleAgent:
    def __init__(self, system_prompt: str = ""):
        self.system = system_prompt or "あなたは役立つアシスタントです。必要に応じてツールを使って正確な情報を提供してください。"
        self.messages = []
        self.max_iterations = 10

    def run(self, user_input: str) -> str:
        self.messages.append({"role": "user", "content": user_input})
        iterations = 0

        while iterations < self.max_iterations:
            iterations += 1
            response = client.messages.create(
                model="claude-sonnet-5",
                max_tokens=2048,
                system=self.system,
                tools=tools,
                messages=self.messages
            )

            # ツール呼び出しなし → 最終回答
            if response.stop_reason == "end_turn":
                answer = next(
                    (b.text for b in response.content if hasattr(b, "text")), ""
                )
                return answer

            # ツール呼び出しあり → 実行して続行
            self.messages.append({"role": "assistant", "content": response.content})

            tool_results = []
            for block in response.content:
                if block.type == "tool_use":
                    print(f"  [Tool] {block.name}({json.dumps(block.input, ensure_ascii=False)})")
                    result = execute_tool(block.name, block.input)
                    print(f"  [Result] {result[:80]}...")
                    tool_results.append({
                        "type": "tool_result",
                        "tool_use_id": block.id,
                        "content": result
                    })

            self.messages.append({"role": "user", "content": tool_results})

        return "最大ループ回数に達しました。"


# ── 実行例 ───────────────────────────────────────
if __name__ == "__main__":
    agent = SimpleAgent()

    questions = [
        "今日の日付と、3756 * 48 の計算結果を教えてください",
        "PD試験の最新情報を調べて、開始時期を教えてください",
    ]

    for q in questions:
        print(f"
質問: {q}")
        print("-" * 50)
        answer = agent.run(q)
        print(f"回答: {answer}")

マルチエージェント:エージェントが協力する

複雑なタスクでは、複数のエージェントが役割分担して協力します。

class OrchestratorAgent:
    def run(self, task: str) -> str:
        # タスクを分解して専門エージェントに振り分ける
        plan = self.make_plan(task)
        results = []

        for subtask in plan:
            if subtask["type"] == "research":
                result = ResearchAgent().run(subtask["query"])
            elif subtask["type"] == "write":
                result = WritingAgent().run(subtask["topic"], results)
            results.append(result)

        return self.synthesize(results)
Orchestrator(指揮者)
    ├── Research Agent(情報収集専門)
    ├── Analysis Agent(分析専門)
    └── Writing Agent(文章生成専門)

ビジネス活用事例

業界 活用例
ITコンサル 提案書の自動作成・競合調査・議事録生成
金融 レポート作成・規制確認・リスク分析
医療 患者記録の整理・診断補助情報収集
製造 設備異常の検知・メンテナンス手配
採用 求人票作成・候補者スクリーニング

2027年PD試験との関連

PD試験のシラバス(Ver.0.2)では、以下の概念が出題範囲に含まれています:

  • AIエージェントの基礎概念(自律的な判断・行動)
  • Tool Use / Function Calling(AIのツール活用)
  • マルチエージェントシステム(エージェント間連携)
  • AIガバナンス(エージェントの監視・制御)

実装レベルの理解は不要ですが、「エージェントが何をするものか」「どんなリスクがあるか」は問われる可能性があります。


まとめ

概念 ポイント
AIアシスタントとの違い エージェントは自律的にツールを使い目標を達成する
主要コンポーネント Brain・Memory・Planning・Tool Calling
思考パターン ReAct(考える→行動する→観察する)を繰り返す
実装の入口 Claude APIのTool Useが最初の一歩

AIエージェントは「AIに仕事をさせる」次世代の活用形態です。概念を理解しておくことが、実務でもPD試験対策でも重要になってきています。


Qiitaでは他にもPD試験・生成AI関連の技術記事を発信しています。

0
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
0
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?