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

جواب «Recover, but Don't Repeat» چالش 6 از جلسه‌ی 73

سؤال

دو قانون ایمنی دیگر. ۱) اگر مدل ابزار ناشناخته خواست، خطا مشاهده می‌شود و عامل ادامه می‌دهد. ۲) اگر مدل دقیقاً همان عمل و ورودی قدم قبلی را دوباره خواست، قبل از اجرا بایست و stopped: the same action twice in a row برگردان. این مدل اول یک ابزار ناشناخته می‌خواهد، بعد درست کار می‌کند، بعد گیر می‌کند. خروجی:
1 wiki Jupiter -> error: unknown tool wiki
2 lookup Jupiter -> 139820
stopped: the same action twice in a row

راهنما

now = (d["action"], d["input"])؛ if now == last: return "stopped: the same action twice in a row"؛ آخر دور: last = now. برای ابزار ناشناخته همان if ... in TOOLS جلسه‌ی قبل.

یک جواب درست

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"))


TOOLS = {"lookup": lookup}


def fake_model(history):
    seen = [h["content"] for h in history if h["role"] == "observation"]
    if not seen:
        return '{"thought": "Ask the wiki.", "action": "wiki", "input": "Jupiter"}'
    return '{"thought": "Use lookup.", "action": "lookup", "input": "Jupiter"}'   # ...again and again


def run_agent(task):
    history = [{"role": "task", "content": task}]
    last = None          # the (action, input) of the previous step
    for n in range(1, MAX_STEPS + 1):
        d = json.loads(fake_model(history))
        if "final" in d:
            return d["final"]
        now = (d["action"], d["input"])
        if now == last:
            return "stopped: the same action twice in a row"
        if d["action"] in TOOLS:
            result = TOOLS[d["action"]](d["input"])
        else:
            result = "error: unknown tool " + d["action"]
        print(n, d["action"], d["input"], "->", result)
        history.append({"role": "observation", "content": result})
        last = now
    return "stopped: step limit"


print(run_agent("How wide is Jupiter?"))

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