Summarise the Old Part چالش 6 از جلسهی 39، سخت
squash(history, keep):
- اگر len(history) <= keep بود، همان history را برگرداند.
- وگرنه پیامهای قدیمی old = history[:-keep] را با " | " به هم بچسباند، از مدل بپرسد ask("Summarize this chat in one line: " + text) و یک لیست تازه برگرداند: اول {"role": "user", "content": "Summary of earlier chat: " + summary} و بعد keep پیام آخر.
خروجی test:3user | Summary of earlier chat: summary of 4 old messagesuser | line 5user | line 66
from ai import ask
def squash(history, keep):
return history
# ---- test with a pretend model (do not change) ----
def fake_ask(prompt, system=None, history=None):
return "summary of " + str(prompt.count("|") + 1) + " old messages"
ask = fake_ask
msgs = []
for i in range(1, 7):
msgs.append({"role": "user", "content": "line " + str(i)})
small = squash(msgs, 2)
print(len(small))
for m in small:
print(m["role"], "|", m["content"])
print(len(squash(msgs, 10)))
راهنما و جواب این چالش · برگشت به درس جلسهی 39: حافظهی گفتوگو
بیشتر بخوان: تابع در پایتون: آموزش def، پارامتر و return با مثال