요약: 쇼핑 어시스턴트
Coddy AI Engineering 여정의 도구와 에이전트 섹션에 포함된 레슨. 22개 중 10번째.
챌린지
어려움쇼핑 도우미의 에이전트 루프를 작성하세요. 시작 코드에는 두 개의 도구, FUNCTIONS에 정의된 도구 실행 함수, MAX_STEPS, 그리고 첫 번째 메시지가 정의되어 있습니다. 두 함수 모두 알 수 없는 제품에 대해 ValueError를 발생시키며, check_stock은 창고 시스템이 중단되었을 때 TimeoutError를 발생시킵니다.
run_tool(block)을 작성하세요:FUNCTIONS[block.name](**block.input)을 실행하고 해당tool_result를 반환하세요.ValueError및TimeoutError를 예외 처리하여 메시지와"is_error": True가 포함된 오류 결과를 반환하세요. 정상 결과의 경우Tool: <name> <input> -> <output>를 출력하고, 오류의 경우Tool: <name> <input> -> error: <message>를 출력하세요.- 모델을 호출하고(
model="claude-opus-5-5",max_tokens=500,tools=TOOLS) 모델이 도구를 요청하는 동안 루프를 실행하세요: assistant 턴을 추가하고, 모든 결과를 하나의 user 메시지로 전송한 뒤, 다시 호출하세요. - 모델을
MAX_STEPS번 호출했을 때 루프를 중지한 다음Stopped: no answer after 4 steps를 출력하세요. - 최종 텍스트가 있는 경우
Answer:와 최종 텍스트를 출력한 다음,Steps:와 호출 횟수를 출력하세요.
예를 들어 Check stock for the desk lamp and the price of the desk lamp 입력에 대해 프로그램은 다음을 출력합니다:
Tool: check_stock {'product': 'desk lamp'} -> desk lamp: 12 in stock
Tool: get_price {'item': 'desk lamp'} -> desk lamp: 40 dollars
Answer: Here is what I found:
- desk lamp: 12 in stock
- desk lamp: 40 dollars
Steps: 2직접 해보기
import coddy_ai as anthropic # 프로덕션 환경에서는: import anthropic
client = anthropic.Anthropic()
MAX_STEPS = 4
STOCK = {"desk lamp": 12, "bookshelf": 5, "office chair": 0}
PRICES = {"desk lamp": 40, "bookshelf": 85, "office chair": 65, "garden bench": 150}
def check_stock(product):
if product == "garden bench":
raise TimeoutError("The warehouse system is temporarily unavailable, try again")
if product not in STOCK:
raise ValueError(f"Unknown product: {product}")
return f"{product}: {STOCK[product]} in stock"
def get_price(item):
if item not in PRICES:
raise ValueError(f"No price for {item}")
return f"{item}: {PRICES[item]} dollars"
TOOLS = [
{
"name": "check_stock",
"description": "Check how many units of a product are in stock",
"input_schema": {
"type": "object",
"properties": {"product": {"type": "string", "description": "The product name"}},
"required": ["product"],
},
},
{
"name": "get_price",
"description": "Look up the price of an item in dollars",
"input_schema": {
"type": "object",
"properties": {"item": {"type": "string", "description": "The item to price"}},
"required": ["item"],
},
},
]
FUNCTIONS = {"check_stock": check_stock, "get_price": get_price}
request = input()
messages = [{"role": "user", "content": request}]
# 아래에 코드를 작성하세요
도구와 에이전트의 모든 레슨
직접 연습해 보세요: 온라인 Python 컴파일러