Run the Right Tool چالش 3 از جلسهی 69، متوسط
تابع run_tool(call) را بنویس: اسم ابزار را بخوان؛ اگر در TOOLS نیست error: unknown tool <name> برگردان (و هیچ چیز اجرا نکن)؛ وگرنه آرگومانها را با json.loads باز کن و TOOLS[name](**args) را برگردان. خروجی:124error: unknown tool delete_files
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):
return None
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))
راهنما و جواب این چالش · برگشت به درس جلسهی 69: ابزار دادن به مدل · چالش بعدی: Send the Result Back
بیشتر بخوان: تابع در پایتون: آموزش def، پارامتر و return با مثال