The Agent Loop with a Trace چالش 4 از جلسهی 73، متوسط
تابع run_agent(task) را بنویس: حداکثر MAX_STEPS دور؛ هر دور تصمیم را از fake_model(history) بگیر و با json.loads باز کن، decision را به تاریخچه اضافه کن؛ اگر final داشت، خط <n> think: <thought> را چاپ کن و جواب را برگردان؛ وگرنه ابزار را اجرا کن، خط <n> think: <thought> | <action> <input> -> <result> را چاپ کن و observation را اضافه کن. خروجی:1 think: I need the diameter of Mars. | lookup Mars -> 67792 think: Now the diameter of Earth. | lookup Earth -> 127423 think: Subtract them. | calc 12742 - 6779 -> 59634 think: I have everything.final: Earth is bigger by 5963 km.
import json
MAX_STEPS = 6
DIAMETER_KM = {"mercury": 4879, "mars": 6779, "earth": 12742, "jupiter": 139820}
def lookup(name):
return str(DIAMETER_KM.get(name.strip().lower(), "not found"))
def calc(expr):
a, op, b = expr.split()
a, b = int(a), int(b)
return str({"+": a + b, "-": a - b, "*": a * b}[op])
TOOLS = {"lookup": lookup, "calc": calc}
def fake_model(history):
# A pretend agent brain: it decides from what it has observed so far.
seen = [h["content"] for h in history if h["role"] == "observation"]
if len(seen) == 0:
return '{"thought": "I need the diameter of Mars.", "action": "lookup", "input": "Mars"}'
if len(seen) == 1:
return '{"thought": "Now the diameter of Earth.", "action": "lookup", "input": "Earth"}'
if len(seen) == 2:
return json.dumps({"thought": "Subtract them.", "action": "calc", "input": seen[1] + " - " + seen[0]})
return json.dumps({"thought": "I have everything.", "final": "Earth is bigger by " + seen[2] + " km."})
def run_agent(task):
history = [{"role": "task", "content": task}]
return "stopped: step limit"
print("final:", run_agent("How many km wider is Earth than Mars?"))
راهنما و جواب این چالش · برگشت به درس جلسهی 73: عامل: فکر، عمل، مشاهده · چالش بعدی: The Step Limit
بیشتر بخوان: تابع در پایتون: آموزش def، پارامتر و return با مثال