﻿※本書掲載リスト




リスト1-1
```Python
import boto3
import json


# Boto3クライアントを作成するリージョンを指定
# aws configure で設定したリージョンと合わせる
TARGET_REGION = "us-east-1" 


print(f"Boto3を使って、リージョン '{TARGET_REGION}' のBedrockに接続テストを行います...")


try:
    # Bedrockの「管理用」クライアントを作成
    # (モデルを呼び出すときは 'bedrock-runtime' を使います)
    bedrock_client = boto3.client(
        service_name='bedrock', 
        region_name=TARGET_REGION
    )


    # 利用可能な基盤モデルのリストを取得してみる
    response = bedrock_client.list_foundation_models()


    print("\n[成功] Boto3のセットアップ成功。Bedrockに接続できました。")


    # 利用可能なモデルが多すぎるため、Anthropic (Claude) のモデルだけを抜粋
    claude_models = [
        model['modelId'] for model in response['modelSummaries'] 
        if 'anthropic.claude' in model['modelId']
    ]


    print(f"\nリージョン '{TARGET_REGION}' で利用可能な Claude モデル (一部):")
    if claude_models:
        for model_id in claude_models:
            print(f"- {model_id}")
    else:
        print("Claude モデルが見つかりません。")


except Exception as e:
    print(f"\n[エラー] 接続に失敗しました: {e}")
    print("\n[トラブルシューティングのヒント]")
    print("1. IAMユーザーに 'AmazonBedrockFullAccess' ポリシーがアタッチされていますか？")
    print(f"2. 'aws configure' で設定したリージョンは '{TARGET_REGION}' になっていますか？")
    print("3. 'aws sts get-caller-identity' コマンドは正常に実行できますか？")
    print("4. (次項) Bedrockの「モデルアクセス」は有効化されていますか？")
```


リスト2-1
```Python
def lambda_handler(event, context):
    print(event)
    return 'Hello from Lambda!'
```




リスト2-2
```Python
import json


def lambda_handler(event, context):
    # TODO implement
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
    }
```


リスト2-3
```Python
import json


def get_dummy_weather(location):
    """
    指定された場所に基づいて、ダミーの天気情報を生成するヘルパー関数
    """
    print(f"場所 '{location}' のダミー天気を生成します。")
    
    # 本来はここで外部の天気APIを呼び出しますが、
    # 本書では、常に決まった情報を返すダミー処理を用意します。
    
    if "東京" in location:
        return {
            "location": location,
            "weather": "晴れ時々曇り",
            "max_temp": 28,
            "min_temp": 20,
            "comment": "東京は日差しが強く、暑い一日になりそうです。"
        }
    elif "大阪" in location:
        return {
            "location": location,
            "weather": "雨",
            "max_temp": 22,
            "min_temp": 18,
            "comment": "大阪は一日中雨が予想されます。傘を忘れずに。"
        }
    else:
        # 上記以外の場所の場合
        return {
            "location": location,
            "weather": "晴れ",
            "max_temp": 25,
            "min_temp": 17,
            "comment": f"{location} は過ごしやすい天気でしょう。"
        }
```


リスト2-4
```Python
def lambda_handler(event, context):
    """
    Bedrockエージェントから呼び出されるメインの関数
    """
    
    # エージェントからの入力をデバッグ用にログ出力
    print(f"受け取ったイベント (event): {json.dumps(event)}")
    
    # エージェントが渡すパラメータを解析する
    location = "不明な場所" # デフォルト値
    
    try:
        # エージェントは 'input' の中の 'parameters' リストで引数を渡す
        # parameters は [{'name': 'location', 'value': '東京'}, ...] のような形式
        
        parameters = event.get('input', {}).get('parameters', [])
        
        for param in parameters:
            if param.get('name') == 'location':
                location = param.get('value')
                break # location が見つかったらループを抜ける
                
        print(f"解析された場所 (location): {location}")


    except Exception as e:
        print(f"パラメータの解析中にエラーが発生しました: {e}")


    # 取得した location を使って、天気情報を取得する
    weather_data = get_dummy_weather(location)
    
    # エージェントに返す応答（レスポンス）を作成する
    # この応答形式はBedrockエージェント=Lambda間の基本仕様
    
  # レスポンスの本体
    response = {
        'response': {
            'actionGroup': event['actionGroup'],
            'function': event['function'],
            'functionResponse': {
                'responseBody': {
                    'TEXT': {'body': json.dumps(weather_data)}
                }
            }
        },
        'messageVersion': event.get('messageVersion', 1)
    }


    print(f"エージェントへの応答 (response): {json.dumps(response)}")


    return response
```


リスト2-5
```JSON
{
  "actionGroup": "get_weather",
  "function": "get_weather_function",
  "input": {
    "parameters": [
      {
        "name": "location",
        "value": "東京"
      }
    ]
  }
}
```


リスト2-6
```JSON
Status: Succeeded
Test Event Name: SampleEvent


Response:
{
  "response": {
    "actionGroup": "get_weather",
    "function": "get_weather_function",
    "functionResponse": {
      "responseBody": {
        "TEXT": {
          "body": "{"location": "東京", "weather": "晴れ時々曇り", "max_temp": 28, "min_temp": 20, 
          "comment": "東京は日差しが強く、暑い一日になりそうです。"}"
        }
      }
    }
  },
  "messageVersion": 1
}


Function Logs:
START RequestId: 3756515c-20fc-4818-9b31-6f7abd909f8c Version: $LATEST
受け取ったイベント (event): {
  "actionGroup": "get_weather", 
  "function": "get_weather_function", 
  "input": {
    "parameters": [
      {"name": "location", "value": "東京"}
    ]
  }
}


解析された場所 (location): 東京
場所 '東京' のダミー天気を生成します。


エージェントへの応答 (response): {
  "response": {
    "actionGroup": "get_weather", 
    "function": "get_weather_function", 
    "functionResponse": {
      "responseBody": {
        "TEXT": {
          "body": "{"location": "東京", "weather": "晴れ時々曇り", "max_temp": 28, "min_temp": 20, "comment": "東京は日差しが強く、暑い一日になりそうです。"}"
        }
      }
    }
  }, 
  "messageVersion": 1
}


END RequestId: 3756515c-20fc-4818-9b31-6f7abd909f8c
REPORT RequestId: 3756515c-20fc-4818-9b31-6f7abd909f8c        Duration: 7.68 ms        Billed Duration: 8 ms        Memory Size: 128 MB        Max Memory Used: 34 MB


Request ID: 3756515c-20fc-4818-9b31-6f7abd909f8c
```




リスト2-7
```JSON
"parameters": [
  {
    "name": "location",
    "value": "千葉"
  }
]
```


リスト2-8
```JSON
Response:
{
  "response": {
    "actionGroup": "get_weather",
    "function": "get_weather_function",
    "functionResponse": {
      "responseBody": {
        "TEXT": {
          "body":"{"location": "千葉", "weather": "晴れ", "max_temp": 25, "min_temp": 17, "comment": "千葉は過ごしやすい天気でしょう。"}"
        }
      }
    }
  },
  "messageVersion": 1
}
```




