جواب «Run the Right Tool» چالش 3 از جلسهی 69
سؤال
تابع run_tool(call) را بنویس: اسم ابزار را بخوان؛ اگر در TOOLS نیست error: unknown tool <name> برگردان (و هیچ چیز اجرا نکن)؛ وگرنه آرگومانها را با json.loads باز کن و TOOLS[name](**args) را برگردان. خروجی:124error: unknown tool delete_files
راهنما
name = call["function"]["name"]؛ if name not in TOOLS: return "error: unknown tool " + name؛ بعد args = json.loads(call["function"]["arguments"]) و return TOOLS[name](**args).
یک جواب درست
import json
def add(a, b):
return a + b
def word_count(text):
return len(text.split())
TOOLS = {"add": add, "word_count": word_count} # the allowlist
def run_tool(call):
name = call["function"]["name"]
if name not in TOOLS:
return "error: unknown tool " + name
args = json.loads(call["function"]["arguments"])
return TOOLS[name](**args)
calls = [
{"id": "c1", "function": {"name": "add", "arguments": '{"a": 5, "b": 7}'}},
{"id": "c2", "function": {"name": "word_count", "arguments": '{"text": "tools make models useful"}'}},
{"id": "c3", "function": {"name": "delete_files", "arguments": '{"folder": "/"}'}},
]
for call in calls:
print(run_tool(call))
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن