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

Step 5: The Full Assistant چالش 5 از جلسه‌ی 70، سخت

تابع assistant(question) را بنویس که چرخه‌ی کامل را اجرا کند: مدل را صدا بزن؛ برای درخواست ابزار، ابزار را اجرا کن و پیام‌های assistant و tool را اضافه کن؛ مدل را دوباره صدا بزن و content نهایی را برگردان (حداکثر ۳ دور، وگرنه gave up). خروجی:
Q: What is 15 * 4?
A: The answer is 60.0.
Q: Tell me about gravity
A: From the class notes: Gravity pulls masses toward each other.

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)


TOOLS = {"calc": calc, "lookup": lookup}


def run_tool(call):
    name = call["function"]["name"]
    if name not in TOOLS:
        return "error: unknown tool"
    return TOOLS[name](**json.loads(call["function"]["arguments"]))


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: picks a tool, then answers from the tool's result.
    last = messages[-1]
    if last["role"] == "tool":
        if last["name"] == "calc":
            return {"content": "The answer is " + last["content"] + ".", "tool_calls": None}
        return {"content": "From the class notes: " + last["content"], "tool_calls": None}
    q = last["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]})


def assistant(question):
    messages = [{"role": "user", "content": question}]
    return "gave up"


for q in ["What is 15 * 4?", "Tell me about gravity"]:
    print("Q:", q)
    print("A:", assistant(q))

راهنما و جواب این چالش · برگشت به درس جلسه‌ی 70: پروژه: دستیار درس · چالش بعدی: Step 6: The Honesty Guard and the Log

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