リスト2-9
```Python
import json
import urllib.request # 外部API(Web)を呼び出すための標準ライブラリ
import urllib.parse   # URLの文字列を安全に組み立てるための標準ライブラリ


def convert_weather_code(code):
    """
    Open-Meteo の WMO 天気コード（数値）を、
    人間が理解できる日本語の天気に変換するヘルパー関数
    """
    code_map = {
        0: "快晴",
        1: "晴れ",
        2: "ところにより曇り",
        3: "曇り",
        45: "霧",
        48: "霧氷",
        51: "弱い霧雨",
        53: "霧雨",
        55: "強い霧雨",
        56: "弱い着氷性の霧雨",
        57: "着氷性の霧雨",
        61: "弱い雨",
        63: "雨",
        65: "強い雨",
        66: "弱い着氷性の雨",
        67: "着氷性の雨",
        71: "弱い雪",
        73: "雪",
        75: "強い雪",
        77: "にわか雪",
        80: "弱いにわか雨",
        81: "にわか雨",
        82: "強いにわか雨",
        85: "弱いにわか雪",
        86: "にわか雪",
        95: "雷雨",
        96: "弱い雹を伴う雷雨",
        99: "雹を伴う雷雨"
    }
    # 辞書に存在しないコードの場合は「不明な天気(コード: xx)」と返す
    return code_map.get(code, f"不明な天気(コード: {code})")


def get_real_weather(location):
    """
    Open-Meteo API を使って、指定された場所の実際の天気情報を取得する
    """
    print(f"場所 '{location}' の実際の天気を Open-Meteo で検索します。")
    
    try:
        # Step 1: Geocoding APIで都市名から緯度・経度を取得
        
        # APIのエンドポイント（URL）
        geo_api_url = "https://geocoding-api.open-meteo.com/v1/search"
        
        # APIに渡すパラメータ（辞書）
        # name=場所, count=1(結果1件), language=ja(日本語), format=json
        geo_params = {
            'name': location,
            'count': 1,
            'language': 'ja',
            'format': 'json'
        }
        
        # パラメータをURLにくっつけられる形式に変換（URLエンコード）
        # 例: {'name': '東京'} -> 'name=%E6%9D%B1%E4%BA%AC'
        query_string = urllib.parse.urlencode(geo_params)
        
        # 最終的なURLを組み立て
        full_geo_url = f"{geo_api_url}?{query_string}"
        print(f"Geocoding API 呼び出しURL: {full_geo_url}")


        with urllib.request.urlopen(full_geo_url) as response:
            geo_data = json.load(response) # 返ってきたJSONデータをPythonの辞書に変換
        
        # 緯度・経度の取得
        if 'results' not in geo_data or len(geo_data['results']) == 0:
            print(f"Geocoding API で '{location}' が見つかりませんでした。")
            return {"error": f"'{location}' という場所が見つかりませんでした。"}
            
        geo_result = geo_data['results'][0]
        latitude = geo_result['latitude']
        longitude = geo_result['longitude']
        found_location_name = geo_result.get('name', location) # 見つかった正式名称
        
        print(f"'{location}' の緯度・経度を取得しました: ({latitude}, {longitude})")


        # Step 2: Weather Forecast APIで、緯度・経度から天気を取得
        
        forecast_api_url = "https://api.open-meteo.com/v1/forecast"
        
        # APIに渡すパラメータ
        forecast_params = {
            'latitude': latitude,
            'longitude': longitude,
            'current_weather': 'true', # 「現在の天気」を取得
            'daily': 'weathercode,temperature_2m_max,temperature_2m_min', # 「今日の天気コード、最高気温、最低気温」を取得
            'timezone': 'Asia/Tokyo', # タイムゾーンを東京に指定
            'forecast_days': 1 # 予報は1日分（今日）のみ
        }
        
        query_string = urllib.parse.urlencode(forecast_params)
        full_forecast_url = f"{forecast_api_url}?{query_string}"
        print(f"Forecast API 呼び出しURL: {full_forecast_url}")
        
        with urllib.request.urlopen(full_forecast_url) as response:
            forecast_data = json.load(response)


        # Step 3: 結果を整形する
        
        current = forecast_data['current_weather']
        daily = forecast_data['daily']
        
        # 天気コード（数値）を日本語（文字列）に変換
        current_weather_text = convert_weather_code(current['weathercode'])
        
        # 戻り値の辞書を作成
        weather_info = {
            "location": found_location_name, # APIが見つけた正式な場所名
            "weather": f"{current_weather_text} (現在 {current['temperature']} °C)",
            "max_temp": daily['temperature_2m_max'][0], # 今日のデータ
            "min_temp": daily['temperature_2m_min'][0], #今日のデータ
            "comment": f"{found_location_name} の現在の天気は {current_weather_text}、気温 {current['temperature']} 度です。今日の最高気温は {daily['temperature_2m_max'][0]} 度、最低気温は {daily['temperature_2m_min'][0]} 度の予報です。"
        }
        
        print(f"天気情報の取得成功: {weather_info}")
        return weather_info


    except urllib.error.URLError as e:
        print(f"API呼び出し中にネットワークエラーが発生しました: {e}")
        return {"error": "天気情報の取得中にネットワークエラーが発生しました。"}
    except Exception as e:
        print(f"天気情報の処理中に予期せぬエラーが発生しました: {e}")
        return {"error": f"天気情報の処理中にエラーが発生しました ({e})。"}


def lambda_handler(event, context):
    """
    Bedrockエージェントから呼び出されるメインの関数
    """
    
    # エージェントからの入力をデバッグ用にログ出力
    print(f"受け取ったイベント (event): {json.dumps(event)}")
    
    # エージェントが渡すパラメータを解析する
    location = "不明な場所" # デフォルト値
    
    try:
        # エージェントは 'input' の中の 'parameters' リストで引数を渡す
        # parameters は [{'name': 'location', 'value': 'Tokyo'}] の形式
        
        parameters = event.get('input', {}).get('parameters', [])
        
        for param in parameters:
            if param.get('name') == 'location':
                location = param.get('value')
                break # location が見つかったらループを抜ける
                
        print(f"解析された場所 (location): {location}")


    except Exception as e:
        print(f"パラメータの解析中にエラーが発生しました: {e}")


    # 取得した location を使って、天気情報を取得する
    weather_data = get_real_weather(location)
    
    # エージェントに返す応答（レスポンス）を作成する
    # この応答形式はBedrockエージェント=Lambda間の基本仕様
    
    # レスポンスの本体
    response = {
        'response': {
            'actionGroup': event['actionGroup'],
            'function': event['function'],
            'functionResponse': {
                'responseBody': {
                    'TEXT': {'body': json.dumps(weather_data)}
                }
            }
        },
        'messageVersion': event.get('messageVersion', 1)
    }


    print(f"エージェントへの応答 (response): {json.dumps(response)}")


    return response
 ```


リスト2-10
```NONE
指定された場所(location)の現在の天気予報、最高気温、最低気温、コメントを取得します。ユーザーが天気について尋ねた場合にのみ使用してください。


+ アクションget_weatherには、get_weather({"location": "{都市名}"}) という形でアクセスされます。{都市名}には、都市名をローマ字表記にしたテキストが入ります。
+ get_weather_functionには、get_weatherの引数にあるlocationの都市名を使い、{"location": "{都市名}"} という形で情報を渡します。
+ Lambda関数のget_weeather_functionに送信する正確な情報は、以下のようになります（都市名が Chiba の場合）。
```json
{
  "actionGroup": "get_weather",
  "function": "get_weather_function",
  "input": {
    "parameters": [
      {
        "name": "location",
        "value": "Chiba"
      }
    ]
  }
}
```
```


リスト2-11
```
世界の天気に関する豆知識集


[ロンドン]
イギリスの首都であるロンドンは、年間を通して「天気が変わりやすく、雨が多い」ことで世界的に知られています。
地元では「1日の中に四季がある」と言われるほどで、晴れていたかと思うと急に雨が降ることも珍しくありません。
観光の際は、折りたたみ傘やレインコートが必須アイテムです。


[カイロ]
エジプトの首都カイロは、典型的な「砂漠気候（さばくきこう）」です。
夏（5月から9月）は非常に暑く、気温が40度を超えることもあります。
雨はほとんど降らず、年間降水量は非常に少ないのが特徴です。
訪問する際は、日差しを遮る帽子やサングラス、十分な水分補給が欠かせません。


[シドニー]
オーストラリアのシドニーは、南半球に位置しています。
そのため、日本や北半球の国々とは「季節が真逆」になります。
日本が冬の12月〜2月は、シドニーでは夏となり、ビーチが最も賑わう季節です。
逆に日本が夏の7月〜8月は、シドニーでは冬にあたります。
...以下略...
```




リスト2-12
```Python
import boto3
import json
import uuid


# 設定が必要な項目


# 1. リージョン名
#    エージェントを作成したリージョン (例: 'us-east-1')
TARGET_REGION = 'us-east-1' 


# 2. エージェントID (Agent ID)
#    Bedrockコンソールの MyFirstAgent 概要ページで確認
#    例: 'ABC123DEF4'
AGENT_ID = 'YOUR_AGENT_ID'  # エージェントIDを指定


# 3. エージェント・エイリアスID (Agent Alias ID)
#    概要ページ、または「Aliases」タブで確認
AGENT_ALIAS_ID = 'YOUR_AGENT_ALIAS_ID' # エイリアスIDを指定


# 設定ここまで


def chat_with_agent(client, agent_id, alias_id, session_id, prompt_text):
    """
    Bedrockエージェントと対話し、応答をストリーミングで受け取る関数
    """
    
    print(f"\n[ユーザー]: {prompt_text}")
    print("[エージェント]: ", end="", flush=True)
    
    try:
        # エージェントを呼び出す (InvokeAgent)
        response = client.invoke_agent(
            agentId=agent_id,
            agentAliasId=alias_id,
            sessionId=session_id,
            inputText=prompt_text,
            enableTrace=False # トレース情報が不要な場合はFalse
        )
        
        full_response = ""
        
        # エージェントの応答は「ストリーミング」形式で返ってくる
        if 'completion' in response:
            for event in response['completion']:
                if 'chunk' in event:
                    # 'chunk' にAIの回答の「断片」が bytes 形式で入っている
                    chunk = event['chunk']
                    decoded_chunk = chunk['bytes'].decode('utf-8')
                    
                    # 断片をコンソールに即時出力 (ストリーミング表示)
                    print(decoded_chunk, end="", flush=True)
                    
                    full_response += decoded_chunk
        
        print() # 最後に改行
        return full_response


    except Exception as e:
        print(f"\n[エラー]: {e}")
        return None


def main():
    """
    メインの実行関数
    """
    # AGENT_ID と AGENT_ALIAS_ID が設定されているかチェック
    if AGENT_ID == 'YOUR_AGENT_ID' or \
          AGENT_ALIAS_ID == 'YOUR_AGENT_ALIAS_ID':
        print("[エラー] AGENT_ID と AGENT_ALIAS_ID を、")
        print("        Bedrockコンソールで確認した値に書き換えてください。")
        return


    # Bedrockエージェントの「実行(Runtime)」用クライアントを作成
    try:
        client = boto3.client(
            'bedrock-agent-runtime', 
            region_name=TARGET_REGION
        )
    except Exception as e:
        print(f"[エラー] Boto3クライアントの作成に失敗しました: {e}")
        print("AWSの認証情報が正しく設定されているか確認してください。")
        return


    # セッションID (Session ID)
    # 会話の履歴を管理するためのID。
    # このIDが同じである限り、エージェントは過去の会話を記憶します。
    session_id = str(uuid.uuid4())
    print(f"セッションID: {session_id} でエージェントとの会話を開始します。")
    print("終了するには 'exit' または 'quit' と入力してください。")


    # 対話ループ
    while True:
        try:
            user_input = input("\n[ユーザー]: ")
            if user_input.lower() in ['exit', 'quit']:
                print("会話を終了します。")
                break
            
            chat_with_agent(client, AGENT_ID, AGENT_ALIAS_ID, session_id, user_input)
            
        except KeyboardInterrupt:
            print("\n会話を中断しました。")
            break


# このファイルが直接実行された時だけ main() を呼び出す
if __name__ == "__main__":
    main()
```


リスト3-1
```Python
from bedrock_agentcore.runtime import BedrockAgentCoreApp


app = BedrockAgentCoreApp()


@app.entrypoint
def invoke(payload):
    """Process user input and return a response"""
    user_message = payload.get("prompt", "Hello")
    return {"result": user_message}


if __name__ == "__main__":
    app.run()
```


※curlコマンド
```Bash
curl -X POST http://localhost:8080/invocations -H "Content-Type: application/json" -d '{"prompt": "こんにちは、ローカルエージェント！"}'
```
 これを実行すると、以下のような表示がされるでしょう。
```JSON
{"result": "こんにちは、ローカルエージェント！"}
```


