Function Calling
- 챗봇이 사용자에게 함수 호출을 위한 params 를 요청하는 기법
- 배송조회를 위해 사용자에게 주문 id 를 요청하는 챗봇 등
- 단, 함수 정의 및 호출은 챗봇이 아닌 개발자가 직접 해야 한다.
- 챗봇이 알려주는 것은 함수가 호출될 준비가 완료되었다는 것이다.
함수 정의
- 고객의 이름과 주문 날짜를 추출하는 함수를 작성하자
from datetime import datetime
def get_delivery_date(order_id):
"""
order_id: str
id of corresponding order
returns: delivery date converted to string format
"""
return datetime.today().strftime("%Y-%m-%d")
def get_customer_name(c_name):
return c_name
- LLM 이 특정 작업을 수행하기 위해 사용하는 도구
- 여기서는 함수를 넣는데, 이외에도 API 호출 도구, DB 조회 도구 등이 포함될 수 있다.
delivery_tool = {
"type": "function",
"function": {
"name": "get_delivery_date",
"description": "고객의 주문에 대한 배송 날짜를 확인합니다. 예를 들어, 고객이 '내 패키지가 어디에 있나요?'라고 물을 때 이 함수를 호출하세요.",
"parameters": {
"type": "object",
"properties": {
"order_id": {"type": "string", "description": "고객의 주문 id"}
},
"required": ["order_id"],
"additionalProperties": False,
},
},
}
parse_name_tool = {
"type": "function",
"function": {
"name": "get_customer_name",
"description": "고객의 이름을 확인합니다. 예를 들어, 고객이 '내 패키지가 어디에 있나요?'라고 물을 때 이 함수를 호출하세요. ",
"parameters": {
"type": "object",
"properties": {"c_name": {"type": "string", "description": "고객의 이름"}},
"required": ["c_name"],
"additionalProperties": False,
},
},
}
tools = [delivery_tool, parse_name_tool]
Message 작성
- LLM 이 정보를 수집할 메시지 기록을 작성하자
messages = []
messages.append(
{
"role": "system",
"content": "당신은 도움이 되는 고객 지원 어시스턴트입니다. 제공된 도구를 사용하여 사용자를 지원하세요.",
}
)
messages.append(
{
"role": "user",
"content": "안녕하세요, 제 이름은 John 입니다. 주문의 배송 날짜를 알려주실 수 있나요?",
}
)
messages.append(
{
"role": "assistant",
"content": "안녕하세요! 제가 도와드릴 수 있습니다. 주문 ID를 알려주시겠어요?",
}
)
messages.append({"role": "user", "content": "제 생각엔 order12345인 것 같아요"})
response = client.chat.completions.create(
model="gpt-4o-mini", messages=messages, tools=tools
)
- LLM 이 tool 을 사용해 도출된 결과인 tool call 은 json 형태로 사용자에게 반환된다.
- 첫 번째 tool 인 delivery_tool 의 tool call 을 조회해보자
print(tool_call[0])
>>> ChatCompletionMessageToolCall(id='call_LMa4EqF3Xy7uxZMFJjFE6pux',
function=Function(arguments='{"c_name": "John"}', name='get_customer_name'),
type='function')
- 우리가 추출하고자 했던 함수 인자는 arguments 에 저장된다.
import json
arguments = []
arguments.append(json.loads(tool_call[0].function.arguments))
arguments.append(json.loads(tool_call[1].function.arguments))
arguments
>>> [{'c_name': 'John'}, {'order_id': 'order12345'}]
- arguments list 에서 keyword argument unpacking 연산자를 이용해 인자를 추출하자
name = get_customer_name(**arguments[0])
date = get_delivery_date(**arguments[1])
name, date
>>> ('John', '2024-10-18')