💡

OpenAI Function Calling と MCP の違いと活用法

に公開

🤖【完全比較】OpenAI Function Calling と MCP の違いと活用法【Pythonサンプル付き】

✅ はじめに

ChatGPTなどのLLM(大規模言語モデル)をアプリケーションに組み込む上で、「関数の呼び出し」や「マルチモーダルな情報処理」は欠かせません。

OpenAIが提供する以下2つの技術は、それを実現するための強力な手段です:

  • 🛠 Function Calling:モデルが外部関数を自動的に呼び出す機能
  • 🌐 Model Context Protocol (MCP):マルチモーダルな情報を構造的に扱う新しい標準仕様

本記事では、それぞれの違いや用途、Pythonコード例を交えてわかりやすく解説します。


📌 目次

  1. Function Callingとは?
  2. MCP(Model Context Protocol)とは?
  3. 両者の比較表
  4. Pythonサンプル:Function Calling
  5. Pythonサンプル:MCP
  6. 応用①:Chain of Thought × Function Calling
  7. 応用②:MCPによるマルチモーダルチャット設計
  8. まとめと今後の展望

🧠 1. Function Callingとは?

OpenAI APIが提供する、モデルが適切な関数を自動的に選び、引数を推論し、呼び出すことができる機能です。

主な用途:

  • 天気取得や計算などの外部処理
  • DBクエリ
  • API連携
  • ツールチェーン構築

📄 2. MCP(Model Context Protocol)とは?

OpenAIが提案するマルチモーダル情報処理のための統一プロトコル。画像、音声、テキスト、関数など、さまざまな情報を意味論付きで構造的に表現できます。

特徴:

  • JSON-LDベースの構造(@context / @type)
  • テキスト・画像・PDF・関数などすべてに対応
  • GPT-4oなどマルチモーダルモデルとの相性◎

📊 3. Function Calling vs MCP 比較表

項目 Function Calling Model Context Protocol (MCP)
目的 関数の自動呼び出し 入力コンテキストの統一仕様
主な形式 JSON Schema JSON-LD
対応内容 関数の選定と引数補完 発話・画像・音声・関数など
モデル対応 GPT-4, GPT-3.5 GPT-4o(マルチモーダル対応)
開発者向け OpenAI API OpenAI + 標準化団体向け
学習難易度 中〜高

🧪 4. Pythonサンプル:Function Calling(基本)

import openai

openai.api_key = "your-api-key"

def get_weather(location):
    return f"{location} は晴れです ☀️"

functions = [
    {
        "name": "get_weather",
        "description": "指定された都市の天気を取得する",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {"type": "string"}
            },
            "required": ["location"]
        }
    }
]

response = openai.ChatCompletion.create(
    model="gpt-4",
    messages=[{"role": "user", "content": "東京の天気は?"}],
    functions=functions,
    function_call="auto"
)

call = response["choices"][0]["message"]["function_call"]
args = eval(call["arguments"])
result = get_weather(**args)

print(result)

🧬 5. Pythonサンプル:MCP構造の基本

import json
from datetime import datetime

mcp_message = {
    "@context": "http://openai.com/mcp/context",
    "@type": "Message",
    "sender": "user",
    "timestamp": datetime.utcnow().isoformat() + "Z",
    "content": {
        "@type": "Text",
        "text": "東京の天気を教えて"
    }
}

print(json.dumps(mcp_message, indent=2, ensure_ascii=False))

🧠 6. 応用①:Chain of Thought × Function Calling

モデルに「考えながら関数を呼ぶ」よう指示する高度な使い方です。

def add(x, y):
    return x + y

functions = [
    {
        "name": "add",
        "description": "2つの数字を足す",
        "parameters": {
            "type": "object",
            "properties": {
                "x": {"type": "integer"},
                "y": {"type": "integer"}
            },
            "required": ["x", "y"]
        }
    }
]

messages = [
    {"role": "system", "content": "君は論理的に考えるAIです。"},
    {"role": "user", "content": "2と3を足すにはどうしたらいい?"},
    {"role": "assistant", "content": "まず2と3を足します。それには add(x=2, y=3) を使います。"}
]

response = openai.ChatCompletion.create(
    model="gpt-4",
    messages=messages,
    functions=functions,
    function_call="auto"
)

call = response["choices"][0]["message"]["function_call"]
args = eval(call["arguments"])
print("答え:", add(**args))

🖼️ 7. 応用②:MCPによるマルチモーダルチャット(画像+発話)

from datetime import datetime
import json

mcp_context = [
    {
        "@type": "Message",
        "sender": "user",
        "timestamp": datetime.utcnow().isoformat() + "Z",
        "content": {
            "@type": "Text",
            "text": "この画像に写っている果物を教えて"
        }
    },
    {
        "@type": "Message",
        "sender": "user",
        "timestamp": datetime.utcnow().isoformat() + "Z",
        "content": {
            "@type": "Image",
            "url": "https://example.com/fruits.jpg"
        }
    }
]

print(json.dumps(mcp_context, indent=2))

この構造を用いれば、GPT-4oなどに画像+質問を同時に渡せるようになります。


✅ 8. まとめ:どう使い分けるか?

シナリオ 推奨技術
API連携・ツール呼び出し Function Calling
マルチモーダルな入出力 MCP
構造化された引数処理 Function Calling
意味論付きコンテキスト MCP
考えながら関数を呼ぶ Function Calling + CoT
LLM間・ツール間連携 MCP(将来的に標準化想定)

🔗 参考リンク


🙌 おわりに

Function CallingとMCPは、それぞれ異なる用途でLLMを強力に拡張する技術です。
用途に応じて正しく選べば、より柔軟で強力なAIアプリケーションの構築が可能になります。

Discussion