リスト3-2
```Python
import sys
import json
from bedrock_agentcore.runtime import BedrockAgentCoreApp


# アプリケーションのインスタンス作成
app = BedrockAgentCoreApp()


# エントリーポイント
@app.entrypoint
def invoke(payload):
    """
    BedrockAgentCoreApp がリクエストを受け取ったときに
    呼び出されるメインの関数。
    
    引数 (payload):
        リクエストの本体 (JSON)。
        boto3から呼ばれる場合、InvokeAgentのパラメータが入る。
        HTTP (curl) から呼ばれる場合、POSTされたJSONデータが入る。


    戻り値 (dict):
        エージェントの実行結果。
        この辞書がJSONに変換されてレスポンスとして返される。
    """
    
    print("\n" + "="*50)
    print("[サーバー] /invoke エンドポイントが呼び出されました。")
    print(f"[サーバー] 受け取ったペイロード: {payload}")


    # ペイロードから "prompt" キーの値を取得
    # もし "prompt" キーが存在しなければ、"Hello" をデフォルト値として使用
    user_message = payload.get("prompt", "Hello")
    
    # "オウム返し" のレスポンスを作成
    response_data = {
        "result": f"オウム返し: {user_message}"
    }
    
    print(f"[サーバー] 以下のレスポンスを返します: {response_data}")
    print("="*50 + "\n")


    # レスポンス（辞書）を返す
    return response_data


# サーバーの実行
if __name__ == "__main__":
    """
    このファイル (agent_server2.py) が直接実行された場合にのみ、
    以下の処理（サーバー起動）を行う。
    """
    print("[情報] BedrockAgentCoreApp ローカルサーバーを起動します...")
    print("[情報] デフォルトでは http://localhost:8080 で待機します。")
    print("[情報] 停止するには Ctrl+C を押してください。")
    
    try:
        # app.run() が、Webサーバーを起動し、
        # 外部からのリクエスト待機状態に入る
        app.run()
        
    except KeyboardInterrupt:
        print("\n[情報] サーバーが停止されました。")
    except Exception as e:
        print(f"\n[エラー] サーバーの起動に失敗しました: {e}", file=sys.stderr)
        sys.exit(1)
```


リスト3-3
```Python
import requests
import json
import sys


# 1. サーバーのエンドポイントURL
#    agent_server2.py が動いている場所
url = "http://localhost:8080/invocations"


# 2. 送信するリクエストヘッダー
headers = {
    "Content-Type": "application/json"
}


# 3. 送信するペイロード（辞書）
data = {
    "prompt": "今度は Python requests からハロー"
}


def call_local_server():
    print(f"[クライアント] サーバー ( {url} ) にリクエストを送信します...")
    print(f"[クライアント] ペイロード: {data}")


    try:
        # 4. requests.post でHTTP POSTリクエストを送信
        #    data=json.dumps(data) で辞書をJSON文字列に変換
        response = requests.post(
            url, 
            headers=headers, 
            data=json.dumps(data)
        )
        
        # 5. エラーチェック (4xx や 5xx のステータスコード)
        response.raise_for_status() 


        # 6. レスポンスの解析
        print("\n[クライアント] サーバーからのレスポンスを受信しました。")
        print(f"ステータスコード: {response.status_code}")
        
        # response.json() で、受信したJSON文字列をPython辞書に変換
        response_data = response.json()
        print(f"レスポンス本体 (辞書): {response_data}")
        
        # "result" キーを取り出して表示
        print(f"\n  >> エージェントの回答: {response_data.get('result')}")


    except requests.exceptions.ConnectionError as e:
        print(f"\n[エラー] サーバーへの接続に失敗しました。", file=sys.stderr)
        print(f"{url} が起動しているか（agent_server2.pyは実行中か）確認してください。", file=sys.stderr)
        # print(f"詳細: {e}", file=sys.stderr)
    except requests.exceptions.HTTPError as e:
        print(f"\n[エラー] HTTPエラーが発生しました（例: 404 Not Found, 500 Internal Server Error）。", file=sys.stderr)
        print(f"詳細: {e}", file=sys.stderr)
    except requests.exceptions.JSONDecodeError as e:
        print(f"\n[エラー] サーバーからの応答がJSON形式ではありませんでした。", file=sys.stderr)
        print(f"応答テキスト: {response.text[:200]}...", file=sys.stderr)
    except Exception as e:
        print(f"\n[エラー] 不明なエラーが発生しました: {e}", file=sys.stderr)


# --- メインの実行 ---
if __name__ == "__main__":
    call_local_server()
```


リスト3-4
```Python
import sys
import json
from bedrock_agentcore.runtime import BedrockAgentCoreApp
# strands のインポート
from strands import Agent


app = BedrockAgentCoreApp()


# 使用するAIモデル
agent_model = "anthropic.claude-3-5-haiku-20241022-v1:0"


# ★ strands.Agent の初期化
print("[情報] strands.Agent を初期化しています...")
try:
    # 1. AIの脳となるエージェントインスタンスを作成
    agent = Agent(
        # 2. 使用するモデルIDを指定
        #    ここではClaude 3.5 Haikuを指定
        model=agent_model          
    )
    print(f"[情報] Agent がモデル {agent.model} で初期化されました。")


except Exception as e:
    print(f"\n[エラー] strands.Agent の初期化に失敗しました。", file=sys.stderr)
    print(f"       詳細: {e}", file=sys.stderr)
    print("       (AWS認証情報が正しいか、Bedrockモデルアクセスが有効か確認してください)", file=sys.stderr)
    sys.exit(1)


@app.entrypoint
def invoke(payload):
    """
    リクエストを受け取り、strands (AI) で処理する関数
    """
    
    print("\n" + "="*50)
    print("[サーバー] /invoke エンドポイントが呼び出されました。")
    print(f"[サーバー] 受け取ったペイロード: {payload}")


    user_message = payload.get("prompt", "Hello! How can I help you today?")
    
    print(f"[サーバー] strands.Agent にプロンプトを渡します: '{user_message}'")
    
    try:
        # ★ strands.Agent の呼び出し
        # 3. AIに処理（推論）を依頼
        #    agent(...) は agent.invoke(...) のショートカット
        #    ここでAWS Bedrock (boto3) へのAPI呼び出しが発生
        result = agent(user_message)
        
        # 4. AIからの応答を取得
        #    result.message に、AIが生成した回答文字列が入る
        ai_response_text = result.message
        
        print(f"[サーバー] strands.Agent から応答を受信しました。")


        # 5. レスポンス辞書の作成
        response_data = {
            "result": ai_response_text
        }
        
    except Exception as e:
        # AWS認証エラー、モデルアクセス権限エラー、タイムアウト等
        print(f"\n[エラー] strands.Agent での処理中にエラーが発生しました: {e}", file=sys.stderr)
        # エラー発生時も、クライアントにはエラー情報を返す
        response_data = {
            "error": f"Agent processing error: {str(e)}"
        }


    print(f"[サーバー] 以下のレスポンスを返します: {response_data}")
    print("="*50 + "\n")


    return response_data


# --- サーバー実行 (agent_server2.py と同じ) ---
if __name__ == "__main__":
    print("[情報] BedrockAgentCoreApp (AIモード) ローカルサーバーを起動します...")
    print("[情報] http://localhost:8080 で待機します。")
    print("[情報] 停止するには Ctrl+C を押してください。")
    
    try:
        app.run()
    except KeyboardInterrupt:
        print("\n[情報] サーバーが停止されました。")
    except Exception as e:
        print(f"\n[エラー] サーバーの起動に失敗しました: {e}", file=sys.stderr)
        sys.exit(1)
```


※curlコマンド
```Bash
curl -X POST⏎
  http://localhost:8080/invocations -H ⏎
  "Content-Type: application/json"  ⏎
  -d '{"prompt": "こんにちは、自己紹介をしてください。"}'
```


リスト3-3 修正
```Python
def call_local_server():
    # ----- 追加した文 -----
    prompt = input("メッセージ: ")
    if prompt != "":
        data["prompt"] = prompt
    # ----- ここまで -----
    print(f"[クライアント] サーバー ( {url} ) にリクエストを送信します...")
    print(f"[クライアント] ペイロード: {data}")


# ...以下略...
```


※requirements.txt
```
strands-agents
bedrock-agentcore
strands-agents-tools
```


※エージェントへの送信データ
```JSON
{
  "input": "What's the weather like in Tokyo today?",
  "user_id": "12345",
  "context": {
    "timezone": "Asia/Tokyo",
    "language": "en",
  }
}
```


※エージェントからの応答
```JSON
{
  "input": "こんにちは。あなたは誰？",
  "user_id": "12345",
  "context": {}
}
```


リスト3-5
```Pytohn
import boto3
import json


client = boto3.client('bedrock-agentcore', region_name='us-east-1')


prompt = input("prompt: ")
payload = json.dumps({"prompt": prompt})


response = client.invoke_agent_runtime(
    agentRuntimeArn='arn:aws:bedrock-agentcore:us-east-1:<アカウントID>:runtime/agentcore_strands1-xxxx',
    runtimeSessionId='...ランダムな文字列...', 
    payload=payload,
    qualifier="DEFAULT" # Optional
)
response_body = response['response'].read()
response_data = json.loads(response_body)
print("Agent Response:", response_data)
```


