Ask, Use a Tool, Ask Again چالش 6 از جلسهی 43، سخت
حلقهی کامل. solve(question): prompt = TOOL_HELP + question. حداکثر ۳ دور: reply = ask(prompt)؛ call = parse_tool(reply)؛ اگر None بود، reply جواب نهایی است و برگردانده شود. وگرنه result = run_tool(call[0], call[1])، چاپ کن tool: calc 1234 * 5678 -> 7006652 و به آخر prompt اضافه کن "\nTOOL RESULT: " + str(result). اگر ۳ دور تمام شد: Too many steps. خروجی test:tool: calc 1234 * 5678 -> 7006652The answer is 7006652.Hi! Ask me a maths question.
و برای سؤال سوم سه خط tool: calc 1 + 1 -> 2 و بعد Too many steps.
def calc(expr):
parts = expr.split()
if len(parts) != 3:
return "error"
a, op, b = parts
if not (a.lstrip("-").isdigit() and b.lstrip("-").isdigit()):
return "error"
a = int(a)
b = int(b)
if op == "+":
return a + b
if op == "-":
return a - b
if op == "*":
return a * b
if op == "/":
if b == 0:
return "error"
return a / b
return "error"
def parse_tool(reply):
reply = reply.strip()
if not reply.startswith("TOOL "):
return None
parts = reply.split(" ", 2)
if len(parts) < 3:
return None
return (parts[1], parts[2])
def count_words(text):
return len(text.split())
def shout(text):
return text.upper() + "!"
TOOLS = {"calc": calc, "count_words": count_words, "shout": shout}
def run_tool(name, arg):
if name not in TOOLS:
return "unknown tool: " + name
return TOOLS[name](arg)
from ai import ask
TOOL_HELP = "If you need maths, reply only: TOOL calc <a> <op> <b>. Question: "
def solve(question):
return ask(question)
# ---- test with a pretend model (do not change) ----
def fake_ask(prompt, system=None, history=None):
if "forever" in prompt:
return "TOOL calc 1 + 1"
if "TOOL RESULT:" in prompt:
return "The answer is " + prompt.split("TOOL RESULT: ")[-1] + "."
if "times" in prompt:
return "TOOL calc 1234 * 5678"
return "Hi! Ask me a maths question."
ask = fake_ask
print(solve("What is 1234 times 5678?"))
print(solve("Hello robot"))
print(solve("Keep adding forever"))
راهنما و جواب این چالش · برگشت به درس جلسهی 43: ابزار دادن به مدل
بیشتر بخوان: تابع در پایتون: آموزش def، پارامتر و return با مثال