بتل کد Battle Codeدارد باز می‌شود…

Check Arguments, Ask a Human چالش 6 از جلسه‌ی 69، سخت

دو لایه‌ی ایمنی بساز. ۱) check_args(name, args): برای multiply هر دو a و b باید عدد (int یا float) باشند، وگرنه bad argument <key>؛ برای send_message متن text حداکثر ۱۰۰ حرف. اگر درست بود None. ۲) safe_run(call): اگر ابزار در TOOLS نیست error: unknown tool، اگر آرگومان بد است همان پیام، اگر در NEEDS_OK است و human_ok(name, args) جواب False داد cancelled: a human said no؛ وگرنه اجرا. خروجی:
84
bad argument a
cancelled: a human said no
sent to teacher
error: unknown tool

import json


def multiply(a, b):
    return a * b


def send_message(to, text):
    return "sent to " + to          # pretend: nothing is really sent


TOOLS = {"multiply": multiply, "send_message": send_message}
NEEDS_OK = {"send_message"}         # irreversible: a human must confirm


def human_ok(name, args):
    # A pretend human who reads the request first.
    return args.get("to") == "teacher"


def check_args(name, args):
    return None


def safe_run(call):
    name = call["function"]["name"]
    args = json.loads(call["function"]["arguments"])
    return TOOLS[name](**args)


calls = [
    {"function": {"name": "multiply", "arguments": '{"a": 12, "b": 7}'}},
    {"function": {"name": "multiply", "arguments": '{"a": "twelve", "b": 7}'}},
    {"function": {"name": "send_message", "arguments": '{"to": "whole school", "text": "Free exam answers here!"}'}},
    {"function": {"name": "send_message", "arguments": '{"to": "teacher", "text": "I finished step 3."}'}},
    {"function": {"name": "format_disk", "arguments": '{}'}},
]
for call in calls:
    print(safe_run(call))

راهنما و جواب این چالش · برگشت به درس جلسه‌ی 69: ابزار دادن به مدل

بیشتر بخوان: تابع در پایتون: آموزش def، پارامتر و return با مثال