에이전트 루프
Coddy AI Engineering 여정의 도구와 에이전트 섹션에 포함된 레슨. 22개 중 6번째.
일부 요청은 둘 이상의 도구 호출이 필요합니다. 램프의 가격을 유로화로 구하려면 모델은 먼저 가격을 알아야 하며, 그 후에야 환전을 요청할 수 있습니다. 두 번째 호출은 첫 번째 결과에 의존하기 때문에 두 호출을 동시에 계획할 수 없습니다.
에이전트 루프가 이를 처리합니다: 모델을 호출하고, 모델이 stop_reason == "tool_use"로 응답하는 동안 요청한 도구를 실행하고 결과를 다시 전송한 뒤 모델을 다시 호출합니다. stop reason이 그 외의 다른 것일 경우, 텍스트 블록에 최종 답변이 담깁니다.
response = client.messages.create(model="claude-opus-5-5", max_tokens=500, tools=TOOLS, messages=messages)
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)각 패스는 두 개의 턴, 즉 모델의 도구 호출과 여러분의 결과를 추가합니다. 리스트는 점점 늘어나며, 모델은 매 호출마다 이 전체를 읽습니다. 프로덕션 코드는 흔히 이 루프를 SDK의 도구 러너(client.beta.messages.tool_runner)나 Managed Agents에 맡깁니다. 이를 직접 한 번 작성해 보면 이들이 대신 무엇을 해주는지 알 수 있습니다.
챌린지
중급상점 가격 보조 프로그램을 위한 에이전트 루프를 작성하세요. 스타터 코드에는 두 개의 도구, FUNCTIONS에 정의된 구현 함수들, 그리고 첫 번째 메시지가 정의되어 있습니다.
model="claude-opus-5-5",max_tokens=500,tools=TOOLS및 메시지를 사용하여 모델을 호출하세요.- 중단 사유가
"tool_use"인 동안: 어시스턴트 턴을 추가하고, 모든tool_use블록을FUNCTIONS[block.name](**block.input)으로 실행하며 각각에 대해Tool:, 이름, 공백, 입력 딕셔너리를 출력한 다음, 모든 결과를 하나의 사용자 메시지로 추가하고 모델을 다시 호출하세요. Answer:와 최종 응답 텍스트를 출력하세요.Steps:와 모델을 호출한 횟수를 출력하세요.
예를 들어, 입력 What is the price of the mug in yen?에 대해 프로그램은 다음과 같이 출력합니다:
Tool: get_price {'item': 'mug'}
Tool: convert_currency {'amount': 8, 'currency': 'JPY'}
Answer: Here is what I found:
- The mug costs 8 dollars
- 8 dollars is 1200.00 JPY
Steps: 3직접 해보기
import coddy_ai as anthropic # 프로덕션 환경: import anthropic
client = anthropic.Anthropic()
PRICES = {"lamp": 40, "desk": 120, "chair": 65, "mug": 8}
RATES = {"EUR": 0.92, "GBP": 0.79, "JPY": 150.0}
def get_price(item):
if item in PRICES:
return f"The {item} costs {PRICES[item]} dollars"
return f"No price for {item}"
def convert_currency(amount, currency):
return f"{amount} dollars is {amount * RATES[currency]:.2f} {currency}"
TOOLS = [
{
"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"],
},
},
{
"name": "convert_currency",
"description": "Convert a dollar amount to another currency",
"input_schema": {
"type": "object",
"properties": {
"amount": {"type": "number", "description": "The amount in dollars"},
"currency": {"type": "string", "description": "The currency code, such as EUR"},
},
"required": ["amount", "currency"],
},
},
]
FUNCTIONS = {"get_price": get_price, "convert_currency": convert_currency}
request = input()
messages = [{"role": "user", "content": request}]
# 에이전트 루프 실행: 모든 호출마다 "Tool: <name> <input>" 출력,
# 그 다음 "Answer: "와 최종 텍스트, 이어서 "Steps: "와 API 호출 횟수를 출력
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
도구와 에이전트의 모든 레슨
직접 연습해 보세요: 온라인 Python 컴파일러