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

جواب «home_chat.py, Site Version» چالش 6 از جلسه‌ی 66

سؤال

نسخه‌ی سایتِ home_chat.py را بنویس. تابع ask(question) یک درخواست با یک پیام system (You are a patient tutor for teenagers.) و یک پیام user بسازد، fake_api را صدا بزند و متن جواب را برگرداند؛ اگر finish_reason برابر length بود، [cut off] به آخر متن اضافه کند. توکن‌های هر جواب را هم به used اضافه کند. خروجی:
A token is a piece of text.
Tokens are counted for the price and the [cut off]
used 48

راهنما

پیام سیستم را اول لیست بگذار: {"role": "system", "content": "You are a patient tutor for teenagers."}. بعد choice = reply["choices"][0]، used += reply["usage"]["total_tokens"] و if choice["finish_reason"] == "length": text += " [cut off]".

یک جواب درست

def fake_api(request):
    # A pretend server with the real reply shape. At home: client.chat.completions.create(...)
    system = request["messages"][0]["content"]
    question = request["messages"][-1]["content"]
    if "tutor" not in system:
        return {"choices": [{"message": {"content": "(no system prompt)"}, "finish_reason": "stop"}],
                "usage": {"total_tokens": 1}}
    if question == "What is a token?":
        text, why = "A token is a piece of text.", "stop"
    else:
        text, why = "Tokens are counted for the price and the", "length"
    return {"choices": [{"message": {"role": "assistant", "content": text}, "finish_reason": why}],
            "usage": {"total_tokens": 20 if why == "stop" else 28}}


used = 0


def ask(question):
    global used
    request = {"model": "deepseek-chat", "messages": [
        {"role": "system", "content": "You are a patient tutor for teenagers."},
        {"role": "user", "content": question},
    ]}
    reply = fake_api(request)
    used += reply["usage"]["total_tokens"]
    choice = reply["choices"][0]
    text = choice["message"]["content"]
    if choice["finish_reason"] == "length":
        text += " [cut off]"
    return text


print(ask("What is a token?"))
print(ask("Why do tokens matter?"))
print("used", used)

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