2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Azure OpenAI でFunction Callingを試してみた

Posted at

はじめに

株式会社メソドロジックの佐藤と申します。
現在は、大手企業様向けに、大規模言語モデル(LLM)活用支援を担当させていただいています。

本記事では、私自身の勉強も兼ねてFunction Callingのサンプル実装を行った結果をまとめます。
AzureOpenAIを使いつつ、ローカル環境で簡単に試せる形をご紹介しますので、これからRAGを拡張してみたい方のご参考になれば幸いです。

この記事で行うこと

本記事では、以下の流れでFunction Callingの実装を紹介します。

サンプル環境の準備
SQLiteで簡易的なCRM/チケット管理DBを用意し、LangChainのツールとして連携できる形にします。

Azure OpenAI × LangChainによる実装
Function Callingを用いて顧客情報参照/チケット発行/Teams通知を実現します。

実行結果とまとめ
実行例を紹介しながら、今後の拡張アイデアについて整理します。

Function Callingとは

Function Callingは、OpenAI が 2023年6月に ChatGPT(GPT-3.5 / GPT-4)向けに公開した機能で、「モデルが出力をJSON形式で返し、それをアプリ側が関数呼び出しに使える」仕組みです。

OpenAI公式ブログ記事

Function Callingを組み合わせることで、LLMは検索結果を参照したうえで外部APIやDBを操作するアクションを実行できます。

例えば顧客サポートのシナリオでは:

  • 顧客IDを入力すると、CRMから契約状況を取得
  • 必要ならチケットを自動で発行
  • 重要案件はTeamsへ通知

という一連の処理を、自然言語で指示するだけで実行可能になります。

実装構成

今回のデモでは以下を用意しました。

  • LLM: Azure OpenAI(gpt-4o)
  • LangChain: Agent + Tool呼び出し
  • 疑似DB: SQLiteで顧客情報・チケット管理
  • ツール関数:
    • get_customer_info(顧客情報を取得)
    • create_ticket(チケットを発行)
    • notify_teams(通知送信)

実装例コード

agent.py(抜粋)

from langchain_openai import AzureChatOpenAI
from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.messages import HumanMessage, AIMessage
from tools import get_customer_info, create_ticket, notify_teams

tools = [get_customer_info, create_ticket, notify_teams]

SYSTEM = """あなたはサポート業務を手伝うアシスタントです。
ユーザーの意図に応じてツールを呼び出してください。
- 顧客IDがあれば get_customer_info
- 障害/依頼があれば create_ticket
- 重要なら notify_teams
"""

prompt = ChatPromptTemplate.from_messages([
    ("system", SYSTEM),
    MessagesPlaceholder("chat_history"),
    ("human", "{input}"),
    MessagesPlaceholder("agent_scratchpad"),
])

llm = AzureChatOpenAI(
    azure_deployment="gpt-4o",
    openai_api_version="2024-06-01",
    azure_endpoint="https://<your-endpoint>.openai.azure.com/",
    api_key="xxxxx",
    temperature=0,
)

agent = create_tool_calling_agent(llm, tools, prompt)
executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

補足:ツール関数の定義(tools.py 抜粋)

from langchain.tools import tool

@tool("get_customer_info", args_schema=GetCustomerInfoInput)
def get_customer_info(customer_id: str) -> str:
    """顧客IDから基本情報と直近購入情報を返す。見つからない場合はその旨を返す。"""
    with _conn() as conn:
        cur = conn.execute(
            "SELECT customer_id,name,plan,tier,email,last_purchase_amount,last_purchase_at "
            "FROM customers WHERE customer_id=?", (customer_id,)
        )
        row = cur.fetchone()
    if not row:
        return f"顧客 {customer_id} は見つかりません。"
    keys = ["customer_id","name","plan","tier","email","last_purchase_amount","last_purchase_at"]
    data = dict(zip(keys, row))
    return (
        f"customer_id={data['customer_id']}, name={data['name']}, plan={data['plan']}, tier={data['tier']}, "
        f"email={data['email']}, last_purchase_amount={data['last_purchase_amount']}, "
        f"last_purchase_at={data['last_purchase_at']}"
    )

class CreateTicketInput(BaseModel):
    customer_id: Optional[str] = Field(None, description="対象顧客ID")
    title: str = Field(..., description="件名")
    priority: Literal["low","medium","high"] = Field(..., description="優先度")

補足:顧客データの例(CSV の一部)

今回のサンプルでは、以下のような顧客データを SQLite に取り込みました。

customer_id,name,plan,tier,email,last_purchase_amount,last_purchase_at
C001,田中 太郎,Basic,bronze,tanaka@example.com,980,2025-07-21
C002,佐藤 花子,Pro,silver,sato@example.com,2980,2025-08-02
C003,鈴木 次郎,Enterprise,gold,suzuki@example.com,12980,2025-07-30

実行結果

実際に以下のように入力しました。

顧客C002の情報を確認し、アップセル相談のチケットを作成して

すると、次のような出力が得られました。

佐藤花子様(顧客ID: C002)は現在Proプランをご利用中です。
Enterpriseプランへのアップセルを提案するためのチケットを作成しました。

--- チケットID: 1
--- 件名: アップセル相談: Enterpriseプランの提案
--- 状態: 中
--- 作成日時: 2025-08-18T05:47:18.124564

まとめ

今回の記事では、Function Callingを活用することで、業務フローを自動化できることを確認しました。

実装はクラウド・モデルを固定し、シンプルなツールに留めましたが、実際の業務では 複数クラウド環境長期的な拡張性 が求められるケースも多いと思います。

そのような場面では、MCP(Model Context Protocol)の利用が有力な選択肢になります。
MCPは2024年11月にAnthropicから発表された、LLMが外部ツールやデータへアクセスするための 標準化された仕組み を提供するプロトコルで、現在はOpenAIやGoogleも支持を表明しています。

Anthropic公式ブログ記事

次回以降、このMCPを活用したサンプル実装についても取り上げていきたいと思います。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?