단계 제한
Coddy AI Engineering 여정의 도구와 에이전트 섹션에 포함된 레슨. 22개 중 9번째.
에이전트 루프는 모델이 도구 요청을 멈출 때 종료되지만, 반드시 멈춘다는 보장은 없습니다. 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라면 제한 때문에 중단되었으며 표시할 답변이 없음을 의미합니다. 아무것도 출력하지 않는 대신 사용자에게 이 사실을 알려주세요. 재시도는 종종 유용합니다. 한 번 시간 초과가 발생한 서비스라도 다음 시도에서는 응답할 수 있습니다. 제한을 두면 루프가 재시도하면서도 결국 종료될 수 있습니다. 프로덕션 에이전트 역시 같은 방식으로 토큰과 시간을 제한합니다.
챌린지
중급스타터 코드의 레스토랑 에이전트는 예약 시스템 오류가 계속될 때 모델이 매번 재시도하여 무한히 실행됩니다. 단계 제한을 추가하세요.
- 루프의 가장 위에서
steps가MAX_STEPS와 같을 때break합니다. - 루프가 끝난 후, 중단 이유가 여전히
"tool_use"이면Stopped: no answer after 5 steps를 출력합니다(MAX_STEPS사용). - 답변이 있을 때 답변을 출력하는 부분과 단계를 출력하는 부분은 그대로 유지합니다.
예를 들어, 입력 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}")
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
도구와 에이전트의 모든 레슨
직접 연습해 보세요: 온라인 Python 컴파일러