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

جواب «Fit the Token Budget» چالش 5 از جلسه‌ی 62

سؤال

پرامپت few-shot هر چه مثال بیشتری داشته باشد، توکن بیشتری می‌گیرد (و گران‌تر است). دو تابع بنویس. count_tokens(text): هر کلمه (با split) یک توکن، و هر کلمه‌ی بلندتر از ۶ حرف دو توکن. fit_examples(examples, question, budget): مثال‌ها را به ترتیب یکی‌یکی به پرامپت اضافه کند، فقط تا وقتی توکن‌های کل (مثال‌های انتخاب‌شده + خط سؤال) از budget بیشتر نشود، و تعداد مثال‌ها و توکن‌های کل را برگرداند. هر مثال یک خط Q: ... A: ... است و سؤال یک خط Q: ... A:. خروجی برای چهار بودجه باید این باشد:
budget 15: 0 examples, 9 tokens
budget 25: 1 examples, 20 tokens
budget 35: 2 examples, 31 tokens
budget 50: 3 examples, 44 tokens

راهنما

در count_tokens روی text.split() بچرخ و 2 if len(word) > 6 else 1 را جمع کن. در fit_examples برای هر مثال cost = count_tokens(f"Q: {q} A: {a}")؛ اگر total + cost > budget بود break، وگرنه total += cost و used += 1.

یک جواب درست

def count_tokens(text):
    total = 0
    for word in text.split():
        if len(word) > 6:
            total += 2
        else:
            total += 1
    return total


def fit_examples(examples, question, budget):
    question_line = f"Q: {question} A:"
    used = 0
    total = count_tokens(question_line)
    for q, a in examples:
        cost = count_tokens(f"Q: {q} A: {a}")
        if total + cost > budget:
            break
        total += cost
        used += 1
    return used, total


examples = [
    ("What is the capital of France?", "Paris"),
    ("What is the largest planet?", "Jupiter"),
    ("Which animal is the fastest runner?", "The cheetah"),
]
for budget in [15, 25, 35, 50]:
    used, total = fit_examples(examples, "Which gas do plants breathe in?", budget)
    print(f"budget {budget}: {used} examples, {total} tokens")

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