リスト3-6
```Python
import sys
import json
import re
import random
from bedrock_agentcore.runtime import BedrockAgentCoreApp
from strands import Agent, tool


# -------------------------
# ツール定義
# -------------------------
@tool
def my_tool(city: str = "tokyo") -> dict:
    """
    指定都市の天気情報を返すツール。
    
    Args:
        city: str(都市名の文字列)


    Returns:
        {
            "city": str(都市名)
            "weather": str(天気)
            "max_temp": int(最高気温)
            "min_temp": int(最低気温)
        }
        
    """
    print(f"[ツール] my_tool が呼ばれました: {city}")


    # 天気のデータ
    weather_list = [
        '晴れ',
        '曇り',
        '雨',
        '雪',
        '晴れのち曇り',
        '曇のち雨',
        '曇のち雪',
        '大嵐!'
    ]
    
    result = {
        'city': city,
        'weather': random.choice(weather_list),
        'max_temp': random.randint(15, 35),
        'min_temp': random.randint(-5, 15)
    }
    return result  # AIに渡すので辞書形式でOK


# -------------------------
# AI プロンプト
# -------------------------
system_prompt = '''
あなたは天気情報を得意とするエージェントです。
ユーザーが天気情報を聞いてきたら、その質問文の中から都市名を受け取り、その都市の天気情報を提供します。
ただし、ツールの呼び出しはサーバー側で行います。
天気情報以外の質問、あるいは調べる都市名が不明の場合、一般的な質問としてツールを使わず、AIモデルが回答します。


※やり取りの例：
[ユーザー]: 東京の天気を教えて。
[アシスタント]: 東京の天気は、大嵐で最高気温15度、最低気温7度です。
ユーザー]: あなたは誰ですか？
[アシスタント]: 私は天気情報を得意とするエージェントです。天気に関する質問に回答できます。
'''
city_prompt = '''
<system message>
ユーザーから入力されたテキストを調べ、天気を知りたい場合、
知りたい都市名を取り出し、その都市名だけを返してください。
都市名がわからない場合は、「不明」と返してください。


※やり取りの例：
[ユーザー]: 東京の天気を教えて。
[アシスタント]: 東京
ユーザー]: あなたは誰ですか？
[アシスタント]: 不明
</system message>
'''


# -------------------------
# BedrockAgentCoreApp 初期化
# -------------------------
app = BedrockAgentCoreApp()


agent_model = "amazon.nova-lite-v1:0"


print("[情報] strands.Agent を初期化しています...")
try:
    agent = Agent(
        model=agent_model,
        tools=[my_tool]
    )
    print(f"[情報] Agent がモデル {agent_model} で初期化されました。")
except Exception as e:
    print(f"[エラー] strands.Agent 初期化失敗: {e}", file=sys.stderr)
    sys.exit(1)


# -------------------------
# エンドポイント
# -------------------------
@app.entrypoint
def invocations(payload):
    """
    /invoke でリクエストを受け取り、AI+ツールで処理
    """
    print("="*50)
    print("[サーバー] /invoke が呼ばれました")
    print(f"[サーバー] ペイロード: {payload}")


    user_message = payload.get("prompt", "")
    print(f"[サーバー] ユーザー入力: {user_message}")


    # -------------------------
    # AI に問い合わせ
    # -------------------------
    try:
        result = agent(system_prompt +city_prompt + user_message)
        # result.message は文字列応答
        ai_response = result.message
        response_data = {"result": user_message}


    except Exception as e:
        print(f"[エラー] Agent 処理中にエラー: {e}", file=sys.stderr)
        response_data = {"error": str(e)}


    print(f"[サーバー] レスポンス: {response_data}")
    return ai_response


# -------------------------
# サーバー起動
# -------------------------
if __name__ == "__main__":
    print("[情報] BedrockAgentCoreApp ローカルサーバーを起動します...")
    print("[情報] http://localhost:8080 で待機中")
    try:
        app.run()
    except KeyboardInterrupt:
        print("\n[情報] サーバー停止")
    except Exception as e:
        print(f"[エラー] サーバー起動失敗: {e}", file=sys.stderr)
        sys.exit(1)
```


リスト3-7
```Python
import requests
import json
import sys
import re


# 1. サーバーのエンドポイントURL
#    agent_server2.py が動いている場所
url = "http://localhost:8080/invocations"


# 2. 送信するリクエストヘッダー
headers = {
    "Content-Type": "application/json"
}


# 3. 送信するペイロード（辞書）
data = {
    "prompt": "Hello"
}


def call_local_server():
    prompt = input("メッセージ: ")
    if prompt != "":
        data["prompt"] = prompt
        
    print(f"[クライアント] サーバー ( {url} ) にリクエストを送信します...")
    print(f"[クライアント] ペイロード: {data}")


    try:
        # 4. requests.post でHTTP POSTリクエストを送信
        #    data=json.dumps(data) で辞書をJSON文字列に変換
        response = requests.post(
            url, 
            headers=headers, 
            data=json.dumps(data)
        )
        
        # 5. エラーチェック (4xx や 5xx のステータスコード)
        response.raise_for_status() 


        # 6. レスポンスの解析
        print("\n[クライアント] サーバーからのレスポンスを受信しました。")
        print(f"  ステータスコード: {response.status_code}")
        
        # response.json() で、受信したJSON文字列をPython辞書に変換
        response_data = response.json()
        # print(f"  レスポンス本体 (辞書): {response_data}")
        
        # "result" キーを取り出して表示
        result = response_data.get('content', [{}])[0].get('text', str(response_data))
        print(f"\n  >> エージェントの回答: {result}")


    except requests.exceptions.ConnectionError as e:
        print(f"\n[エラー] サーバーへの接続に失敗しました。", file=sys.stderr)
        print(f"{url} が起動しているか確認してください。", file=sys.stderr)
        # print(f"詳細: {e}", file=sys.stderr)
    except requests.exceptions.HTTPError as e:
        print(f"\n[エラー] HTTPエラーが発生しました。", file=sys.stderr)
        print(f"詳細: {e}", file=sys.stderr)
    except requests.exceptions.JSONDecodeError as e:
        print(f"\n[エラー] サ応答がJSON形式ではありません。", file=sys.stderr)
        print(f"応答テキスト: {response.text[:200]}...", file=sys.stderr)
    except Exception as e:
        print(f"\n[エラー] 不明なエラーが発生しました: {e}", file=sys.stderr)


# --- メインの実行 ---
if __name__ == "__main__":
    call_local_server()
```


リスト4-1
```Python
from mcp.server.fastmcp import FastMCP
from starlette.responses import JSONResponse


# FastMCPを使ってMCPサーバーのインスタンスを作成。
# stateless_http=True でHTTP通信をステートレスモードで利用。
mcp = FastMCP(host="0.0.0.0", stateless_http=True)


# @mcp.tool() デコレータを付けることで「ツール」として登録
@mcp.tool()
def add_numbers(a: int, b: int) -> int:
   """２つの数値を足し合わせます"""
   return a + b


@mcp.tool()
def multiply_numbers(a: int, b: int) -> int:
   """２つの数値を掛け合わせます"""
   return a * b


@mcp.tool()
def greet_user(name: str) -> str:
   """ユーザーに名前で挨拶します"""
   return f"Hello, {name}! Nice to meet you."


if __name__ == "__main__":
   # MCPサーバーを起動し、streamable-httpトランスポートで通信を待ち受ける
   # このファイルを実行すると、サーバーが起動する
   mcp.run(transport="streamable-http")
```


リスト4-2
```Python
import asyncio
from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client


async def main():
 mcp_url = "http://localhost:8000/mcp"
 headers = {}


 # streamablehttp_clientを使ってサーバーに接続します。
 async with streamablehttp_client(mcp_url, headers, timeout=120, terminate_on_close=False) as (
   read_stream,
   write_stream,
   _,
 ):
   # 接続ストリームからClientSessionを作成します。
   async with ClientSession(read_stream, write_stream) as session:
     await session.initialize()
     print("MCP Session Initialized. (セッション確立)")
    
     # session.list_tools()を呼び出し、サーバー上の全ツールを取得します。
     tool_result = await session.list_tools()
     print("\n--- 利用可能なツール一覧 ---")
     for tool in tool_result.tools:
       print(f"名前: {tool.name}, 説明: {tool.description}")
     print("--------------------------")


asyncio.run(main())
```


リスト4-3
```Python
import asyncio
import json
from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client


async def main():
 mcp_url = "http://localhost:8000/mcp"
 headers = {}


 async with streamablehttp_client(mcp_url, headers, timeout=120, terminate_on_close=False) as (
   read_stream,
   write_stream,
   _,
 ):
   async with ClientSession(read_stream, write_stream) as session:
     await session.initialize()
     print("MCP Session Initialized. (セッション確立)")


     # ツールを呼び出す例
     tool_name = "add_numbers" # 呼び出したいツールの名前
     tool_args = {
       "a": 10,
       "b": 5
     } # ツールに渡す引数（辞書形式）


     print(f"\n--- Calling Tool: '{tool_name}' with args: {tool_args} ---")
     try:
       # session.call_tool() でツールをリモート実行し、結果を受け取ります。
       tool_call_result = await session.call_tool(tool_name, tool_args)
      
       print(f"\n--- Tool Call Result ---")
       print(f"呼び出し結果: {tool_call_result.result}")
       print("------------------------")
     except Exception as e:
       print(f"Error calling tool '{tool_name}': {e}")


asyncio.run(main())
```


リスト4-4
```Python
import asyncio # 非同期処理を扱うための標準ライブラリ
import json # JSONデータのエンコード・デコードに使用
from mcp import ClientSession # MCPセッション管理のためのクラス
from mcp.client.streamable_http import streamablehttp_client # ストリーミングHTTPクライアント


# グローバル変数として、呼び出すツール名と引数を初期化
tool_name = '' 
tool_args = {}


def get_input():
    # グローバル変数を宣言、関数内で値を更新できるようにする
    global tool_name, tool_args
    # ユーザーに実行したいツールの番号を入力させる
    func_num = int(input('ツール番号(1:add, 2:multiply, 3:greet): '))


    # --- ツール1: 数値の加算 (add_numbers) ---
    def process_1():
        # グローバル変数を更新
        global tool_name, tool_args
        tool_name = 'add_numbers'
        # ユーザーから加算する2つの数値を取得
        a = int(input('a: '))
        b = int(input('b: '))
        # ツール引数を辞書として設定
        tool_args = {'a': a, 'b': b}


    # --- ツール2: 数値の乗算 (multiply_numbers) ---
    def process_2():
        # グローバル変数を更新
        global tool_name, tool_args
        tool_name = 'multiply_numbers'
        # ユーザーから乗算する2つの数値を取得
        a = int(input('a: '))
        b = int(input('b: '))
        # ツール引数を辞書として設定
        tool_args = {'a': a, 'b': b}


    # --- ツール3: ユーザーへの挨拶 (greet_user) ---
    def process_3():
        # グローバル変数を更新
        global tool_name, tool_args
        tool_name = 'greet_user'
        # ユーザーから名前を取得
        name = input('name: ')
        # ツール引数を辞書として設定
        tool_args = {'name': name}


    # 入力された番号に対応する関数を格納した辞書
    process_dict = {
        1: process_1,
        2: process_2,
        3: process_3
    }


    # 辞書から対応する関数を取得して実行
    process_dict.get(func_num, lambda: print("値は1, 2, 3以外です"))()


async def main():
    # get_input()で設定されたグローバル変数を使用
    global tool_name, tool_args
    # MCPサーバーのエンドポイントURL
    mcp_url = "http://localhost:8000/mcp"
    # HTTPヘッダー（今回は空）
    headers = {}


    # ストリーミングHTTPクライアントでサーバーと接続
    async with streamablehttp_client(
        mcp_url, 
        headers, 
        timeout=120, 
        terminate_on_close=False
    ) as (
        read_stream, # サーバーからのデータ読み込みストリーム
        write_stream, # サーバーへのデータ書き込みストリーム
        _, # 未使用の変数
    ):
        # 取得したストリームを使ってMCPセッションを開始
        async with ClientSession(read_stream, write_stream) as session:
            # セッションを初期化し、接続を確立
            await session.initialize()
            print("MCP Session Initialized. (セッション確立)")


            # ツールを呼び出す処理
            print(f"\n--- Calling Tool: '{tool_name}' with args: {tool_args} ---")
            try:
                # session.call_tool() でツールをリモート実行し、結果を受け取ります。
                tool_call_result = await session.call_tool(tool_name, tool_args)
            
                print(f"\n--- Tool Call Result ---")
                # ツール呼び出し結果から 'structuredContent' 内の 'result' を表示
                print(f"呼び出し結果: {tool_call_result.structuredContent['result']}")
                print("------------------------")
            except Exception as e:
                # ツール呼び出し中にエラーが発生した場合の処理
                print(f"Error calling tool '{tool_name}': {e}")


# ユーザーからの入力でツール名と引数を設定
get_input()
# 非同期ランタイムを開始し、mainコルーチンを実行
asyncio.run(main())
```


