Function Calling により、AI モデルは外部ツールや API と連携できるようになり、特定のアクションを実行したり、リアルタイム情報にアクセスしたりできます。この機能は、AI モデルの機能を単純なテキスト生成の範囲を超えて拡張し、より動的で実用的なアプリケーションを可能にします。
サポートされているモデル
以下のモデルはFunction Calling をサポートしています。
クイックスタートガイド
このガイドでは、Function Calling を使用して、ユーザーが指定した場所の現在の天気情報を取得する方法を示します。完全な Python コード例を順を追って説明します。 Function Calling の具体的な API 形式については、API リファレンス Create Chat Completion を参照してください。1. クライアントを初期化する
まず、Novita API key を使用してクライアントを初期化する必要があります。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 endpoint への 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)
ChatCompletionMessage(content="The weather in San Francisco, CA is currently **60 degrees Fahrenheit**. For more detailed information, such as specific conditions (e.g., sunny, cloudy, rainy), you might want to check a local weather app or website. Let me know if you'd like help with anything else!", refusal=None, role='assistant', function_call=None, tool_calls=None)
完全なコード
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."""
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"})
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())
# 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)