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

جواب «It Only Remembers What You Send» چالش 4 از جلسه‌ی 67

سؤال

تابع chat(text) فقط پیام تازه را می‌فرستد، پس مدل اسم را «فراموش» می‌کند. درستش کن: پیام کاربر را به history اضافه کن، مدل را با کل history صدا بزن و جواب را با نقش assistant اضافه کن. خط آخر برنامه عمداً بدون تاریخچه می‌پرسد. خروجی:
Nice to meet you, Kian.
Your name is Kian.
I don't know your name. I only see the messages you send.

راهنما

سه خط: history.append({"role": "user", "content": text})، reply = fake_model(history)، history.append({"role": "assistant", "content": reply}).

یک جواب درست

def fake_model(messages):
    # A pretend model. It knows only what is inside `messages`.
    question = messages[-1]["content"]
    if question.startswith("My name is "):
        return "Nice to meet you, " + question[11:].strip(".") + "."
    if question == "What is my name?":
        for m in messages[:-1]:
            if m["role"] == "user" and m["content"].startswith("My name is "):
                return "Your name is " + m["content"][11:].strip(".") + "."
        return "I don't know your name. I only see the messages you send."
    return "OK."


history = [{"role": "system", "content": "You are a friendly helper."}]


def chat(text):
    history.append({"role": "user", "content": text})
    reply = fake_model(history)
    history.append({"role": "assistant", "content": reply})
    return reply


print(chat("My name is Kian."))     # a nickname: never your full name and address
print(chat("What is my name?"))
print(fake_model([{"role": "user", "content": "What is my name?"}]))

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