Menu
CoddyTech

מגבלות צעדים

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

לולאת סוכן מסתיימת כאשר המודל מפסיק לבקש כלים, ואין שום דבר שמבטיח שהוא יעשה זאת. כלי שממשיך להיכשל עם try again יכול לגרום למודל לנסות שוב לנצח, וכל מעבר עולה בקריאה ובאסימונים שלה. הגדירו מגבלה ללולאה:

steps = 1
while response.stop_reason == "tool_use":
    if steps == MAX_STEPS:
        break
    # הרץ את הכלים, הוסף את התורות, קרא למודל שוב
    steps += 1
if response.stop_reason == "tool_use":
    print("Gave up: the task took too many steps")

הבדיקה נמצאת בראש הלולאה, ולכן התוכנית אף פעם לא מבצעת את קריאה מספר MAX_STEPS + 1. לאחר הלולאה, סיבת העצירה מראה לך כיצד היא הסתיימה: עדיין tool_use פירושו שהמגבלה עצרה אותה ואין תשובה להציג. הודע על כך למשתמש במקום לא להדפיס דבר. ניסיונות חוזרים הם לעיתים קרובות נכונים: שירות שחווה חריגת זמן פעם אחת עשוי לענות בניסיון הבא. המגבלה מאפשרת ללולאה לבצע ניסיונות חוזרים ועדיין להסתיים. סוכנים בסביבת ייצור מגבילים גם הם טוקנים וזמן באותה דרך.

challenge icon

אתגר

בינוני

סוכן המסעדות בקוד ההתחלתי רץ ללא הפסקה כאשר מערכת ההזמנות ממשיכה להיכשל, מכיוון שהמודל מנסה שוב בכל פעם. הוסף מגבלת צעדים.

  1. בתחילת הלולאה, בצע break כאשר steps שווה ל-MAX_STEPS.
  2. לאחר הלולאה, אם סיבת העצירה היא עדיין "tool_use", הדפס Stopped: no answer after 5 steps (השתמש ב-MAX_STEPS).
  3. המשך להדפיס את התשובה, כאשר יש כזו, ואת הצעדים.

לדוגמה, עבור הקלט Is there a table at Golden Dragon tonight? התוכנית מדפיסה:

Tool: check_table {'restaurant': 'Golden Dragon'} -> error: The booking system is temporarily unavailable, try again
Tool: check_table {'restaurant': 'Golden Dragon'} -> error: The booking system is temporarily unavailable, try again
Tool: check_table {'restaurant': 'Golden Dragon'} -> error: The booking system is temporarily unavailable, try again
Tool: check_table {'restaurant': 'Golden Dragon'} -> error: The booking system is temporarily unavailable, try again
Stopped: no answer after 5 steps
Steps: 5

נסו בעצמכם

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

client = anthropic.Anthropic()

MAX_STEPS = 5
TABLES = {"Bella Vista": "a table for two at 8 pm", "Sunset Grill": "a table by the window at 9 pm"}
attempts = {}


def check_table(restaurant):
    attempts[restaurant] = attempts.get(restaurant, 0) + 1
    if restaurant == "Golden Dragon":
        raise TimeoutError("The booking system is temporarily unavailable, try again")
    if restaurant == "Sunset Grill" and attempts[restaurant] < 3:
        raise TimeoutError("The booking system timed out, try again")
    if restaurant in TABLES:
        return f"{restaurant} has {TABLES[restaurant]}"
    return f"{restaurant} has no free table tonight"


TOOLS = [
    {
        "name": "check_table",
        "description": "Check if a restaurant has a free table tonight",
        "input_schema": {
            "type": "object",
            "properties": {"restaurant": {"type": "string", "description": "The restaurant name"}},
            "required": ["restaurant"],
        },
    }
]


def run_tool(block):
    try:
        output = check_table(**block.input)
    except TimeoutError as error:
        print(f"Tool: {block.name} {block.input} -> error: {error}")
        return {"type": "tool_result", "tool_use_id": block.id, "content": str(error), "is_error": True}
    print(f"Tool: {block.name} {block.input} -> {output}")
    return {"type": "tool_result", "tool_use_id": block.id, "content": output}


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

# עצור את הלולאה כאשר היא קראה למודל MAX_STEPS פעמים
response = client.messages.create(model="claude-opus-5-5", max_tokens=500, tools=TOOLS, messages=messages)
steps = 1
while response.stop_reason == "tool_use":
    messages.append({"role": "assistant", "content": response.content})
    results = [run_tool(block) for block in response.content if block.type == "tool_use"]
    messages.append({"role": "user", "content": results})
    response = client.messages.create(model="claude-opus-5-5", max_tokens=500, tools=TOOLS, messages=messages)
    steps += 1

for block in response.content:
    if block.type == "text":
        print("Answer: " + block.text)
print(f"Steps: {steps}")
quiz iconבחנו את עצמכם

השיעור הזה כולל חידון קצר. התחילו את השיעור כדי לענות עליו ולעקוב אחרי ההתקדמות.

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

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