도구 간 선택하기
Coddy AI Engineering 여정의 도구와 에이전트 섹션에 포함된 레슨. 22개 중 4번째.
여러 도구를 전달하면 모델은 각 도구의 이름과 설명을 읽고 요청에 맞는 도구를 선택합니다. 그런 다음 코드에서 모델이 선택한 도구를 실행해야 합니다. block.name에 대한 긴 if/elif 체인도 작동하지만, 도구 이름에서 함수로 매핑되는 dict를 사용하면 확장하기가 더 좋습니다. 도구당 한 줄이면 됩니다.
functions = {"add": add, "multiply": multiply}
name = "multiply"
arguments = {"a": 6, "b": 7}
print(functions[name](**arguments))이것은 42를 출력합니다. **arguments는 dict의 키를 키워드 인자로 전달하므로, block.input은 매개변수가 스키마의 속성 이름을 가지는 함수에 바로 들어맞습니다.
모든 도구의 이름을 딕셔너리에 보관하세요: 모델은 여러분이 나열한 도구만 호출하므로, 누락된 항목은 모델의 선택이 아니라 프로그램의 버그입니다. 적합한 도구가 없으면 모델은 텍스트로 답변하며 실행할 작업이 없습니다.
챌린지
중급기본 코드에서는 모델에 날씨, 현지 시간, 가격이라는 세 가지 툴이 주어집니다. 모델이 선택하는 것을 실행하세요.
- 각 툴 이름을 해당하는 Python 함수에 매핑하는 dict를 만드세요.
- 타입이
"tool_use"인 각 블록에 대해Tool:과 그 이름을 출력한 다음, dict에서 해당 함수를**block.input으로 실행하고Result:과 반환값을 출력하세요. - 타입이
"text"인 블록에 대해Answer:과 그 텍스트를 출력하세요.
예를 들어 What time is it in Rome? 입력에 대해 프로그램은 다음과 같이 출력합니다:
Tool: get_time
Result: Rome: 14:05직접 해보기
import coddy_ai as anthropic # 프로덕션 환경: import anthropic
client = anthropic.Anthropic()
WEATHER = {"Rome": "21 C and sunny", "Tokyo": "16 C and cloudy", "Oslo": "4 C and windy"}
TIMES = {"Rome": "14:05", "Tokyo": "22:05", "Oslo": "14:05"}
PRICES = {"lamp": 40, "desk": 120}
def get_weather(city):
return f"{city}: {WEATHER.get(city, 'no data')}"
def get_time(city):
return f"{city}: {TIMES.get(city, 'no data')}"
def get_price(item):
return f"{item}: {PRICES.get(item, 'no price')} dollars"
def city_schema():
return {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}
tools = [
{"name": "get_weather", "description": "Get the current weather for a city", "input_schema": city_schema()},
{"name": "get_time", "description": "Get the current local time in a city", "input_schema": city_schema()},
{"name": "get_price", "description": "Look up the price of an item in dollars",
"input_schema": {"type": "object", "properties": {"item": {"type": "string"}}, "required": ["item"]}},
]
question = input()
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=300,
tools=tools,
messages=[{"role": "user", "content": question}],
)
# 1. 각 도구 이름을 해당하는 Python 함수에 매핑하는 dict를 만듭니다.
# 2. 각 tool_use 블록에 대해 "Tool: <name>"을 출력하고, **block.input으로 함수를 실행하며
# "Result: <what it returns>"를 출력합니다.
# 3. 모델이 대신 텍스트로 응답한 경우 "Answer: <text>"를 출력합니다.
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
도구와 에이전트의 모든 레슨
직접 연습해 보세요: 온라인 Python 컴파일러