人間による承認
CoddyのAI Engineeringジャーニー「ツールとエージェント」セクションの一部。レッスン 13/22。
ツールの中には読み取りを行うだけのものもあります。カレンダーの照会や天気の確認は何も変更しません。一方、現実世界に影響を与えるツールもあります。それらはメールの送信、カード決済、ファイルの削除などを行うため、誤った呼び出しを取り消すことはできません。エージェントは前者のようなツールを独自に実行し、後者のようなツールについては事前に人に確認するべきです。
if block.name in NEEDS_APPROVAL:
print(f"Approve {block.name} {block.input}? (yes/no)")
if input() != "yes":
return {"type": "tool_result", "tool_use_id": block.id,
"content": "The user declined this action.", "is_error": True}何が起こるかを正確に承認してもらうために、ツールの名前と正確な引数を提示してください。ツールの実行後ではなく、必ず実行前に尋ねるようにしましょう。
拒否であっても tool_result であることに変わりはありません。次のメッセージではすべての tool_use ブロックに対して 1 つ必要であり、そうでない場合 API はリクエストを拒否します。"is_error": True とマークすることで、アクションが実行されなかったことがモデルに伝わるため、成功を主張する代わりにその旨を報告します。Web アプリでは質問が確認ボタンになり、ループは同様に回答を待ちます。
チャレンジ
中級オフィスアシスタントは確認せずにメールを送信してしまいます。まず確認するように変更してください。run_tool のみを変更します。
- ツールの名前が
NEEDS_APPROVALに含まれている場合は、ツールの名前とその入力辞書(input dict)を用いてApprove <name> <input>? (yes/no)を出力し、input()で1行を読み込みます。 - その行が
yesでない場合は、ツールを実行しないでください。content がThe user declined this action.であり、"is_error": Trueを含む結果を返します。 - それ以外のすべてのツール、および承認されたツールは、以前と同様に実行します。
カレンダーに関する質問では何も確認せず、追加の行を読み込むこともありません。例えば、入力が Send an email to ana@example.com about the team lunch および no の場合、プログラムは以下を出力します:
Approve send_email {'to': 'ana@example.com', 'subject': 'team lunch'}? (yes/no)
Answer: Sorry, I could not finish: The user declined this action.
Emails sent: 0自分で試してみよう
import coddy_ai as anthropic # 本番環境では: import anthropic
client = anthropic.Anthropic()
EVENTS = {"Friday": "team lunch at 12:30", "Monday": "budget review at 9:00"}
SENT = []
TOOLS = [
{
"name": "list_events",
"description": "List the calendar events for one day. Use it to answer questions about the calendar.",
"input_schema": {
"type": "object",
"properties": {"day": {"type": "string", "description": "A weekday, such as Friday"}},
"required": ["day"],
},
},
{
"name": "send_email",
"description": "Send an email to a recipient. Use it when the user asks to email someone.",
"input_schema": {
"type": "object",
"properties": {
"to": {"type": "string", "description": "The recipient's email address"},
"subject": {"type": "string", "description": "The subject line"},
},
"required": ["to", "subject"],
},
},
]
NEEDS_APPROVAL = {"send_email"}
def list_events(day):
return f"{day}: {EVENTS.get(day, 'nothing planned')}"
def send_email(to, subject):
SENT.append(to)
return f"Email sent to {to}."
FUNCTIONS = {"list_events": list_events, "send_email": send_email}
def run_tool(block):
# NEEDS_APPROVAL 内のツールを実行する前に確認する
return {"type": "tool_result", "tool_use_id": block.id, "content": FUNCTIONS[block.name](**block.input)}
request = input()
messages = [{"role": "user", "content": request}]
response = client.messages.create(model="claude-opus-5-5", max_tokens=300, 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=300, tools=TOOLS, messages=messages)
for block in response.content:
if block.type == "text":
print("Answer: " + block.text)
print(f"Emails sent: {len(SENT)}")
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
ツールとエージェントのすべてのレッスン
自分で練習してみよう: Pythonオンラインコンパイラ