Menu
CoddyTech

エージェントループ

CoddyのAI Engineeringジャーニー「ツールとエージェント」セクションの一部。レッスン 6/22。

リクエストによっては、複数のツール呼び出しが必要になる場合があります。ランプの価格をユーロで計算するには、モデルはまず価格を取得する必要があり、その後に初めて換算をリクエストできます。2番目の呼び出しは最初の結果に依存するため、両方の呼び出しを一度に計画することはできません。

エージェントループがこれを処理します。モデルを呼び出し、応答の stop_reason == "tool_use" である間は、要求されたツールを実行してその結果を送り直し、再びモデルを呼び出します。停止理由がそれ以外になったとき、テキストブロックに最終的な回答が含まれます。

response = client.messages.create(model="claude-opus-5-5", max_tokens=500, tools=TOOLS, messages=messages)
while response.stop_reason == "tool_use":
    messages.append({"role": "assistant", "content": response.content})
    results = [run_tool(block) for block in response.content if block.type == "tool_use"]
    messages.append({"role": "user", "content": results})
    response = client.messages.create(model="claude-opus-5-5", max_tokens=500, tools=TOOLS, messages=messages)

各パスでは、モデルのツール呼び出しと、あなたの結果という2つのターンが追加されます。リストは大きくなり、モデルは毎回の呼び出しでそのすべてを読み込みます。プロダクションコードでは、このループをSDKのツールランナー(client.beta.messages.tool_runner)やManaged Agentsに任せることがよくあります。一度自分で書いてみることで、それらが代わりに何をしてくれているかが分かります。

challenge icon

チャレンジ

中級

ショップの価格アシスタントのためのエージェントループを作成してください。スターターコードでは、2つのツール、それらに対応する FUNCTIONS 内の関数、および最初のメッセージが定義されています。

  1. model="claude-opus-5-5"、max_tokens=500、tools=TOOLS、およびメッセージを指定してモデルを呼び出します。
  2. 停止理由が "tool_use" である間:アシスタントのターンを追加し、FUNCTIONS[block.name](**block.input) で各 tool_use ブロックを実行し、それぞれについて Tool: 、名前、スペース、入力辞書を出力し、すべての結果を1つのユーザーメッセージとして追加して、モデルを再度呼び出します。
  3. Answer: と最終レスポンスのテキストを出力します。
  4. Steps: とモデルを呼び出した回数を出力します。

例えば、入力が What is the price of the mug in yen? の場合、プログラムは次のように出力します:

Tool: get_price {'item': 'mug'}
Tool: convert_currency {'amount': 8, 'currency': 'JPY'}
Answer: Here is what I found:
- The mug costs 8 dollars
- 8 dollars is 1200.00 JPY
Steps: 3

自分で試してみよう

import coddy_ai as anthropic  # 本番環境では: import anthropic

client = anthropic.Anthropic()

PRICES = {"lamp": 40, "desk": 120, "chair": 65, "mug": 8}
RATES = {"EUR": 0.92, "GBP": 0.79, "JPY": 150.0}


def get_price(item):
    if item in PRICES:
        return f"The {item} costs {PRICES[item]} dollars"
    return f"No price for {item}"


def convert_currency(amount, currency):
    return f"{amount} dollars is {amount * RATES[currency]:.2f} {currency}"


TOOLS = [
    {
        "name": "get_price",
        "description": "Look up the price of an item in dollars",
        "input_schema": {
            "type": "object",
            "properties": {"item": {"type": "string", "description": "The item to price"}},
            "required": ["item"],
        },
    },
    {
        "name": "convert_currency",
        "description": "Convert a dollar amount to another currency",
        "input_schema": {
            "type": "object",
            "properties": {
                "amount": {"type": "number", "description": "The amount in dollars"},
                "currency": {"type": "string", "description": "The currency code, such as EUR"},
            },
            "required": ["amount", "currency"],
        },
    },
]
FUNCTIONS = {"get_price": get_price, "convert_currency": convert_currency}

request = input()
messages = [{"role": "user", "content": request}]

# エージェントループを実行: 呼び出しごとに "Tool: <name> <input>" を出力し、
# 次に "Answer: " と最終テキスト、続いて "Steps: " とAPI呼び出し回数を出力する
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

ツールとエージェントのすべてのレッスン

自分で練習してみよう: Pythonオンラインコンパイラ