Menu
CoddyTech

Limity kroków

Część sekcji Narzędzia i agenci ścieżki AI Engineering w Coddy. Lekcja 9 z 22.

Pętla agenta kończy się, gdy model przestaje prosić o narzędzia, a nic nie gwarantuje, że tak się stanie. Narzędzie, które ciągle kończy się niepowodzeniem z komunikatem try again, może sprawić, że model będzie próbował w nieskończoność, a każde przejście kosztuje wywołanie i jego tokeny. Ustaw limit dla pętli:

steps = 1
while response.stop_reason == "tool_use":
    if steps == MAX_STEPS:
        break
    # uruchom narzędzia, dodaj tury, wywołaj model ponownie
    steps += 1
if response.stop_reason == "tool_use":
    print("Gave up: the task took too many steps")

Sprawdzenie znajduje się na początku pętli, więc program nigdy nie wykonuje wywołania o numerze MAX_STEPS + 1. Po pętli powód zatrzymania informuje, w jaki sposób się zakończyła: nadal tool_use oznacza, że limit ją zatrzymał i nie ma odpowiedzi do wyświetlenia. Poinformuj o tym użytkownika, zamiast niczego nie wypisywać. Ponowne próby często mają sens: usługa, w której raz przekroczono limit czasu, może odpowiedzieć przy kolejnej próbie. Limit pozwala pętli ponawiać próby i mimo to się zakończyć. Agenci produkcyjni również w ten sam sposób ograniczają tokeny i czas.

challenge icon

Wyzwanie

Średni

Agent restauracyjny w kodzie początkowym działa w nieskończoność, gdy system rezerwacji ciągle zgłasza błędy, ponieważ model ponawia próbę za każdym razem. Dodaj limit kroków.

  1. Na początku pętli wykonaj break, gdy steps jest równe MAX_STEPS.
  2. Po pętli, jeśli powód zatrzymania to nadal "tool_use", wypisz Stopped: no answer after 5 steps (użyj MAX_STEPS).
  3. Nadal wypisuj odpowiedź, gdy się pojawi, oraz kroki.

Na przykład dla danych wejściowych Is there a table at Golden Dragon tonight? program wypisuje:

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

Spróbuj swoich sił

import coddy_ai as anthropic  # na produkcji: 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}]

# Zatrzymaj pętlę, gdy wywoła model MAX_STEPS razy
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 iconSprawdź się

Ta lekcja zawiera krótki quiz. Zacznij lekcję, żeby na niego odpowiedzieć i śledzić swoje postępy.

Wszystkie lekcje w sekcji Narzędzia i agenci

Poćwicz samodzielnie: Kompilator Python online