Menu
CoddyTech

사람 승인

Coddy AI Engineering 여정의 도구와 에이전트 섹션에 포함된 레슨. 22개 중 13번째.

일부 도구는 읽기만 수행합니다. 일정 조회나 날씨 확인은 아무것도 변경하지 않습니다. 다른 도구들은 현실 세계에 작용합니다. 이메일을 보내거나, 카드를 결제하거나, 파일을 삭제하며, 잘못된 호출은 되돌릴 수 없습니다. 에이전트는 첫 번째 종류의 도구는 스스로 실행하고, 두 번째 종류의 도구를 실행하기 전에는 사람에게 물어봐야 합니다.

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로 표시하면 모델에게 해당 작업이 수행되지 않았음을 알리므로, 성공을 주장하는 대신 이를 보고하게 됩니다. 웹 앱에서는 이 질문이 확인 버튼이 되며, 루프는 동일한 방식으로 응답을 기다립니다.

challenge icon

챌린지

중급

사무용 어시스턴트가 묻지 않고 이메일을 보냅니다. 먼저 묻도록 만드세요. run_tool만 변경됩니다.

  1. 도구 이름이 NEEDS_APPROVAL에 있는 경우, 도구 이름과 입력 딕셔너리를 포함하여 Approve <name> <input>? (yes/no)를 출력한 다음, input()으로 한 줄을 읽습니다.
  2. 입력받은 줄이 yes가 아니라면 도구를 실행하지 마세요. 내용이 The user declined this action.이고 "is_error": True인 결과를 반환하세요.
  3. 그 외의 모든 도구 및 승인된 도구는 이전과 같이 실행하세요.

달력 관련 질문은 아무것도 묻지 않으며 추가 줄을 읽지 않습니다. 예를 들어, 입력이 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)}")
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

도구와 에이전트의 모든 레슨

직접 연습해 보세요: 온라인 Python 컴파일러