Menu
CoddyTech

Giới hạn bước

Thuộc phần Công cụ và agent trong hành trình AI Engineering của Coddy. Bài học 9 trên 22.

Vòng lặp agent (agent loop) kết thúc khi mô hình dừng yêu cầu công cụ, và không có gì đảm bảo điều đó sẽ xảy ra. Một công cụ liên tục thất bại với try again có thể khiến mô hình thử lại mãi mãi, và mỗi lượt chạy đều tốn một lượt gọi cùng các token. Đặt giới hạn cho vòng lặp:

steps = 1
while response.stop_reason == "tool_use":
    if steps == MAX_STEPS:
        break
    # chạy các công cụ, thêm các lượt, gọi lại mô hình
    steps += 1
if response.stop_reason == "tool_use":
    print("Gave up: the task took too many steps")

Việc kiểm tra nằm ở đầu vòng lặp (loop), vì vậy chương trình không bao giờ thực hiện cuộc gọi thứ MAX_STEPS + 1. Sau vòng lặp, lý do dừng cho bạn biết chương trình đã kết thúc theo cách nào: nếu vẫn là tool_use thì có nghĩa là giới hạn đã dừng vòng lặp và không có câu trả lời nào để hiển thị. Thông báo cho người dùng biết điều đó thay vì không in ra gì cả. Việc thử lại thường rất hiệu quả: một dịch vụ bị hết thời gian chờ ở một lần gọi có thể sẽ phản hồi ở lần thử tiếp theo. Giới hạn giúp vòng lặp có thể thử lại mà vẫn đảm bảo dừng lại được. Các agent thực tế cũng giới hạn token và thời gian theo cách tương tự.

challenge icon

Thử thách

Trung bình

Agent đặt nhà hàng trong code ban đầu sẽ chạy vô hạn khi hệ thống đặt bàn liên tục gặp lỗi, vì mô hình sẽ thử lại mỗi lần. Thêm giới hạn số bước.

  1. Ở đầu vòng lặp, break khi steps bằng MAX_STEPS.
  2. Sau vòng lặp, nếu lý do dừng vẫn là "tool_use", in ra Stopped: no answer after 5 steps (sử dụng MAX_STEPS).
  3. Tiếp tục in ra câu trả lời, khi có câu trả lời, và số bước.

Ví dụ, với đầu vào Is there a table at Golden Dragon tonight? chương trình sẽ in ra:

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

Tự làm thử

import coddy_ai as anthropic  # khi chạy thực tế: 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}]

# Dừng vòng lặp khi đã gọi mô hình MAX_STEPS lần
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 iconTự kiểm tra

Bài học này có một bài trắc nghiệm ngắn. Bắt đầu bài học để trả lời và theo dõi tiến độ.

Tất cả bài học trong Công cụ và agent

Tự luyện tập: Trình biên dịch Python online