جواب «Step 5: The Full Assistant» چالش 5 از جلسهی 70
سؤال
تابع assistant(question) را بنویس که چرخهی کامل را اجرا کند: مدل را صدا بزن؛ برای درخواست ابزار، ابزار را اجرا کن و پیامهای assistant و tool را اضافه کن؛ مدل را دوباره صدا بزن و content نهایی را برگردان (حداکثر ۳ دور، وگرنه gave up). خروجی:Q: What is 15 * 4?A: The answer is 60.0.Q: Tell me about gravityA: From the class notes: Gravity pulls masses toward each other.
راهنما
پیام ابزار اینجا یک کلید name هم لازم دارد چون fake_model از آن استفاده میکند: {"role": "tool", "tool_call_id": call["id"], "name": call["function"]["name"], "content": str(result)}. حلقه: for _ in range(3):.
یک جواب درست
import json
NOTES = {
"photosynthesis": "Plants turn light, water and CO2 into sugar and oxygen.",
"gravity": "Gravity pulls masses toward each other.",
}
OPS = {"+": lambda a, b: a + b, "-": lambda a, b: a - b,
"*": lambda a, b: a * b, "/": lambda a, b: a / b}
def lookup(topic):
key = topic.strip().lower()
return NOTES.get(key, "not found: " + key)
def calc(expr):
parts = expr.split()
if len(parts) != 3 or parts[1] not in OPS:
return "error: use a op b"
try:
a, b = float(parts[0]), float(parts[2])
except ValueError:
return "error: not a number"
if parts[1] == "/" and b == 0:
return "error: division by zero"
return OPS[parts[1]](a, b)
TOOLS = {"calc": calc, "lookup": lookup}
def run_tool(call):
name = call["function"]["name"]
if name not in TOOLS:
return "error: unknown tool"
return TOOLS[name](**json.loads(call["function"]["arguments"]))
def tool_call(name, args):
return {"content": None, "tool_calls": [{"id": "t1", "function": {"name": name, "arguments": json.dumps(args)}}]}
def fake_model(messages):
# A pretend model: picks a tool, then answers from the tool's result.
last = messages[-1]
if last["role"] == "tool":
if last["name"] == "calc":
return {"content": "The answer is " + last["content"] + ".", "tool_calls": None}
return {"content": "From the class notes: " + last["content"], "tool_calls": None}
q = last["content"].lower().replace("?", "")
if any(ch.isdigit() for ch in q):
expr = " ".join(w for w in q.split() if w.isdigit() or w in "+-*/")
return tool_call("calc", {"expr": expr})
return tool_call("lookup", {"topic": q.split()[-1]})
def assistant(question):
messages = [{"role": "user", "content": question}]
for _ in range(3):
reply = fake_model(messages)
if not reply["tool_calls"]:
return reply["content"]
messages.append({"role": "assistant", "content": None, "tool_calls": reply["tool_calls"]})
for call in reply["tool_calls"]:
result = run_tool(call)
messages.append({"role": "tool", "tool_call_id": call["id"],
"name": call["function"]["name"], "content": str(result)})
return "gave up"
for q in ["What is 15 * 4?", "Tell me about gravity"]:
print("Q:", q)
print("A:", assistant(q))
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن