あなたが求めるものを手に入れていない誰かと話したことがありますか? あなたがあなたの友人に6時に空港へ行く必要があると伝えるときのように、彼らは代わりに彼らの好きな空港のレストランについてあなたに話し始めるのですか? それは基本的に機能呼び出しの前にプログラミングのようなものです。
呼び出しの機能とは?
機能呼び出しは、AIがタスクを完了するために外部のツールやサービスを使用する必要があることを理解するときです. それは、あなたが何を望んでいるかを理解するだけでなく、天候を確認するために携帯電話を外すときを知っているスマートアシスタントを持っているように、方向を調べ、またはタクシーを呼ぶ。
技術的には、関数呼び出しは、AIモデルが特定の関数を使用するときに、どのパラメータを渡すべきか、データを正しくフォーマットする方法を識別することを可能にします - すべて自然言語の指示から。
『The Dark Ages: Before Function Calling』
機能呼び出しの前に、物事は...混乱していました。AIが外部ツールを使用することを望んでいたら、あなたは2つの同様に不快なオプションを持っていました。
-
Train the AI to generate exact API calls (which often went wrong)
-
Write complex code to parse AI responses and extract parameters
あなたは、「ニューヨークの天気データが必要だ」というようなことを言い、AIはあなたが必要とする実際のデータではなく、天気に関するテキストで応答します。
レストランの予約を予約することを目的としたチャットボットを構築することを覚えています。機能の呼び出しがなければ、実際に予約システムに接続することなく、「テーブルを予約しました!」とユーザーに喜んで言います。
なぜ機能が事柄を呼ぶのか
機能呼び出しは、人間の言語とコンピュータシステムの間のギャップを橋渡します。
-
It's more reliable - the AI structures data exactly as functions need it
-
It's more capable - an AI can access real-time data, control devices, or run calculations
-
It's more natural - users can make requests in plain language
機能呼び出しは、AIにツールボックスへのアクセスを与えるように考えます。以前は、ハンマーについてだけ話すことができます。
シンプルに考える方法
あなたが「オーブミルクと中型のラテが欲しい」と言ったとき、あなたは本質的にバリスタを「呼ぶ」のです。
この機能は、次のように見えるかもしれません:
make_coffee(size="medium", drink_type="latte", milk="oat")
バーテンダーは知っている:
-
Identify the function needed (make a drink)
-
Extract the parameters (size, type, milk choice)
-
Execute the function (make the coffee)
-
Return the result (your drink)
機能呼び出しがなければ、「オーブミルクを含む中型ラテは美味しい!」という答えを得るでしょうが、実際のコーヒーはありません。Hope you get the idea !
オリジナルタイトル: The Core Mechanics Behind Function Calling
その中心に、機能呼び出しは、いくつかの技術革新が一緒に働いているため働きます。
-
Structured Function Definitions: When you define functions for an AI model to use, you provide a clear schema that includes the function name, description, and parameter specifications with their types and requirements. This JSON schema helps the model understand not just what the function does, but exactly what information it needs to execute properly.
-
Intent Recognition: The AI model analyzes user input to determine when a function should be called. Modern models like GPT-4 can recognize when a user's request could be satisfied by calling an external function, even when the user doesn't explicitly ask for it.
-
Parameter Extraction: The model identifies and extracts relevant parameters from natural language, converting them into the structured format required by the function. For example, when someone asks about Microsoft stock, the model knows to extract "MSFT" as the ticker parameter.
-
Response Formatting: After a function executes, the model receives the result and incorporates it into a natural language response, creating a seamless experience for the user.
-
Context Awareness: The model maintains context throughout the conversation, allowing it to use previous function calls and responses to inform new function calls.
️ Scaffolding Code for Function Calling(機能呼び出しのためのコード)
以下は、OpenAI API を使用して機能呼び出しを開始するために使用できるテンプレートです。
from openai import OpenAI
import json
# Initialize the client
client = OpenAI()
# Define your functions
functions = [
{
"type": "function",
"function": {
"name": "your_function_name",
"description": "Description of what this function does",
"parameters": {
"type": "object",
"properties": {
"param1": {
"type": "string",
"description": "Description of parameter 1"
},
"param2": {
"type": "integer",
"description": "Description of parameter 2"
}
},
"required": ["param1"]
}
}
}
]
# Your actual implementation of the function
def your_function_name(param1, param2=None):
# Your code here
result = f"Did something with {param1}"
if param2:
result += f" and {param2}"
return result
# Process messages and handle function calls
def process_with_function_calling(messages):
# Get response from the model
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=functions,
tool_choice="auto"
)
response_message = response.choices[0].message
# Check if the model wants to call a function
if response_message.tool_calls:
# Append the model's response to messages
messages.append(response_message)
# Process each function call
for tool_call in response_message.tool_calls:
function_name = tool_call.function.name
function_args = json.loads(tool_call.function.arguments)
# Call the function
if function_name == "your_function_name":
function_response = your_function_name(
function_args.get("param1"),
function_args.get("param2")
)
# Append the function response to messages
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"name": function_name,
"content": function_response
})
# Get a new response from the model
second_response = client.chat.completions.create(
model="gpt-4o",
messages=messages
)
return second_response.choices[0].message.content
return response_message.content
# Example usage
messages = [{"role": "user", "content": "Your user query here"}]
result = process_with_function_calling(messages)
print(result)
☀️ 仕事の例:天気チェック
これを、Azure OpenAI を使用するシンプルな天候チェック機能で実践してみましょう。
from openai import AzureOpenAI
import json
import requests
# Initialize the Azure OpenAI client
client = AzureOpenAI(
api_key="your key",
api_version="2024-10-21", # Make sure to use a version that supports function calling
azure_endpoint="your endpoint"
)
# Define the weather function
weather_functions = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather for a location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City name, e.g., 'San Francisco'"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "Temperature unit"
}
},
"required": ["location"]
}
}
}
]
# Implement the weather function
def get_weather(location, unit="celsius"):
# In a real app, you'd call a weather API here
# This is a mock implementation
weather_data = {
"San Francisco": {"temp": 18, "condition": "Foggy"},
"New York": {"temp": 22, "condition": "Partly Cloudy"},
"London": {"temp": 15, "condition": "Rainy"},
"Tokyo": {"temp": 24, "condition": "Sunny"}
}
# Get data for the location or return a default
data = weather_data.get(location, {"temp": 20, "condition": "Unknown"})
# Convert temperature if needed
temp = data["temp"]
if unit == "fahrenheit":
temp = (temp * 9/5) + 32
return f"It's currently {data['condition']} and {temp}°{'F' if unit == 'fahrenheit' else 'C'} in {location}."
# Process messages with weather function
def check_weather(user_query):
messages = [{"role": "user", "content": user_query}]
# Get response from the model
response = client.chat.completions.create(
model="gpt-4o-mini", # The name you gave your deployment
messages=[{"role": "user", "content": user_query}],
tools=weather_functions,
tool_choice="auto"
)
response_message = response.choices[0].message
# Check if the model wants to call the weather function
if response_message.tool_calls:
# Append the model's response to messages
messages.append(response_message)
# Process each function call
for tool_call in response_message.tool_calls:
function_name = tool_call.function.name
function_args = json.loads(tool_call.function.arguments)
# Call the weather function
if function_name == "get_weather":
function_response = get_weather(
function_args.get("location"),
function_args.get("unit", "celsius")
)
# Append the function response to messages
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"name": function_name,
"content": function_response
})
# Get a new response from the model
second_response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages
)
return second_response.choices[0].message.content
return response_message.content
# Try it out
result = check_weather("What's the weather like in Tokyo right now?")
print(result)
このコードを「今、東京の天気はどうですか?」という質問で実行すると、AIは次のようになります。
-
Recognize it needs weather data
-
Call the
get_weather
function with "Tokyo" as the location -
Receive the weather data
-
Generate a natural response with the information
推測したり天気情報を作成するのではなく、機能を通じて実際のデータを提供しています。
️ The Output: Weather Function Calling in Action オリジナルタイトル
「東京の現在の天気はどうですか?」というクエリで天気例を実行すると、呼び出し機能の魔法が生き返ります。{"location": "Tokyo", "unit": "celsius"}
このフォーマットされた JSON は、当社のget_weather
この機能は、私たちが定義した「24°C」の温度と「Sunny」の条件の模天候データを取得します。
Azure OpenAI の代わりに OpenAI を使用したいですか?
主な違いは、OpenAIそしてAzure OpenAI implementation lies in how you initialize the clientOpenAI では、標準クライアントと直接の API キーを使用しますが、Azure OpenAI ではその特定のクライアントと追加のパラメータが必要です。azure_endpoint
そしてapi_version
機能呼び出しを行う際に、OpenAI はモデルを標準名で参照しますが、Azure OpenAI では、Azure ポータルで作成した展開名を使用する必要があります。
以下はコード比較です。
# Standard OpenAI implementation
from openai import OpenAI
# Initialize the client
client = OpenAI(
api_key="your-openai-api-key"
)
# Make an API call
response = client.chat.completions.create(
model="gpt-4o", # Standard model name
messages=[{"role": "user", "content": "What's the weather in Seattle?"}],
tools=functions,
tool_choice="auto"
)
# Azure OpenAI implementation
from openai import AzureOpenAI
# Initialize the client - requires more parameters
client = AzureOpenAI(
api_key="your-azure-openai-api-key",
api_version="2023-07-01-preview", # Azure-specific
azure_endpoint="https://your-resource-name.openai.azure.com" # Azure-specific
)
# Make an API call
response = client.chat.completions.create(
model="your-deployed-model-name", # The name you gave your deployment in Azure
messages=[{"role": "user", "content": "What's the weather in Seattle?"}],
tools=functions,
tool_choice="auto"
)
新たな可能性の世界
機能呼び出しはすべてを変えました. AI は現在:
-
Book real appointments
-
Look up real-time data
-
Control smart home devices
-
Query databases
-
Process payments
-
And much more
それは、世界について話せるAIと、実際に世界と対話できるAIの違いです。
次回、今日のニュースをチャットボットに聞くか、ライトを点灯するかを尋ねると、それは舞台の後ろで魔法が起こる機能の呼び出しです。
↓ 概要
機能呼び出しは、人間の言語とコンピュータシステムの間のギャップをブリッジします。それによってAIは、適切にフォーマットされたデータを使用して外部ツールやサービスを呼び出すときに理解することができます - OpenAI を直接使用するか、Azure OpenAI Service を使用しているかを問わず。我々は、AI が被動的な応答者からアクティブなエージェントにどのように変換するかを調査しました。
展望
機能呼び出しの本当のパワーは、今日できることではなく、明日できることである。より多くのシステムがAPIエンドポイントを露出し、認証とセキュリティ基準が進化するにつれて、私たちは自然言語がデジタルシステムの普遍的なインターフェイスになる世界に近づいています。
最後の考え方
本当の革命は、AIが行動を起こすことだけではなく、思考と行動の間の障壁が解消されることである。Function callingは単に技術的な機能ではなく、AIがページを超えて世界に突入し、観察者から参加者へと変化した瞬間です。