بتل کد 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

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": "user", "content": question}]}
    reply = fake_api(request)
    return reply["choices"][0]["message"]["content"]


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

راهنما و جواب این چالش · برگشت به درس جلسه‌ی 66: کلید رایگان روی کامپیوتر خودت

بیشتر بخوان: تابع در پایتون: آموزش def، پارامتر و return با مثال