Menu
CoddyTech

סיכום: עוזר חנות

חלק מהיחידה כלים וסוכנים במסלול ה-AI Engineering של Coddy. שיעור 10 מתוך 22.

challenge icon

אתגר

קשה

בנה את לולאת הסוכן (agent loop) של עוזר החנות. הקוד ההתחלתי מגדיר שני כלים, את הפונקציות שמאחוריהם ב-FUNCTIONS, את MAX_STEPS ואת ההודעה הראשונה. שתי הפונקציות מעלות ValueError עבור מוצר לא מוכר, ו-check_stock מעלה TimeoutError כאשר מערכת המחסן אינה זמינה.

  1. כתוב את run_tool(block): הרץ את FUNCTIONS[block.name](**block.input) והחזר את ה-tool_result שלו. תפוס את ValueError ו-TimeoutError והחזר תוצאת שגיאה עם ההודעה ו-"is_error": True. הדפס Tool: <name> <input> -> <output> עבור תוצאה, או Tool: <name> <input> -> error: <message> עבור שגיאה.
  2. קרא למודל (model="claude-opus-5-5", max_tokens=500, tools=TOOLS) ובצע לולאה כל עוד הוא מבקש כלים: הוסף את תור המסייע (assistant turn), שלח את כל התוצאות בהודעת משתמש אחת, וקרא שוב.
  3. עצור את הלולאה כאשר היא קראה למודל MAX_STEPS פעמים, ואז הדפס Stopped: no answer after 4 steps.
  4. הדפס Answer: ואת הטקסט הסופי כשיש כזה, ואז Steps: ואת מספר הקריאות.

לדוגמה, עבור הקלט Check stock for the desk lamp and the price of the desk lamp התוכנית מדפיסה:

Tool: check_stock {'product': 'desk lamp'} -> desk lamp: 12 in stock
Tool: get_price {'item': 'desk lamp'} -> desk lamp: 40 dollars
Answer: Here is what I found:
- desk lamp: 12 in stock
- desk lamp: 40 dollars
Steps: 2

נסו בעצמכם

import coddy_ai as anthropic  # בסביבת ייצור: import anthropic

client = anthropic.Anthropic()

MAX_STEPS = 4
STOCK = {"desk lamp": 12, "bookshelf": 5, "office chair": 0}
PRICES = {"desk lamp": 40, "bookshelf": 85, "office chair": 65, "garden bench": 150}


def check_stock(product):
    if product == "garden bench":
        raise TimeoutError("The warehouse system is temporarily unavailable, try again")
    if product not in STOCK:
        raise ValueError(f"Unknown product: {product}")
    return f"{product}: {STOCK[product]} in stock"


def get_price(item):
    if item not in PRICES:
        raise ValueError(f"No price for {item}")
    return f"{item}: {PRICES[item]} dollars"


TOOLS = [
    {
        "name": "check_stock",
        "description": "Check how many units of a product are in stock",
        "input_schema": {
            "type": "object",
            "properties": {"product": {"type": "string", "description": "The product name"}},
            "required": ["product"],
        },
    },
    {
        "name": "get_price",
        "description": "Look up the price of an item in dollars",
        "input_schema": {
            "type": "object",
            "properties": {"item": {"type": "string", "description": "The item to price"}},
            "required": ["item"],
        },
    },
]
FUNCTIONS = {"check_stock": check_stock, "get_price": get_price}

request = input()
messages = [{"role": "user", "content": request}]

# כתוב את הקוד שלך למטה

כל השיעורים ביחידה כלים וסוכנים

תרגלו בעצמכם: קומפיילר Python אונליין