도구 입력 검증하기
Coddy AI Engineering 여정의 도구와 에이전트 섹션에 포함된 레슨. 22개 중 12번째.
도구 인자는 모델에서 들어오므로 외부에서 들어오는 모든 입력처럼 취급하여, 도구가 실행되기 전에 확인하세요. 스키마는 guests가 정수라는 것을 알려줄 수 있지만, 테이블 좌석이 최대 8개라거나 주문이 반드시 존재해야 함을 말해줄 수는 없습니다.
def check_booking(guests):
if not isinstance(guests, int):
return "guests must be a whole number."
if guests < 1 or guests > 8:
return "Tables seat 1 to 8 guests."
return Nonecheck_booking(12)는 Tables seat 1 to 8 guests.를 반환하고 check_booking(4)는 None을 반환합니다.
검사가 실패하면 도구를 실행하지 마세요. 모델이 사용자에게 알리거나 다른 인자를 시도할 수 있도록 "is_error": True와 함께 tool_result로 메시지를 다시 보내세요. 모델을 위한 메시지를 작성하세요. 무엇이 잘못되었고 무엇이 허용되는지 설명해야 합니다. 도구에 "strict": True를 추가하면(스키마에 "additionalProperties": False 포함) API가 입력이 스키마와 일치함을 보장해주므로 타입 검사의 수고는 줄여주지만, 비즈니스 규칙까지 검사해주지는 않습니다.
챌린지
중급상점의 어시스턴트는 모델이 요청하는 모든 금액을 환불합니다. refund_order가 실행되기 전에 검사를 추가하세요.
check_refund(order_id, amount)를 채우세요. 다음 순서대로 반환해야 합니다:- id가
ORDERS에 존재하지 않을 때Order <order_id> does not exist.; - amount가 0 이하일 때
The refund amount must be more than 0.; - amount가
ORDERS에 있는 주문 가격보다 클 때Order <order_id> only cost <price> dollars.; - 그 외의 경우에는
None.
- id가
- 루프 안에서 도구의 입력으로
check_refund를 호출하세요. 메시지가 반환되면"is_error": True와 함께 해당 메시지를 결과로 전송하고 환불을 진행하지 마세요.
예를 들어, Refund order 1311 for 25 dollars 입력에 대해 프로그램은 다음과 같이 출력합니다:
Tool: refund_order {'order_id': 1311, 'amount': 25}
Answer: Sorry, I could not finish: Order 1311 only cost 18.5 dollars.직접 해보기
import coddy_ai as anthropic # 프로덕션 환경: import anthropic
client = anthropic.Anthropic()
ORDERS = {1182: 64.0, 1205: 120.0, 1311: 18.5}
TOOLS = [
{
"name": "refund_order",
"description": "Refund part or all of an order. Use it when a customer asks for money back on an order.",
"input_schema": {
"type": "object",
"properties": {
"order_id": {"type": "integer", "description": "The order number"},
"amount": {"type": "number", "description": "The amount to refund, in dollars"},
},
"required": ["order_id", "amount"],
},
}
]
def refund_order(order_id, amount):
return f"Refunded {amount} dollars on order {order_id}."
def check_refund(order_id, amount):
# 오류 메시지를 반환하거나, 환불을 진행할 수 있는 경우 None을 반환합니다.
return None
request = input()
messages = [{"role": "user", "content": request}]
response = client.messages.create(model="claude-opus-5-5", max_tokens=300, tools=TOOLS, messages=messages)
while response.stop_reason == "tool_use":
messages.append({"role": "assistant", "content": response.content})
results = []
for block in response.content:
if block.type == "tool_use":
print(f"Tool: {block.name} {block.input}")
results.append({"type": "tool_result", "tool_use_id": block.id, "content": refund_order(**block.input)})
messages.append({"role": "user", "content": results})
response = client.messages.create(model="claude-opus-5-5", max_tokens=300, tools=TOOLS, messages=messages)
for block in response.content:
if block.type == "text":
print("Answer: " + block.text)
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
도구와 에이전트의 모든 레슨
직접 연습해 보세요: 온라인 Python 컴파일러