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.
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}]
return "gave up"
print(answer("What is 12 times 7, and how many words are in 'the cat sat'?"))
راهنما و جواب این چالش · برگشت به درس جلسهی 69: ابزار دادن به مدل · چالش بعدی: Check Arguments, Ask a Human
بیشتر بخوان: تابع در پایتون: آموزش def، پارامتر و return با مثال