リスト4-5
```python
from bedrock_agentcore.memory import MemoryClient


client = MemoryClient(region_name="us-east-1")
memory = client.create_memory(
   name="CustomerSupportAgentMemory",
   description="Memory for customer support conversations",
)
print(f"Memory ID: {memory.get('id')}")
```


リスト4-6
```Python
from bedrock_agentcore.memory import MemoryClient


client = MemoryClient(region_name="us-east-1")


print("--------------------------------------------------------------------")


for memory in client.list_memories():
    print(f"Memory Arn: {memory.get('arn')}")
    print(f"Memory ID: {memory.get('id')}")
    print("--------------------------------------------------------------------")
```


リスト4-7
```Python
import sys
import json
from bedrock_agentcore.runtime import BedrockAgentCoreApp
# strands のインポート
from strands import Agent


# システムプロンプト
system_prompt = '''
あなたは顧客対応エージェントです。
ユーザーからの問い合わせに真摯に回答してください。
ユーザーから送られた情報はすべてユーザーのものです。
注文番号やユーザーの個人情報など、あなたが勝手に判断して回答を拒否しないでください。
すべてのユーザーからの情報をもとに、ユーザーの身になって回答してください。
'''


app = BedrockAgentCoreApp()


agent_model = "amazon.nova-lite-v1:0"


# ★ strands.Agent の初期化
print("[情報] strands.Agent を初期化しています...")
try:
    # 1. Aエージェントインスタンスを作成
    agent = Agent(
        # 2. 使用するモデルIDを指
        model= agent_model
    )
    print(f"[情報] Agentが {agent_model} で初期化されました。")


except Exception as e:
    print(f"\n[エラー] Agentの初期化に失敗しました。", file=sys.stderr)
    print(f"詳細: {e}", file=sys.stderr)
    print("認証情報またはBedrockモデルへのアクセスを確認ください。", file=sys.stderr)
    sys.exit(1)


@app.entrypoint
def invocations(payload):
    """
    リクエストを受け取り、strands (AI) で処理する関数
    """
    print("\n" + "="*50)


    user_message = payload.get("prompt", "Hello! How can I help you today?")
    
    print(f"[サーバー] strands.Agent にプロンプトを渡します: '{user_message}'")
    
    try:
        # ★ strands.Agent の呼び出し
        result = agent(system_prompt + '\n\n' + user_message)
        
        # AIからの応答を取得
        ai_response_text = result.message
        
        #print(f"[サーバー] strands.Agent から応答を受信しました。")


        # 5. レスポンス辞書の作成
        response_data = {
            "result": ai_response_text
        }
        
    except Exception as e:
        # AWS認証エラー、モデルアクセス権限エラー、タイムアウト等
        print(f"\n[エラー] strands.Agent での処理中にエラーが発生しました: {e}", file=sys.stderr)
        # エラー発生時も、クライアントにはエラー情報を返す
        response_data = {
            "error": f"Agent processing error: {str(e)}"
        }


    print(f"[サーバー] 以下のレスポンスを返します: {response_data}")
    print("="*50 + "\n")


    return response_data


# --- サーバー実行 (app_parrot.py と同じ) ---
if __name__ == "__main__":
    print("[情報] BedrockAgentCoreAppを起動します...")
    print("[情報] http://localhost:8080 で待機します。")
    print("[情報] 停止するには Ctrl+C を押してください。")
    
    try:
        app.run()
    except KeyboardInterrupt:
        print("\n[情報] サーバーが停止されました。")
    except Exception as e:
        print(f"\n[エラー] サーバーの起動に失敗しました: {e}", file=sys.stderr)
        sys.exit(1)
```


リスト4-8
```python
from bedrock_agentcore.memory import MemoryClient


client = MemoryClient(region_name="us-east-1")


memory = client.list_memories()[0] # 最初のメモリを取り出す


response = client.create_event(
    memory_id=memory.get("id"), # list_memoriesから得たメモリのID
    actor_id="User99",  # アクターのID（ここではユーザーを識別する）
    session_id="OrderSupportSession1", #リクエスト/会話のID。
    messages=[
        ("こんにちは。注文番号12345で問題が起こったのですが。", "USER"),
        ("申し訳ございません。ご注文を確認させていただきます。", "ASSISTANT"),
        ("lookup_order(order_id='12345')", "TOOL"),
        ("ご注文は3日前に発送されましたね。具体的にどのような問題が発生していますか？", "ASSISTANT"),
        ("実はその前にメールアドレスも変更したいのですが。", "USER"),
        (
            "もちろんです！まずはメールアドレスの更新を行いましょう。新しいメールアドレスを教えて下さい。",
            "ASSISTANT",
        ),
        ("newemail@example.com", "USER"),
        ("update_customer_email(old='old@example.com', new='newemail@example.com')", "TOOL"),
        ("メールが更新されました！さて、ご注文に関する問題についてお伺いします。", "ASSISTANT"),
        ("荷物が破損して届きました", "USER"),
    ],
)


print("Created event: ", response['eventId']) # イベントIDの表示
print("Event timestamp: ", response['eventTimestamp']) # 作成時刻の表示
``` 


リスト4-9
```Python
import boto3
import json
from bedrock_agentcore.memory import MemoryClient


memory = MemoryClient(region_name="us-east-1")


# 既存のメモリを取得（例示のための仮定）
# 実際の環境では、エラーハンドリングや適切なメモリIDの指定が必要です。
memory_id = 'agentcore_strands_simple_mem-xxxx' # メモリIDに修正
print(f'使用するメモリID: {memory_id}.')


# --- 最初のイベントの作成（ユーザーの元のコード） ---
print("最初のイベントを作成中...")


session_id = 'OrderSupportSession1-abcdefg1234567890' # セッションID
actor_id = 'User99' # アクタID


memory.create_event(
    memory_id=memory_id,
    actor_id=actor_id,
    session_id=session_id,
    messages=[
        ("こんにちは。注文番号12345で問題が起こったのですが。", "USER"),
        ("申し訳ございません。ご注文を確認させていただきます。", "ASSISTANT"),
        ("lookup_order(order_id='12345')", "TOOL"),
        ("ご注文は3日前に発送されましたね。具体的にどのような問題が発生していますか？", "ASSISTANT"),
        ("実はその前にメールアドレスも変更したいのですが。", "USER"),
        (
            "もちろんです！まずはメールアドレスの更新を行いましょう。新しいメールアドレスを教えて下さい。",
            "ASSISTANT",
        ),
        ("newemail@example.com", "USER"),
        ("update_customer_email(old='old@example.com', new='newemail@example.com')", "TOOL"),
        ("メールが更新されました！さて、ご注文に関する問題についてお伺いします。", "ASSISTANT"),
        ("荷物が破損して届きました", "USER"),
        ("大変申し訳ございません。お手数ですが商品をこちらにご返送いただけば返金の手続きをいたします。", "ASSISTANT")
    ],
)
print("最初のイベントがメモリに記録されました。")
print("---")


# ユーザーの新しい入力とその応答をシミュレートし、新しいイベントを作成


# ユーザーからの新しい入力
new_user_message = input("prompt: ")


# 短期記憶の取得
events = memory.list_events(
    memory_id=memory_id,
    actor_id=actor_id,
    session_id=session_id
)


# content を抽出
event_texts = []
event = events[0]
f = False
c = ['[USER]: ','[ASSISTANT]: ']
for ev in event['payload']:
    content = ev['conversational']['content']['text']
    event_texts.append(c[f] + content)
    f = not f
memory_text = "\n".join(event_texts)


prompt = f"""
以下は最近のやり取りです:
{memory_text}


これらの情報から回答してください。


[USER]: {new_user_message}
[ASSISTANT]: 
"""


# エージェントの作成
boto3_client = boto3.client('bedrock-agentcore', region_name='us-east-1')


# エージェントからの応答
new_assistant_response = boto3_client.invoke_agent_runtime(
    agentRuntimeArn='arn:aws:bedrock-agentcore:us-east-1:<ユーザーID>:runtime/agentcore_strands_simple-xxxx',
    runtimeSessionId=session_id, 
    payload=json.dumps({"prompt": prompt}),
    qualifier="DEFAULT"
)
response_body = new_assistant_response['response'].read()
response_data = json.loads(response_body)
response_text = response_data['result']['content'][0]['text']


print(f"ユーザー入力: {new_user_message}")
print(f"エージェント応答: {response_text}")
```


リスト4-10
```Python
import time
from bedrock_agentcore.memory import MemoryClient


client = MemoryClient(region_name="us-east-1")


memory_id = 'longterm_mem'


memory = client.create_memory(
    name=memory_id,
    strategies=[{
        "userPreferenceMemoryStrategy": {
            "name": "UserPreference",
            "namespaces": ["/users/{actorId}"]
        }
    }]
)
```


