Function Calling은 LLM이 외부 함수를 호출할 수 있게 해주는 OpenAI의 기능입니다. 2023년 6월에 처음 도입되었으며, GPT-5 ~ GPT-3.5-turbo에서 사용 가능합니다.
작동 원리
LLM은 실제로 함수를 실행하지 않습니다. 대신:
함수 설명을 읽고
**”이 함수를 이런 인자로 실행하면 좋겠어요”**라고 제안
개발자가 실제 실행
결과를 받아서 자연어로 변환
Tool 정의 방법
OpenAI API에서는 함수를 “Tool”이라고 부릅니다:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
TOOLS = [ { "type": "function", "function": { "name": "get_weather", "description": "A function to get the weather of a city", "parameters": { "type": "object", "properties": { "city": { "type": "string", "description": "The name of the city" } }, "required": ["city"] } } } ]
# 4. Tool 정의 TOOLS = [ { "type": "function", "function": { "name": "get_weather", "description": "A function to get the weather of a city", "parameters": { "type": "object", "properties": { "city": { "type": "string", "description": "The name of the city" } }, "required": ["city"] } } } ]
# 5. AI 응답 처리 함수 defprocess_ai_response(message: ChatCompletionMessage): """AI 응답을 처리하고 필요시 함수를 실행"""
# Tool 호출이 있는 경우 if message.tool_calls: # AI의 tool_calls를 messages에 추가 messages.append({ "role": "assistant", "content": message.content or"", "tool_calls": [ { "id": tool_call.id, "type": "function", "function": { "name": tool_call.function.name, "arguments": tool_call.function.arguments } } for tool_call in message.tool_calls ] })
# 각 tool_call 실행 for tool_call in message.tool_calls: function_name = tool_call.function.name arguments = tool_call.function.arguments
print(f"Calling function: {function_name} with arguments: {arguments}")
User: My name is Chaehyeon AI: Nice to meet you, Chaehyeon!
User: What is my name? AI: Your name is Chaehyeon
User: What is the weather in Seoul? Calling function: get_weather with arguments: {"city":"Seoul"} Ran function: get_weather with result: 15 degrees Celsius. AI: Chaehyeon, the current temperature in Seoul is 15°C
[ {"role": "user", "content": "My name is Chaehyeon"}, {"role": "assistant", "content": "Nice to meet you, Chaehyeon!"}, {"role": "user", "content": "What is my name?"}, {"role": "assistant", "content": "Your name is Chaehyeon"}, {"role": "user", "content": "What is the weather in Seoul?"}, { "role": "assistant", "content": "", "tool_calls": [{ "id": "call_m4kzxZOWvelD5Mc5iVUifI8C", "type": "function", "function": { "name": "get_weather", "arguments": '{"city":"Seoul"}' } }] }, { "role": "tool", "tool_call_id": "call_m4kzxZOWvelD5Mc5iVUifI8C", "name": "get_weather", "content": "15 degrees Celsius." }, { "role": "assistant", "content": "Chaehyeon, the current temperature in Seoul is 15°C" } ]
핵심 포인트
재귀 호출: process_ai_response() 함수 내에서 call_ai()를 다시 호출합니다. 이는 AI가 함수 실행 결과를 읽고 최종 응답을 생성하기 위함입니다.
tool_call_id: 각 tool call에는 고유 ID가 있으며, 함수 실행 결과를 반환할 때 이 ID를 반드시 포함해야 합니다.