جواب «Several Tools in One Reply» چالش 5 از جلسهی 69
سؤال
مدل میتواند در یک جواب چند ابزار بخواهد. تابع answer(question) را بنویس: حداکثر ۳ دور؛ در هر دور مدل را صدا بزن؛ اگر tool_calls نداشت، content را برگردان؛ وگرنه برای هر درخواست ابزار را با run_tool اجرا کن، خط tool <name> <arguments> -> <result> را چاپ کن و پیام tool را اضافه کن. اگر بعد از ۳ دور جوابی نبود gave up. خروجی:tool multiply {"a": 12, "b": 7} -> 84tool word_count {"text": "the cat sat"} -> 312 x 7 = 84 and the sentence has 3 words.
راهنما
for round in range(3): → reply = fake_model(messages)؛ if not reply["tool_calls"]: return reply["content"]؛ messages.append({"role": "assistant", ...})؛ بعد for call in reply["tool_calls"]: → result = run_tool(call)، چاپ، و messages.append({"role": "tool", "tool_call_id": call["id"], "content": str(result)}).
یک جواب درست
import json
def multiply(a, b):
return a * b
def word_count(text):
return len(text.split())
TOOLS = {"multiply": multiply, "word_count": word_count}
def run_tool(call):
name = call["function"]["name"]
if name not in TOOLS:
return "error: unknown tool " + name
return TOOLS[name](**json.loads(call["function"]["arguments"]))
def fake_model(messages):
# Asks for two tools at once, then answers from both results.
results = [m["content"] for m in messages if m["role"] == "tool"]
if len(results) == 2:
return {"content": f"12 x 7 = {results[0]} and the sentence has {results[1]} words.", "tool_calls": None}
return {"content": None, "tool_calls": [
{"id": "a", "function": {"name": "multiply", "arguments": '{"a": 12, "b": 7}'}},
{"id": "b", "function": {"name": "word_count", "arguments": '{"text": "the cat sat"}'}},
]}
def answer(question):
messages = [{"role": "user", "content": question}]
for round 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)
print("tool", call["function"]["name"], call["function"]["arguments"], "->", result)
messages.append({"role": "tool", "tool_call_id": call["id"], "content": str(result)})
return "gave up"
print(answer("What is 12 times 7, and how many words are in 'the cat sat'?"))
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن