人工确认
本课属于 Coddy AI Engineering 学习旅程的“工具与 Agent”单元。第 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 块都需要对应一个,否则 API 会拒绝该请求。将其标记为 "is_error": True 可以告诉模型该操作并未发生,因此它会据实报告,而不是声称成功。在 Web 应用中,这个问题会变成一个确认按钮;循环会以相同的方式等待回答。
挑战
中等办公室助手在发送电子邮件前没有进行询问。修改代码让它先询问。只需要修改 run_tool。
- 当工具的名称在
NEEDS_APPROVAL中时,使用工具的名称及其输入字典打印Approve <name> <input>? (yes/no),然后使用input()读取一行输入。 - 如果该行不是
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)}")
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
工具与 Agent中的所有课
自己练习: Python 在线编译器