에이전트 루프 실행
Coddy AI Engineering 여정의 도구와 에이전트 섹션에 포함된 레슨. 22개 중 17번째.
챌린지
중급에이전트가 호텔도 검색할 수 있도록 하고, 모델이 도구를 요청하는 것을 멈출 때까지 계속 진행하세요. 지금까지 작성한 모든 코드를 유지하세요.
- 설명이
Find a hotel room in a city with its nightly rate이고, 설명이The city to stay in인 필수 문자열 프로퍼티city를 갖는find_hotel이라는 이름의 도구를 추가하세요. TOOLS = {"search_flights": search_flights, "find_hotel": find_hotel}을 추가하고 모든 호출에 두 도구를 모두 전달하세요.- 단일 후속 호출을 루프로 교체하세요.
response.stop_reason이"tool_use"인 동안, 각tool_use블록에 대해Tool:줄을 출력하고,TOOLS에서 해당 블록의 이름에 지정된 함수를 블록의 입력값으로 실행하며, 모든 결과를 하나의 사용자 메시지에 함께 담아 다시 전송하고 모델을 다시 호출하세요. - 루프가 끝난 후,
Agent:와 텍스트 블록의 텍스트를 출력하세요.
예를 들어, 입력이 Find a flight to Rome and a hotel in Lisbon일 때 프로그램은 다음과 같이 출력합니다:
Tool: search_flights {'destination': 'Rome'}
Tool: find_hotel {'city': 'Lisbon'}
Agent: Here is what I found:
- Flight to Rome: 95 dollars
- Hotel in Lisbon: 80 dollars a night모델이 한 응답에서 두 도구를 모두 요청했으므로, 두 결과가 하나의 사용자 메시지에 담겨 다시 전송됩니다.
직접 해보기
import coddy_ai as anthropic # 프로덕션 환경에서: import anthropic
client = anthropic.Anthropic()
FLIGHTS = {"Lisbon": 120, "Rome": 95, "Tokyo": 640, "Oslo": None}
HOTELS = {"Lisbon": 80, "Rome": 110, "Tokyo": 150, "Oslo": 130}
def search_flights(destination):
if destination not in FLIGHTS:
raise ValueError(f"No flights to {destination}")
if FLIGHTS[destination] is None:
raise ConnectionError("The flight service is temporarily unavailable, try again")
return f"Flight to {destination}: {FLIGHTS[destination]} dollars"
def find_hotel(city):
if city not in HOTELS:
raise ValueError(f"No hotels in {city}")
return f"Hotel in {city}: {HOTELS[city]} dollars a night"
def book_flight(destination):
return f"Booked a seat to {destination} for {FLIGHTS[destination]} dollars"
request = input()
# 아래에 코드를 작성하세요
flight_tool = {
"name": "search_flights",
"description": "Search flights to a destination and give the ticket price",
"input_schema": {
"type": "object",
"properties": {"destination": {"type": "string", "description": "The destination city"}},
"required": ["destination"],
},
}
messages = [{"role": "user", "content": request}]
response = client.messages.create(model="claude-opus-5-5", max_tokens=500, tools=[flight_tool], messages=messages)
results = []
for block in response.content:
if block.type == "tool_use":
print(f"Tool: {block.name} {block.input}")
result = search_flights(block.input["destination"])
results.append({"type": "tool_result", "tool_use_id": block.id, "content": result})
messages.append({"role": "assistant", "content": response.content})
messages.append({"role": "user", "content": results})
response = client.messages.create(model="claude-opus-5-5", max_tokens=500, tools=[flight_tool], messages=messages)
for block in response.content:
if block.type == "text":
print("Agent: " + block.text)
도구와 에이전트의 모든 레슨
직접 연습해 보세요: 온라인 Python 컴파일러