5. Tool
Last updated
Last updated
# 곱셈연산을 지원하는 함수.
def multiply(a: int, b: int) -> int:
"""
두 정수 a와 b를 곱합니다. 이 도구는 복잡한 곱셈 계산에 사용됩니다.
Args:
a: 첫 번째 정수
b: 두 번째 정수
"""
return a * b
# 2. 도구 스키마 정의(Tool Schema)
tools = [
{
"type": "function",
"function": {
"name": "multiply",
"description": "두 정수 a와 b를 곱합니다.",
"parameters": {
"type": "object",
"properties": {
"a": {"type": "integer", "description": "첫 번째 정수"},
"b": {"type": "integer", "description": "두 번째 정수"}
},
"required": ["a", "b"]
}
}
}
]# llm 요청시 tool을 함께 전달.
user_query = "137에 45를 곱하면 얼마야?"
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "user", "content": user_query}
],
tools=tools,
tool_choice="auto" # 모델이 알아서 도구 쓸지 판단
)
message = response.choices[0].message
print("=== 1차 응답 ===")
print(message)import json
if message.tool_calls:
tool_call = message.tool_calls[0]
tool_name = tool_call.function.name
tool_args = json.loads(tool_call.function.arguments)
tool_call_id = tool_call.id
print("\n=== 도구 실행 ===")
print("도구:", tool_name)
print("인자:", tool_args)
if tool_name == "multiply":
tool_result = multiply(**tool_args)
print("결과:", tool_result)
second_response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "user", "content": user_query},
message, # LLM의 tool_call 메시지
{
"role": "tool",
"tool_call_id": tool_call_id,
"content": str(tool_result)
}
]
)
final_message = second_response.choices[0].message
print("\n=== 최종 응답 ===")
print(final_message.content)