リスト4-11
```Python
import sys
import json
from bedrock_agentcore.runtime import BedrockAgentCoreApp
from strands import tool, Agent
from strands_tools.agent_core_memory import AgentCoreMemoryToolProvider


memory_id = 'longterm_mem-xxxx' # メモリIDを変更
agent_model = "amazon.nova-lite-v1:0"


session_id = 'PersonalSession1-abcdefg1234567890'
actor_id = 'User100'


app = BedrockAgentCoreApp()


# メモリの設定
# どのメモリを使うか、
strands_provider = AgentCoreMemoryToolProvider(
    memory_id=memory_id,
    actor_id=actor_id,
    session_id=session_id,
    namespace="/users/samplePerson",
    region="us-east-1"
)


agent_model = "amazon.nova-lite-v1:0"


# strands.Agent の初期化
print("[情報] strands.Agent を初期化しています...")


system_prompt = """
あなたはアクセスしたユーザーに特化したエージェントです。
記憶しているユーザーとのやり取りを元に回答をします。
ユーザーのメッセージはagent_core_memoryのrecordを使って記録します。
agent_core_memoryのretrievで関連するユーザー情報を取り出し利用します。
"""


# 必須IDの準備
memory_id = 'longterm_mem'
agent_model = "amazon.nova-lite-v1:0"
session_id = 'PersonalSession1-abcdefg1234567890'
actor_id = 'User100'


# エージェントの作成
agent = Agent(
    model=agent_model,
    system_prompt=system_prompt,
    tools=strands_provider.tools
)


@app.entrypoint
def invocations(payload):
    """
    リクエストを受け取り、strands (AI) で処理する関数
    """
    print("\n" + "="*50)


    user_message = payload.get("prompt", "Hello! How can I help you today?")
    
    print(f"[サーバー] strands.Agent にプロンプトを渡します: '{user_message}'")
    
    try:
        # strands.Agent の呼び出し
        result = agent(user_message)
        
        # AIからの応答を取得
        ai_response_text = result.message
        
        # レスポンス辞書の作成
        response_data = {
            "result": ai_response_text
        }
        
    except Exception as e:
        # AWS認証エラー、モデルアクセス権限エラー、タイムアウト等
        print(f"\n[エラー] strands.Agent での処理中にエラーが発生しました: {e}", file=sys.stderr)
        response_data = {
            "error": f"Agent processing error: {str(e)}"
        }
    print("="*50 + "\n")


    return response_data


# サーバー実行
if __name__ == "__main__":
    print("[情報] BedrockAgentCoreAppを起動します...")
    print("[情報] http://localhost:8080 で待機します。")
    print("[情報] 停止するには Ctrl+C を押してください。")
    
    try:
        app.run()
    except KeyboardInterrupt:
        print("\n[情報] サーバーが停止されました。")
    except Exception as e:
        print(f"\n[エラー] サーバーの起動に失敗しました: {e}", file=sys.stderr)
        sys.exit(1)
```


リスト4-12
```Python
import boto3
import json


prompt = input('prompt: ')
client = boto3.client('bedrock-agentcore', region_name='us-east-1')
payload = json.dumps({"prompt": prompt})


response = client.invoke_agent_runtime(
    agentRuntimeArn='arn:aws:bedrock-agentcore:us-east-1:<ユーザーID>:runtime/agent_longerm-xxxx',
    runtimeSessionId=' ランダムな文字列を指定 ',
    payload=payload,
    qualifier="DEFAULT"
)
response_body = response['response'].read()
response_data = json.loads(response_body)
print("Agent Response:", response_data)
```


リスト4-13
```Pythonfrom
bedrock_agentcore.tools.code_interpreter_client import CodeInterpreter
import json


# Configureクライアントを作成し利用開始する
code_client = CodeInterpreter('us-east-1')
code_client.start()


# コードを実行する
response = code_client.invoke("executeCode", {
  "language": "python", 
  "code": 'print("Hello World!!!")'
})


# 応答を処理し出力する
for event in response["stream"]:
  print(json.dumps(event["result"], indent=2))


# クライアントを停止する 
code_client.stop()
```


リスト4-14
```Python
import boto3
import json


client = boto3.client('bedrock-agentcore', region_name='us-east-1')


response = client.invoke_code_interpreter(
    codeInterpreterIdentifier='aws.codeinterpreter.v1',
    name='executeCode',
    arguments={
        'code': '''
print("Hello, world!")
total = 0
for i in range(1,101):
    total = total + i
print(f'total: {total}.')
        ''',
        'language': 'python'
    }
)


print("=== Code Interpreter Output ===")


for event in response['stream']:
    # event は以下のような辞書になる
    print(event['result']['content'][0]['text'])


    if "error" in event:
        # 実行時エラー
        print("[ERROR]", event["error"])
```


リスト5-1
```Python
from bedrock_agentcore.runtime import BedrockAgentCoreApp
from langchain.agents import create_agent
from langchain_core.tools import tool
from langchain_anthropic import ChatAnthropic
import os


# 環境変数から読み込む
anthropic_api_key = os.getenv("ANTHROPIC_API_KEY")
if not anthropic_api_key:
    raise ValueError("ANTHROPIC_API_KEY 環境変数が設定されていません。")


# モデル初期化
llm = ChatAnthropic(
    model="claude-3-5-haiku-latest",
    temperature=0,
    api_key=anthropic_api_key
)


@tool
def get_weather(city: str) -> str:
    # 実運用ではここで外部 API を叩く
    return f"It's always sunny in {city}!"


tools = [get_weather]
agent = create_agent(llm, tools)
app = BedrockAgentCoreApp()


@app.entrypoint
def invoke(payload):
    location = payload.get("prompt", "tokyo")


    try:
        result = agent.invoke(
            {"messages": [{"role": "user", "content": f"what is the weather in {location}"}]}
        )
    except Exception as e:
        return {"error": f"Agent invocation failed: {e}"}


    # result の構造を安全に扱う
    messages = result.get("messages") if isinstance(result, dict) else None
    if not messages:
        return {"error": "Agent returned no messages."}


    last_msg = messages[-1]
    content = getattr(last_msg, "content", None) or last_msg.get("content")
    return {"result": content}


if __name__ == "__main__":
    app.run()
```




リスト5-2
```Python
from typing import TypedDict, Annotated
import operator


# Annotatedとoperator.addを使うと、
# このキーが更新されたとき、リストに追加します。
class AgentState(TypedDict):
    # メッセージ情報
    messages: Annotated[list, operator.add]
    # 中間ステップの結果
    intermediate_steps: Annotated[list, operator.add]
    # 取得したデータ
    user_input: str
```


リスト5-3
```Python
import os
import json
import operator
from typing import TypedDict, Annotated, List, Union
from langchain_core.messages import AnyMessage, SystemMessage, HumanMessage, ToolMessage
from langchain_core.tools import tool
from langchain_aws import ChatBedrock
from langgraph.graph import StateGraph, END
from langchain.agents import create_agent


# --- Bedrock (Claude 3) モデルのセットアップ ---
# Bedrockのクライアントを初期化
# ここでは Claude 3 haikuを使用します
model = ChatBedrock(
    model_id="anthropic.claude-3-haiku-20240307-v1:0", # 使用するモデル
    model_kwargs={"temperature": 0.1},
)


# ツールの定義


@tool
def get_current_datetime() -> str:
    """現在の日時をISOフォーマットで取得します。"""
    import datetime
    return datetime.datetime.now().isoformat()


# ツールをリストにまとめる
tools = [get_current_datetime]


# モデルにツールを「バインド」して、LLMがツールの存在と使い方を
# 認識できるようにします。
model_with_tools = model.bind_tools(tools)


# 状態の定義


class AgentState(TypedDict):
    """
    エージェントの状態を定義します。
    'messages'キーは、新しいメッセージが追加されるたびにリストに蓄積されます。
    """
    messages: Annotated[List[AnyMessage], operator.add]


# ノードの定義


# 1. モデル呼び出しノード
def call_model(state: AgentState):
    """LLM（Bedrock）を呼び出すノード"""
    print("---[ノード] call_model 実行---")
    messages = state["messages"]
    
    # 状態（会話履歴）をそのままモデルに渡す
    response = model_with_tools.invoke(messages)
    
    # モデルの応答（AIMessage）を状態に追加する
    # operator.add が設定されているため、リストに追加される
    return {"messages": [response]}


# 2. ツール実行ノード
def call_tool(state: AgentState):
    """LLMが要求したツールを実行するノード"""
    print("---[ノード] call_tool 実行---")
    
    # 最後のメッセージ（AIからのツール呼び出し要求）を取得
    last_message = state["messages"][-1]
    
    # ツール呼び出し（tool_calls）があるかチェック
    if not last_message.tool_calls:
        # 本来ここには来ないはずだが、念のため
        print("エラー: ツール呼び出しがありません")
        return {}


    # ツールを実行し、結果をリストに格納
    tool_results = []
    tool_map = {t.name: t for t in tools} # ツール名で関数を引けるようにマップを作成


    for tool_call in last_message.tool_calls:
        tool_name = tool_call["name"]
        print(f"  > ツール '{tool_name}' を実行します")
        
        if tool_name in tool_map:
            try:
                # ツール（関数）を実行
                tool_output = tool_map[tool_name].invoke(tool_call["args"])
                
                # 結果を ToolMessage 形式で格納
                tool_results.append(
                    ToolMessage(
                        content=str(tool_output), 
                        tool_call_id=tool_call["id"]
                    )
                )
            except Exception as e:
                print(f"ツール実行エラー: {e}")
                tool_results.append(
                    ToolMessage(
                        content=f"Error: {e}", 
                        tool_call_id=tool_call["id"]
                    )
                )
        else:
            print(f"未定義のツール: {tool_name}")
            tool_results.append(
                ToolMessage(
                    content=f"Error: Tool '{tool_name}' not found.", 
                    tool_call_id=tool_call["id"]
                )
            )


    # ツール実行結果（ToolMessageのリスト）を状態に追加する
    return {"messages": tool_results}


# 条件分岐（ルーター）の定義


def should_continue(state):
    last = state["messages"][-1]
    if last.tool_calls:
        return "continue_to_tool"
    return END


# グラフの構築


print("グラフを構築します...")


workflow = StateGraph(AgentState)


# 1. ノードを登録
workflow.add_node("agent", call_model) # モデル呼び出しノード
workflow.add_node("action", call_tool) # ツール実行ノード


# 2. 開始点を設定
workflow.set_entry_point("agent") # 最初に 'agent' ノードから開始


# 3. 条件分岐エッジを設定
workflow.add_conditional_edges(
    "agent",
    should_continue,
    {
        "continue_to_tool": "action",
        END: END
    }
)


# 4. 通常のエッジを設定 (ループ)
# 'action' ノード（ツール実行）が終わったら、
# 必ず 'agent' ノード（モデル呼び出し）に戻る
workflow.add_edge("action", "agent")


# 5. グラフをコンパイル
app = workflow.compile()


print("グラフのコンパイルが完了しました。")


# エージェントの実行


if __name__ == "__main__":
    print("\n--- エージェント実行開始 ---")
    
    # 最初のユーザー入力
    input_str = input("prompt: ")
    inputs = {"messages": [HumanMessage(content=input_str )]}
    
    # app.stream() を使うと、各ステップ（ノード）の実行結果が順次得られる
    # config={"recursion_limit": 10} は、無限ループを防ぐための実行回数制限
    for output in app.stream(inputs, config={"recursion_limit": 10}):
        # output には、そのステップを終えた時点での「状態」がキーバリューで入る
        # (例: {'agent': {'messages': [...]}} )
        step_name = list(output.keys())[0]
        step_output = output[step_name]
        
        print(f"\n---[ステップ完了] {step_name} ---")
        if "messages" in step_output:
            # 最後のメッセージ（そのステップで追加されたメッセージ）を表示
            last_msg = step_output["messages"][-1]
            if isinstance(last_msg, ToolMessage):
                print(f"  > ツール結果: {last_msg.content}")
            else:
                print(f"  > AI応答/要求: {last_msg.content}")
                if last_msg.tool_calls:
                    print(f"    > ツール呼び出し要求: {last_msg.tool_calls}")


    print("\n--- エージェント実行終了 ---")
    
    # 最終的な状態（全履歴）を取得したい場合
    # final_state = app.invoke(inputs, config={"recursion_limit": 10})
    # print("\n--- 最終回答 ---")
    # print(final_state["messages"][-1].content)
```


