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

جواب «The Agent Loop with a Trace» چالش 4 از جلسه‌ی 73

سؤال

تابع run_agent(task) را بنویس: حداکثر MAX_STEPS دور؛ هر دور تصمیم را از fake_model(history) بگیر و با json.loads باز کن، decision را به تاریخچه اضافه کن؛ اگر final داشت، خط <n> think: <thought> را چاپ کن و جواب را برگردان؛ وگرنه ابزار را اجرا کن، خط <n> think: <thought> | <action> <input> -> <result> را چاپ کن و observation را اضافه کن. خروجی:
1 think: I need the diameter of Mars. | lookup Mars -> 6779
2 think: Now the diameter of Earth. | lookup Earth -> 12742
3 think: Subtract them. | calc 12742 - 6779 -> 5963
4 think: I have everything.
final: Earth is bigger by 5963 km.

راهنما

for n in range(1, MAX_STEPS + 1): → d = json.loads(fake_model(history))، history.append({"role": "decision", "content": d}). برای عمل: result = TOOLS[d["action"]](d["input"]) و history.append({"role": "observation", "content": result}).

یک جواب درست

import json

MAX_STEPS = 6
DIAMETER_KM = {"mercury": 4879, "mars": 6779, "earth": 12742, "jupiter": 139820}


def lookup(name):
    return str(DIAMETER_KM.get(name.strip().lower(), "not found"))


def calc(expr):
    a, op, b = expr.split()
    a, b = int(a), int(b)
    return str({"+": a + b, "-": a - b, "*": a * b}[op])


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


def fake_model(history):
    # A pretend agent brain: it decides from what it has observed so far.
    seen = [h["content"] for h in history if h["role"] == "observation"]
    if len(seen) == 0:
        return '{"thought": "I need the diameter of Mars.", "action": "lookup", "input": "Mars"}'
    if len(seen) == 1:
        return '{"thought": "Now the diameter of Earth.", "action": "lookup", "input": "Earth"}'
    if len(seen) == 2:
        return json.dumps({"thought": "Subtract them.", "action": "calc", "input": seen[1] + " - " + seen[0]})
    return json.dumps({"thought": "I have everything.", "final": "Earth is bigger by " + seen[2] + " km."})


def run_agent(task):
    history = [{"role": "task", "content": task}]
    for n in range(1, MAX_STEPS + 1):
        d = json.loads(fake_model(history))
        history.append({"role": "decision", "content": d})
        if "final" in d:
            print(n, "think:", d["thought"])
            return d["final"]
        result = TOOLS[d["action"]](d["input"])
        print(n, "think:", d["thought"], "|", d["action"], d["input"], "->", result)
        history.append({"role": "observation", "content": result})
    return "stopped: step limit"


print("final:", run_agent("How many km wider is Earth than Mars?"))

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن