Menu
CoddyTech

אישור אנושי

חלק מהיחידה כלים וסוכנים במסלול ה-AI Engineering של Coddy. שיעור 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 מודיע למודל שהפעולה לא התרחשה, ולכן הוא מדווח על כך במקום לטעון להצלחה. באפליקציית ווב השאלה הופכת ללחצן אישור; הלולאה מחכה לתשובה באותה הדרך.

challenge icon

אתגר

בינוני

עוזר המשרד שולח אימיילים מבלי לבקש אישור. גרום לו לבקש אישור תחילה. רק run_tool משתנה.

  1. כאשר שם הכלי נמצא ב-NEEDS_APPROVAL, הדפס Approve <name> <input>? (yes/no) עם שם הכלי ומילון ה-input שלו, ולאחר מכן קרא שורה אחת עם 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 אונליין