リスト5-4
```Python
from crewai.tools import BaseTool
from typing import Type
from pydantic import BaseModel, Field




class MyCustomToolInput(BaseModel):
    """Input schema for MyCustomTool."""
    argument: str = Field(..., description="Description of the argument.")


class MyCustomTool(BaseTool):
    name: str = "Name of my tool"
    description: str = (
        "Clear description for what this tool is useful for, your agent will need this information to use it."
    )
    args_schema: Type[BaseModel] = MyCustomToolInput


    def _run(self, argument: str) -> str:
        # Implementation goes here
        return "this is an example of a tool output, ignore it and move along."
```


※user_preference.txt
```
User name is John Doe.
User is an AI Engineer.
User is interested in AI Agents.
User is based in San Francisco, California.
```


リスト5-5
```
[project]
name = "crew_app"
version = "0.1.0"
description = "crew_app using crewAI"
authors = [{ name = "Your Name", email = "you@example.com" }]
requires-python = ">=3.10,<3.14"
dependencies = [
    "crewai[tools]==1.5.0"
]


[project.scripts]
crew_app = "crew_app.main:run"
run_crew = "crew_app.main:run"
train = "crew_app.main:train"
replay = "crew_app.main:replay"
test = "crew_app.main:test"
run_with_trigger = "crew_app.main:run_with_trigger"


[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"


[tool.crewai]
type = "crew"
```


リスト5-6――agents.yaml
```
researcher:
  role: >
    {topic} Senior Data Researcher
  goal: >
    Uncover cutting-edge developments in {topic}
  backstory: >
    You're a seasoned researcher with a knack for uncovering the latest
    developments in {topic}. Known for your ability to find the most relevant
    information and present it in a clear and concise manner.


reporting_analyst:
  role: >
    {topic} Reporting Analyst
  goal: >
    Create detailed reports based on {topic} data analysis and research findings
  backstory: >
    You're a meticulous analyst with a keen eye for detail. You're known for
    your ability to turn complex data into clear and concise reports, making
    it easy for others to understand and act on the information you provide.
```




リスト5-7――tasks.yaml
```
research_task:
  description: >
    Conduct a thorough research about {topic}
    Make sure you find any interesting and relevant information given
    the current year is {current_year}.
  expected_output: >
    A list with 10 bullet points of the most relevant information about {topic}
  agent: researcher


reporting_task:
  description: >
    Review the context you got and expand each topic into a full section for a report.
    Make sure the report is detailed and contains any and all relevant information.
  expected_output: >
    A fully fledged report with the main topics, each with a full section of information.
    Formatted as markdown without '```'
  agent: reporting_analyst
```


リスト5-8――travel_report_crew.py
```Python
"""
CLIから都市名を受け取り、日本語でレポートを生成。
_geocodeで日本語名を英語に変換し、API検索が失敗しないようにする。
"""
# 必要なライブラリのインポート
from dataclasses import dataclass
from datetime import datetime
import requests # 外部APIへのHTTPリクエストに使用
from typing import Dict, Any, List, Optional
from bs4 import BeautifulSoup # (未使用だが元のコードに含まれていたためそのまま) HTML解析用
import sys # コマンドライン引数処理用
import json # JSONデータの処理用


# 【エージェントの定義】
# CrewAIにおける「ツール」または「エージェントが使用する機能」に相当するクラス群


@dataclass
class WeatherAgent:
    """Open-Meteo APIから天気情報を取得するエージェント"""
    base_url: str = "https://api.open-meteo.com/v1/forecast" # 天気予報APIのベースURL


    def fetch(self, lat: float, lon: float, timezone: str = "UTC") -> Dict[str, Any]:
        """指定された緯度・経度の天気情報を取得する"""
        try:
            # APIリクエストのパラメータを設定
            params = {
                "latitude": lat,
                "longitude": lon,
                "current_weather": True, # 現在の天気を取得
                "hourly": "temperature_2m,precipitation,weathercode", #気温 降水 天気コード取得
                "timezone": timezone, # タイムゾーン
            }
            # APIへGETリクエストを送信
            resp = requests.get(self.base_url, params=params, timeout=10)
            resp.raise_for_status() # HTTPエラーが発生した場合、例外を発生
            return resp.json() # 成功した場合、JSONレスポンスを返す
        except Exception as e:
            # 取得失敗時、空の辞書を返す
            print(f"WeatherAgent error: {e}")
            return {}


@dataclass
class WikiAgent:
    """Wikipedia APIから記事の要約を取得するエージェント"""
    base_url: str = "https://ja.wikipedia.org/api/rest_v1/page/summary/" # WikipediaのAPI
    headers = {"User-Agent": "Mozilla/5.0"} # リクエストのUser-Agent


    def fetch_summary(self, title: str) -> Dict[str, Any]:
        """指定されたタイトル（都市名など）のWikipedia要約を取得する"""
        try:
            safe_title = title.replace(" ", "_")
            # 特定の主要都市以外の場合、検索効率のために「県」を追加する
            if safe_title not in ['東京','京都','大阪','名古屋','北海道']:
                safe_title += '県'
            
            url = self.base_url + safe_title # リクエストURLを構築
            resp = requests.get(url, headers=self.headers, timeout=10)
            resp.raise_for_status()
            return resp.json()
        except Exception as e:
            # 取得失敗時、空の辞書を返す
            print(f"WikiAgent error: {e}")
            return {}


@dataclass
class PlacesAgent:
    """Hotpepper API を利用して指定都市の飲食店情報を取得するエージェント"""
    #実際にCrewAIを使用する場合、APIキーは環境変数等で管理すること
    hotpepper_key: str = '1234abcd...' # Hotpepper APIキー
    large_area_url: str = "http://webservice.recruit.co.jp/hotpepper/large_area/v1/"
    shop_search_url: str = "http://webservice.recruit.co.jp/hotpepper/gourmet/v1/"


    def get_area_code(self, city: str) -> Optional[str]:
        """都市名を含む large_area コードを Hotpepper API から取得する"""
        try:
            params = {"key": self.hotpepper_key, "format": "json"}
            # 大エリア一覧を取得
            resp = requests.get(self.large_area_url, params=params, timeout=10)
            resp.raise_for_status()
            data = resp.json()
            # 取得したエリア一覧から、都市名を含むエリアコードを検索
            for area in data.get("results", {}).get("large_area", []):
                if city in area.get("name", ""):
                    return area.get("code")
        except Exception as e:
            print(f"PlacesAgent area code error: {e}")
            pass
        return None


    def search(self, city: str, limit: int = 10) -> List[Dict[str, Any]]:
        """都市名に対応するエリアコードを使って飲食店情報を検索する"""
        area_code = self.get_area_code(city)
        if not area_code:
            return [] # エリアコードが取得できなければ空リストを返す
            
        try:
            # 飲食店検索のパラメータを設定
            params = {
                "key": self.hotpepper_key,
                "format": "json",
                "large_area": area_code, # 取得したエリアコードを使用
                "count": limit # 取得件数
            }
            # 飲食店検索APIへリクエストを送信
            resp = requests.get(self.shop_search_url, params=params, timeout=10)
            resp.raise_for_status()
            data = resp.json()
            
            shops = []
            # 必要な情報（店舗名とPC用URL）を抽出
            for shop in data.get("results", {}).get("shop", []):
                shops.append({
                    "title": shop.get("name"),
                    "url": shop.get("urls", {}).get("pc")
                })
            return shops
        except Exception as e:
            print(f"PlacesAgent search error: {e}")
            return []


