함수 호출 (Function Calling)
함수 호출 (Function Calling)
AI 모델이 단순히 텍스트를 만들어 내는 것만으로는 부족할 때가 있어요. 실제로 도구나 API를 불러서 작업을 수행하고 실시간 정보에 접근하고 싶을 때, 함수 호출(Function Calling)이 그 역할을 해요. 모델이 외부 함수를 호출해 더 역동적이고 실용적인 응용을 만들 수 있게 되죠.
개요
함수 호출은 AI 모델이 외부 도구와 API와 상호작용하도록 하여, 특정 동작을 수행하고 실시간 정보에 접근할 수 있게 해요. 이 능력은 모델의 기능을 단순 텍스트 생성 너머로 확장해서 더 역동적이고 실용적인 응용을 가능하게 해요.
지원 모델
현재 함수 호출을 지원하는 모델 목록은 문서의 모델 섹션을 참고하면 돼요.
퀵스타트 가이드
함수 호출의 구체적인 API 형식은 Create Chat Completion API 레퍼런스를 참고하면 돼요.
1. 클라이언트 초기화
먼저 Novita API 키로 클라이언트를 초기화해요.
from openai import OpenAI
import json
client = OpenAI(
base_url="https://api.novita.ai/openai",
# Get the Novita AI API Key from: https://novita.ai/settings/key-management.
api_key="<YOUR Novita AI API Key>",
)
model = "deepseek/deepseek_v3"
2. 호출할 함수 정의
다음으로 모델이 호출할 수 있는 Python 함수를 정의해요. 이 예시에서는 날씨 정보를 가져오는 함수예요.
# Example function to simulate fetching weather data.
def get_weather(location):
"""Retrieves the current weather for a given location."""
print("Calling get_weather function with location: ", location)
# In a real application, you would call an external weather API here.
# This is a simplified example returning hardcoded data.
return json.dumps({"location": location, "temperature": "60 degrees Fahrenheit"})
3. tools와 사용자 메시지로 API 요청 구성
이제 Novita 엔드포인트에 API 요청을 만들게요. 이 요청에는 모델이 사용할 수 있는 함수를 정의하는 tools 파라미터와 사용자 메시지가 포함돼요.
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather of an location, the user shoud supply a location first",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA",
}
},
"required": ["location"]
},
}
},
]
messages = [
{
"role": "user",
"content": "What is the weather in San Francisco?"
}
]
# Let's send the request and print the response.
response = client.chat.completions.create(
model=model,
messages=messages,
tools=tools,
)
# Please check if the response contains tool calls if in production.
tool_call = response.choices[0].message.tool_calls[0]
print(tool_call.model_dump())
출력:
{'id': '0', 'function': {'arguments': '{"location": "San Francisco, CA"}', 'name': 'get_weather'}, 'type': 'function'}
4. 함수 호출 결과로 응답하고 최종 답 얻기
다음 단계는 함수 호출을 처리하는 거예요. get_weather 함수를 실행하고, 그 결과를 다시 모델에 보내 사용자에게 최종 응답을 만들어 내는 방식이에요.
# Ensure tool_call is defined from the previous step
if tool_call:
# Extend conversation history with the assistant's tool call message
messages.append(response.choices[0].message)
function_name = tool_call.function.name
if function_name == "get_weather":
function_args = json.loads(tool_call.function.arguments)
# Execute the function and get the response
function_response = get_weather(
location=function_args.get("location"))
# Append the function response to the messages
messages.append(
{
"tool_call_id": tool_call.id,
"role": "tool",
"content": function_response,
}
)
# Get the final response from the model, now with the function result
answer_response = client.chat.completions.create(
model=model,
messages=messages,
# Note: Do not include tools parameter here
)
print(answer_response.choices[0].message)
완전한 코드
위 단계를 하나로 모은 전체 코드예요. 함수 호출 응답을 확인하고, 함수를 실행해 그 결과를 다시 모델에 보내 최종 답을 얻는 흐름이에요.
from openai import OpenAI
import json
client = OpenAI(
base_url="https://api.novita.ai/openai",
# Get the Novita AI API Key from: https://novita.ai/settings/key-management.
api_key="<YOUR Novita AI API Key>",
)
model = "deepseek/deepseek_v3"
# Example function to simulate fetching weather data.
def get_weather(location):
"""Retrieves the current weather for a given location."""
return json.dumps({"location": location, "temperature": "60 degrees Fahrenheit"})
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather of an location, the user shoud supply a location first",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g. San Francisco, CA",
}
},
"required": ["location"]
},
}
},
]
messages = [
{
"role": "user",
"content": "What is the weather in San Francisco?"
}
]
response = client.chat.completions.create(
model=model,
messages=messages,
tools=tools,
)
tool_call = response.choices[0].message.tool_calls[0]
print(tool_call.model_dump())
if tool_call:
messages.append(response.choices[0].message)
function_name = tool_call.function.name
if function_name == "get_weather":
function_args = json.loads(tool_call.function.arguments)
function_response = get_weather(
location=function_args.get("location"))
messages.append(
{
"tool_call_id": tool_call.id,
"role": "tool",
"content": function_response,
}
)
answer_response = client.chat.completions.create(
model=model,
messages=messages,
# Note: Do not include tools parameter here
)
print(answer_response.choices[0].message)