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

Step 4: Connect the Tools چالش 4 از جلسه‌ی 70، متوسط

حالا ابزارها را به مدل وصل کن. دیکشنری TOOLS را با calc و lookup بساز و تابع run_tool(call) را بنویس (اسم مجاز؟ آرگومان‌ها با json.loads، بعد TOOLS[name](**args)). برنامه برای هر سؤال، ابزارِ انتخاب‌شده‌ی مدل و نتیجه را چاپ می‌کند. خروجی:
calc 15 * 4 -> 60.0
lookup photosynthesis -> Plants turn light, water and CO2 into sugar and oxygen.
lookup volcanoes -> not found: volcanoes

import json

NOTES = {
    "photosynthesis": "Plants turn light, water and CO2 into sugar and oxygen.",
    "gravity": "Gravity pulls masses toward each other.",
}
OPS = {"+": lambda a, b: a + b, "-": lambda a, b: a - b,
       "*": lambda a, b: a * b, "/": lambda a, b: a / b}


def lookup(topic):
    key = topic.strip().lower()
    return NOTES.get(key, "not found: " + key)


def calc(expr):
    parts = expr.split()
    if len(parts) != 3 or parts[1] not in OPS:
        return "error: use a op b"
    try:
        a, b = float(parts[0]), float(parts[2])
    except ValueError:
        return "error: not a number"
    if parts[1] == "/" and b == 0:
        return "error: division by zero"
    return OPS[parts[1]](a, b)


def tool_call(name, args):
    return {"content": None, "tool_calls": [{"id": "t1", "function": {"name": name, "arguments": json.dumps(args)}}]}


def fake_model(messages):
    # A pretend model: digits -> calc, otherwise lookup the last word.
    q = messages[-1]["content"].lower().replace("?", "")
    if any(ch.isdigit() for ch in q):
        expr = " ".join(w for w in q.split() if w.isdigit() or w in "+-*/")
        return tool_call("calc", {"expr": expr})
    return tool_call("lookup", {"topic": q.split()[-1]})


TOOLS = {}


def run_tool(call):
    return "error: unknown tool"


for question in ["What is 15 * 4?", "Tell me about photosynthesis", "What do you know about volcanoes?"]:
    call = fake_model([{"role": "user", "content": question}])["tool_calls"][0]
    args = json.loads(call["function"]["arguments"])
    print(call["function"]["name"], list(args.values())[0], "->", run_tool(call))

راهنما و جواب این چالش · برگشت به درس جلسه‌ی 70: پروژه: دستیار درس · چالش بعدی: Step 5: The Full Assistant

بیشتر بخوان: مدیریت خطا با try و except در پایتون: آموزش کامل با مثال