@dataclass
class ReportAgent:
    """収集した情報を統合し、最終的なレポート（Markdown形式）を生成するエージェント"""


    def getWmoWeather(self, code: int):
      """"""
      wmo = {
          0: "晴れ", 1: "概ね晴れ", 2: "所により曇り",
          3: "曇り", 45: "霧", 48: "霧氷", 51: "霧雨",
          53: "霧雨", 55: "霧雨", 56: "着氷性の霧雨",
          57: "着氷性の霧雨", 61: "雨", 63: "雨", 65: "雨",
          66: "着氷性の雨", 67: "着氷性の雨",
          71: "雪", 73: "雪", 75: "雪", 77: "霧雪",
          80: "にわか雨", 81: "にわか雨", 82: "にわか雨",
          85: "にわか雪", 86: "にわか雪",
          95: "雷雨", 96: "雷雨", 99: "雷雨",
      }
      return wmo.get(code, '不明')


    def assemble(self, city: str, weather: Dict[str, Any], wiki: Dict[str, Any], places: List[Dict[str, Any]]) -> str:
        """収集したデータからMarkdown形式のレポートを作成する"""
        # レポートのヘッダー情報を作成
        lines = [f"# {city} のレポート", "", f"生成日時: {datetime.utcnow().isoformat()} UTC", ""]
        
        # --- 天気情報セクション ---
        lines.append("## 天気情報")
        cw = weather.get("current_weather")
        code = int(cw.get('weathercode', -1))
        
        lines.append(f"- 現在の天気: {self.getWmoWeather(code)}")
        lines.append(f"- 現在の気温: {cw.get('temperature', 'N/A')} °C")
        lines.append(f"- 風速: {cw.get('windspeed', 'N/A')} m/s")
        lines.append("")


        # --- Wikipedia情報セクション ---
        lines.append("## その場所について（Wikipedia）")
        title = wiki.get("title")
        extract = wiki.get("extract")
        if title and extract:
            lines.append(f"**{title}**")
            lines.append("")
            # 要約文が長すぎる場合、1200文字で切り詰める
            excerpt = extract[:1200] + ("..." if len(extract) > 1200 else "")
            lines.append(excerpt)
        else:
            lines.append("Wikipedia の要約が見つかりません。")
        lines.append("")


        # --- 飲食店情報セクション ---
        lines.append("## 飲食店情報 (Hotpepper の検索結果)")
        if places:
            for p in places:
                lines.append(f"- [{p.get('title', '不明')}]({p.get('url', '#')})")
        else:
            lines.append("見つかりませんでした。")


        return "\n".join(lines)


# 【Crewの定義】
# 複数のエージェント（機能）を連携させ、一連のタスクを管理・実行するクラス


class TravelReportCrew:
    """旅行レポート生成のためのタスクとエージェントを管理するクルー（Crew）クラス"""
    def __init__(self):
        # 各エージェントのインスタンス化
        self.weather_agent = WeatherAgent()
        self.wiki_agent = WikiAgent()
        self.places_agent = PlacesAgent()
        self.report_agent = ReportAgent()
        # 各タスクの結果を保持するための変数
        self._weather: Dict[str, Any] = {}
        self._wiki: Dict[str, Any] = {}
        self._places: List[Dict[str, Any]] = []


    def _geocode(self, city: str) -> Optional[Dict[str, Any]]:
        """都市名を緯度・経度に変換するジオコーディング処理"""
        # ジオコーディングAPIの引数に合わせるための日本語-英語変換マップ
        # 日本の全47都道府県の日本語名とその英語表記（ローマ字）をマッピングした辞書
        jp_to_en = {
            "北海道": "Hokkaido", "青森": "Aomori", "岩手": "Iwate",
            "宮城": "Miyagi", "秋田": "Akita", "山形": "Yamagata",
            "福島": "Fukushima", "茨城": "Ibaraki", "栃木": "Tochigi",
            "群馬": "Gunma", "埼玉": "Saitama", "千葉": "Chiba",
            "東京": "Tokyo", "神奈川": "Kanagawa", "新潟": "Niigata",
            "富山": "Toyama", "石川": "Ishikawa", "福井": "Fukui",
            "山梨": "Yamanashi", "長野": "Nagano", "岐阜": "Gifu",
            "静岡": "Shizuoka", "愛知": "Aichi", "三重": "Mie",
            "滋賀": "Shiga", "京都": "Kyoto", "大阪": "Osaka",
            "兵庫": "Hyogo", "奈良": "Nara", "和歌山": "Wakayama",
            "鳥取": "Tottori", "島根": "Shimane", "岡山": "Okayama",
            "広島": "Hiroshima", "山口": "Yamaguchi", "徳島": "Tokushima",
            "香川": "Kagawa", "愛媛": "Ehime", "高知": "Kochi",
            "福岡": "Fukuoka", "佐賀": "Saga", "長崎": "Nagasaki",
            "熊本": "Kumamoto", "大分": "Oita", "宮崎": "Miyazaki",
            "鹿児島": "Kagoshima", "沖縄": "Okinawa"
        }
        city_en = jp_to_en.get(city, city) # 変換マップにあれば英語名、なければそのまま都市名
        try:
            # Open-MeteoのジオコーディングAPIを使用
            resp = requests.get("https://geocoding-api.open-meteo.com/v1/search", params={"name": city_en}, timeout=10)
            resp.raise_for_status()
            data = resp.json()
            # 最初の検索結果を返す
            if data.get("results"):
                return data["results"][0]
        except Exception as e:
            print(f"Geocoding error: {e}")
            pass
        return None


    def fetch_weather_task(self, city: str) -> None:
        """天気情報を取得するタスク"""
        print("fetch_weather_task: 実行")
        loc = self._geocode(city) # ジオコーディングを実行
        if not loc:
            self._weather = {}
            print("fetch_weather_task: 失敗（ジオコーディングできず）")
            return
        # ジオコーディング結果を使って天気情報を取得し、結果を内部変数に保存
        self._weather = self.weather_agent.fetch(loc.get("latitude"), loc.get("longitude"), loc.get("timezone", "UTC"))
        print("fetch_weather_task: 終了")
        
    def fetch_wikipedia_task(self, city: str) -> None:
        """Wikipediaの要約を取得するタスク"""
        print("fetch_wikipedia_task: 実行")
        # WikiAgentを使用して要約を取得し、結果を内部変数に保存
        self._wiki = self.wiki_agent.fetch_summary(city)
        print("fetch_wikipedia_task: 終了")


    def fetch_places_task(self, city: str) -> None:
        """飲食店情報を取得するタスク"""
        print("fetch_places_task: 実行")
        # PlacesAgentを使用して飲食店情報を検索し、結果を内部変数に保存
        restaurants = self.places_agent.search(f"{city}", limit=10)
        self._places = restaurants
        print("fetch_places_task: 終了")


    def write_report_task(self, city: str, filename: str = "travel_report.md") -> None:
        """収集したデータからレポートを作成し、ファイルに書き出すタスク"""
        print("write_report_task: 実行")
        # ReportAgentを使用して最終レポート（Markdown文字列）を生成
        report_md = self.report_agent.assemble(city, self._weather, self._wiki, self._places)
        # ファイルへの書き出し
        with open(filename, "w", encoding="utf-8") as f:
            f.write(report_md)
        print("write_report_task: 終了")
        print("========== レポート結果 ==========")
        print(report_md)
        print("========== ここまで ==========\n")
      
    def run(self, city: str, output: str = "travel_report.md") -> str:
        """全てのタスクを実行するメインのシーケンス"""
        # 各タスクを順次実行（CrewAI本来は並列実行も可能）
        self.fetch_weather_task(city)
        self.fetch_wikipedia_task(city)
        self.fetch_places_task(city)
        self.write_report_task(city, output)
        print("Crew finished. Report saved to:", output)
        return output


# 【CLIからの実行】
# スクリプトが直接実行された場合の処理


if __name__ == "__main__":
    # コマンドライン引数のチェック
    if len(sys.argv) < 3 or sys.argv[1] != "run":
        print("Usage: python travel_report_crew.py run <都市名>")
        sys.exit(1)
        
    city_name = sys.argv[2] # 2番目の引数を都市名として取得
    
    # Crewのインスタンス化と実行
    crew = TravelReportCrew()
    crew.run(city=city_name)
```


リスト5-9――run_travel_crew.py
```Python
"""
travel_report_crew.py から TravelReportCrew を実行するためのCLIラッパー


使用例:
python run_travel_crew.py run 東京
python run_travel_crew.py run_with_payload '{"city": "東京"}'
"""
# 必要なライブラリのインポート
import sys # コマンドライン引数を扱うためのモジュール
import json # JSONデータを解析するためのモジュール
# 前のファイルで定義されたクルー（Crew）クラスをインポート
# （このファイルを実行するには、`travel_report_crew.py`が同じディレクトリにある必要があります）
from travel_report_crew import TravelReportCrew


def usage_and_exit():
    """使用法メッセージを表示し、スクリプトを終了する"""
    print("Usage:")
    print("  python run_travel_crew.py run <CityName> [output_filename]")
    print("  python run_travel_crew.py run_with_payload '<json-payload>'")
    sys.exit(1)


# スクリプトが直接実行された場合のメイン処理
if __name__ == "__main__":
    # 引数が1つ（スクリプト名のみ）の場合、使用法を表示して終了
    if len(sys.argv) < 2:
        usage_and_exit()


    cmd = sys.argv[1] # 最初の引数（コマンド）を取得


    crew = TravelReportCrew() # TravelReportCrewのインスタンスを生成


    # --- "run" コマンドの処理 ---
    if cmd == "run":
        # 都市名が指定されているかチェック
        if len(sys.argv) < 3:
            usage_and_exit()
        
        city = sys.argv[2] # 2番目の引数を都市名として取得
        
        # 3番目の引数があればそれを出力ファイル名に、なければデフォルト値を使用
        output = sys.argv[3] if len(sys.argv) > 3 else "travel_report.md"
        
        # クルーを実行
        crew.run(city=city, output=output)


    # --- "run_with_payload" コマンドの処理 ---
    elif cmd == "run_with_payload":
        # JSONペイロードが指定されているかチェック
        if len(sys.argv) < 3:
            usage_and_exit()
            
        try:
            # 2番目の引数をJSON文字列として解析
            payload = json.loads(sys.argv[2])
        except json.JSONDecodeError:
            # JSON解析エラーが発生した場合
            print("Invalid JSON payload")
            sys.exit(1)
            
        # ペイロードから 'city' または 'topic' キーの値を取得
        city = payload.get("city") or payload.get("topic") or ""
        
        # 都市名が取得できなかった場合
        if not city:
            print("Payload must contain 'city' or 'topic'")
            sys.exit(1)
            
        # クルーを実行（この実行方法では、出力ファイル名はデフォルト値になる）
        crew.run(city=city)


    # --- 未知のコマンドの場合の処理 ---
    else:
        usage_and_exit()
```