近年、AIエージェントは単純なテキスト生成から自律的な意思決定へと進化を遂げました。本稿では、Pythonを用いたAIエージェントの基礎から実装まで、ゼロから丁寧に解説します。私が実際にECサイトのカスタマーサービス自動化プロジェクトでぶつかった壁とその解決策も交えながら、初めてAIエージェントに触れる开发者にも分かりやすく説明します。

AIエージェントとは?基本概念の理解

AIエージェントとは、ユーザーの指示を受けて自律的にタスクを実行するシステムのことです。従来のLLM(大規模言語モデル)が「受け身」で応答するのに対し、エージェントは「能動的」に行動し、目標達成を目指します。

エージェントの3つの核心能力

実践編:Pythonで最初のAIエージェントを作る

ここからは具体的なコードとともに、AIエージェントを実装していきます。今すぐ登録して取得したAPIキーを使用し、HolySheep AIの安定したAPI基盤を活用します。

プロジェクト構成

ai-agent-project/
├── config.py
├── agent_core.py
├── tools.py
├── main.py
└── requirements.txt

1. 環境設定とAPIクライアント

まず、依存関係をインストールし、APIクライアントをセットアップします。HolySheep AIを選ぶ理由は明確にされています:レートが¥1=$1(公式¥7.3=$1比85%節約)という破格のコスト効率と、<50msの超低レイテンシです。

# requirements.txt
openai>=1.12.0
python-dotenv>=1.0.0

config.py

import os from dotenv import load_dotenv load_dotenv()

HolySheep AI設定

HOLYSHEEP_API_KEY = os.getenv("HOLYSHEEP_API_KEY") BASE_URL = "https://api.holysheep.ai/v1" # HolySheep公式エンドポイント

モデル設定(2026年最新価格)

MODELS = { "fast": "gpt-4.1-mini", # $8/MTok - 高速処理用 "balanced": "gpt-4.1", # $8/MTok - 標準タスク "reasoning": "claude-sonnet-4.5", # $15/MTok - 推論タスク "economy": "deepseek-v3.2", # $0.42/MTok - コスト重視 }

2. コアエージェントクラスの実装

次に、エージェントの中核となるクラスを実装します。これはReAct(Reasoning + Acting)パターンを採用した、基本的なAIエージェントです。

# agent_core.py
from openai import OpenAI
from config import HOLYSHEEP_API_KEY, BASE_URL, MODELS
from tools import get_available_tools

class AIAgent:
    """基本的なAIエージェント - ReActパターンを実装"""
    
    def __init__(self, model_name="balanced", max_iterations=10):
        self.client = OpenAI(
            api_key=HOLYSHEEP_API_KEY,
            base_url=BASE_URL,
        )
        self.model = MODELS.get(model_name, MODELS["balanced"])
        self.max_iterations = max_iterations
        self.tools = get_available_tools()
        self.conversation_history = []
    
    def think(self, user_input: str) -> dict:
        """思考プロセスを実行して次の一手を決定"""
        
        messages = [
            {"role": "system", "content": """あなたは問題解決型のAIアシスタントです。
思考プロセスを使って問題を解決し、必要に応じてツールを活用してください。

利用可能なツール:
{tool_descriptions}

応答形式:
1. 思考: 現在の状況を分析し、何をするべきか考えてください
2. 行動: 使用するツール名(該当する場合)
3. 観察: ツールの結果を解釈(該当する場合)
4. 最終回答: ユーザーに返す答え""".format(tool_descriptions=self._format_tools())}
        ]
        messages.extend(self.conversation_history)
        messages.append({"role": "user", "content": user_input})
        
        response = self.client.chat.completions.create(
            model=self.model,
            messages=messages,
            temperature=0.7,
            max_tokens=2000
        )
        
        return {
            "thinking": response.choices[0].message.content,
            "usage": {
                "tokens": response.usage.total_tokens,
                "cost": response.usage.total_tokens / 1_000_000 * 8  # $8/MTok
            }
        }
    
    def _format_tools(self) -> str:
        """ツール一覧をフォーマット"""
        return "\n".join([f"- {tool['name']}: {tool['description']}" 
                         for tool in self.tools])
    
    def run(self, user_input: str) -> dict:
        """エージェントのメイン実行ループ"""
        print(f"\n🤖 エージェント起動 - 入力: {user_input}\n")
        
        iteration = 0
        while iteration < self.max_iterations:
            result = self.think(user_input if iteration == 0 else "続けてください")
            
            print(f"【思考 {iteration + 1}】\n{result['thinking']}\n")
            
            # 最終回答を抽出して終了
            if "最終回答" in result['thinking'] or "final" in result['thinking'].lower():
                break
                
            iteration += 1
        
        self.conversation_history.append(
            {"role": "user", "content": user_input},
            {"role": "assistant", "content": result['thinking']}
        )
        
        return result

使用例

if __name__ == "__main__": agent = AIAgent(model_name="balanced") result = agent.run("東京の天気を調べて、明日の出行プランを提案してください") print(f"コスト: ${result['usage']['cost']:.4f}")

3. ツール関数の定義

エージェントが外部の世界とやり取りするためのツールを定義します。

# tools.py
import json
from datetime import datetime, timedelta
from typing import List, Dict, Callable

def get_available_tools() -> List[Dict]:
    """利用可能なツール一覧を返す"""
    return [
        {
            "name": "search_web",
            "description": "Web検索を実行して最新情報を取得",
            "function": search_web
        },
        {
            "name": "calculate",
            "description": "数学的計算を実行",
            "function": calculate
        },
        {
            "name": "get_time",
            "description": "現在時刻を取得",
            "function": get_current_time
        },
        {
            "name": "send_email",
            "description": "メールを送信(模擬)",
            "function": send_email
        }
    ]

def search_web(query: str) -> Dict:
    """Web検索の模擬実装"""
    # 本番環境では実際の検索APIを接続
    results = [
        {"title": f"'{query}' 相关搜索结果1", "url": "https://example.com/1"},
        {"title": f"'{query}' 相关搜索结果2", "url": "https://example.com/2"}
    ]
    return {
        "query": query,
        "results": results,
        "count": len(results)
    }

def calculate(expression: str) -> Dict: