جواب «The Handout Bot» چالش 6 از جلسهی 42
سؤال
همهی تکهها آمادهاند. answer(question):
- picked = top_chunks(question, CHUNKS, 2).
- اگر خالی بود، بدون صدا زدن مدل برگرداند I don't know. The handout does not say.
- وگرنه reply = ask(build_prompt(question, CHUNKS, picked), system=SYSTEM) و برگرداند reply + " (source: part 1, 2)": شمارهها (اندیس + ۱) با ", " جدا شدهاند.
خروجی test:Answer (parts used: 2). (source: part 1, 3)Answer (parts used: 1). (source: part 3)I don't know. The handout does not say.model calls: 2
راهنما
شمارهها: یک لیست از str(i + 1) بساز و ", ".join(...).
یک جواب درست
HANDOUT = """Nilu is a small made-up planet with two moons, Pip and Tov.
A day on Nilu lasts 30 hours, and a year lasts 200 days.
The glow trees of Nilu shine blue at night. They drink rain water
and grow 2 meters every year.
The sand foxes of Nilu sleep in the day and hunt at night.
They eat glow berries and small beetles.
Pip is the bigger moon. It turns around Nilu in 12 days.
Tov is tiny and turns around Nilu in 5 days."""
STOP = {"the", "a", "an", "is", "of", "in", "on", "and", "what", "how", "do", "does", "it", "at", "to", "many"}
def words(text):
clean = ""
for ch in text.lower():
if ch in ".,?!":
clean += " "
else:
clean += ch
result = set()
for w in clean.split():
if w not in STOP:
result.add(w)
return result
def split_chunks(text):
chunks = []
for part in text.split("\n\n"):
part = part.strip()
if part != "":
chunks.append(part)
return chunks
def score(question, chunk):
return len(words(question) & words(chunk))
def top_chunks(question, chunks, k):
picked = []
for round_number in range(k):
best = None
best_score = 0
for i in range(len(chunks)):
s = score(question, chunks[i])
if i not in picked and s > best_score:
best = i
best_score = s
if best is None:
break
picked.append(best)
return picked
def build_prompt(question, chunks, picked):
text = "Use ONLY the handout parts below. If the answer is not there, say: I don't know."
for i in picked:
text += "\n[" + str(i + 1) + "] " + chunks[i]
text += "\nQuestion: " + question
return text
from ai import ask
CHUNKS = split_chunks(HANDOUT)
SYSTEM = "You answer questions about a school handout. Be short and kind."
def answer(question):
picked = top_chunks(question, CHUNKS, 2)
if len(picked) == 0:
return "I don't know. The handout does not say."
reply = ask(build_prompt(question, CHUNKS, picked), system=SYSTEM)
numbers = []
for i in picked:
numbers.append(str(i + 1))
return reply + " (source: part " + ", ".join(numbers) + ")"
# ---- test with a pretend model (do not change) ----
calls = []
def fake_ask(prompt, system=None, history=None):
calls.append(prompt)
return "Answer (parts used: " + str(prompt.count("[")) + ")."
ask = fake_ask
print(answer("How long is a day on Nilu?"))
print(answer("What do sand foxes eat?"))
print(answer("What is the capital of France?"))
print("model calls:", len(calls))
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن