> ## Documentation Index
> Fetch the complete documentation index at: https://docs.jiekou.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# ツール呼び出し（Function Calling）

export const FunctionCallingModels = () => {
  if (typeof document === "undefined") {
    return null;
  } else {
    let attempts = 0;
    const maxAttempts = 50;
    const INIT_DISPLAY_COUNT = 3;
    const interval = setInterval(() => {
      const clientComponent = document.getElementById("function-calling-models");
      if (clientComponent && window.jiekouRemoteData.llmModels.status === 'loaded') {
        const modelList = window.jiekouRemoteData.llmModels.data.filter(model => {
          return (model.features || []).includes('function-calling');
        });
        let displayModels = modelList.slice(0, INIT_DISPLAY_COUNT).map(model => {
          return `<li><span class="model-id-item">${model.id}</span></li>`;
        }).join('');
        let showMoreButton = '';
        if (modelList.length > INIT_DISPLAY_COUNT) {
          showMoreButton = `<button id="show-more-function-call-btn" style="margin-left: 32px; color: rgb(40 116 255)">展示更多</button>`;
        }
        clientComponent.innerHTML = `
          <ul>${displayModels}</ul>
          ${showMoreButton}
        `;
        document.getElementById('show-more-function-call-btn')?.addEventListener('click', () => {
          clientComponent.innerHTML = `
            <ul>${modelList.map(model => {
            return `<li><span class="model-id-item">${model.id}</span></li>`;
          }).join('')}</ul>
          `;
        });
        clearInterval(interval);
      }
      attempts++;
      if (attempts >= maxAttempts) {
        clearInterval(interval);
      }
    }, 200);
    return <div id="function-calling-models"></div>;
  }
};

## ユースケース

Function Calling 機能により、モデルは外部ツールと連携し、リアルタイム情報を取得したり、特定の操作を実行したりできます。この機能はデータの正確性を高めると同時に、モデルの能力を拡張します。これにより、モデルは単なるテキスト生成にとどまらず、より動的で実用的なユースケースをサポートできます。

Function Calling のユースケース例は次のとおりです。

* **動的な情報検索**：API を呼び出して外部システムから天気、ニュース、株価などの動的データをリアルタイムに取得します。たとえば、天気 API を呼び出してリアルタイムの天気情報を取得することで、ユーザーが現在の天気を尋ねた際に、古い天気予報ではなく、その時点の天気状況を伝えることができます。
* **タスク操作の自動化**：関数呼び出しによって特定の操作を実行し、ユーザーは会話を通じてバックエンドの自動化処理をトリガーできます。たとえば、チケット予約サイトの API を呼び出してチケットを予約することで、ユーザーが特定の観光地のチケット購入方法を尋ねた際に、モデルは予約方法を説明するだけでなく、ユーザーの代わりに直接予約操作を完了できます。

## サポートされているモデル

以下のモデルは Function Calling をサポートしています。

<FunctionCallingModels />

## 使用方法

1. モデルが呼び出すツール関数を定義します。
2. リクエストに `tools` パラメータを追加し、モデルが使用する関数を定義します。

## 使用例

以下では、特定の場所の現在の天気を照会する例を使用して、Function Calling の使い方を示す完全な Python コード例を提供します。

Function Calling の具体的な API 形式については、[チャット会話作成リクエスト API](/ja/docs/models/reference-llm-create-chat-completion) を参照してください。

### 1. クライアントを初期化する

JieKou AI API キーを使用してクライアントを初期化する必要があります。

```python theme={null}
from openai import OpenAI
import json

client = OpenAI(
    base_url="https://api.highwayapi.ai/openai",
    api_key="<Your API Key>",
)

model = "deepseek/deepseek-v3"
```

### 2. 呼び出す関数を定義する

モデルが呼び出す関数を定義します。以下の Python 例では、天気情報を取得する機能を示しています。

```python theme={null}
# 天気データの取得をシミュレートするサンプル関数。
def get_weather(location):
    """指定した場所の現在の天気を取得する"""
    print("get_weather 関数を呼び出します。場所: ", location)
    # 実際のアプリケーションでは、ここで外部の天気 API を呼び出す必要があります。
    # これは簡略化した例で、ハードコードされたデータを返します。
    return json.dumps({"位置": location, "温度": "摂氏 20 度"})
```

### 3. ツールとユーザーメッセージを含む API リクエストを構築する

API 呼び出しリクエストを作成します。このリクエストには、モデルが使用する関数を定義する `tools` パラメータと、ユーザーのメッセージが含まれます。

```python theme={null}
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "ある場所の天気を取得します。ユーザーはまず場所を提供する必要があります",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "都市情報、例：上海",
                    }
                },
                "required": ["location"]
            },
        }
    },
]
messages = [
    {
        "role": "user",
        "content": "上海の天気はどうですか？"
    }
]
# リクエストを送信し、レスポンスを出力する
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())
```

**出力**：

```js theme={null}
{'id': '0', 'function': {'arguments': '{"location": "上海"}', 'name': 'get_weather'}, 'type': 'function'}
```

### 4. 関数呼び出しの結果に基づいて応答し、最終回答を取得する

次に関数呼び出しを処理し、`get_weather` 関数を実行して、その結果をモデルに送り返し、ユーザーへの最終応答を生成します。

```python theme={null}
# ツール呼び出しが前のステップで定義されていることを確認する
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,
        # 注意：ここには tools パラメータを含めないでください
    )
    print(answer_response.choices[0].message)
```

**出力**：

```
ChatCompletionMessage(content="上海の現在の気温は摂氏 20 度です。天気状況は随時変化する可能性があるため、より正確な情報を得るには最新の天気予報を確認することをおすすめします。", refusal=None, role='assistant', function_call=None, tool_calls=None)
```

## 完全なコード

```python theme={null}
from openai import OpenAI
import json

client = OpenAI(
    base_url="https://api.highwayapi.ai/openai",
    api_key="<Your API Key>",
)

model = "deepseek/deepseek-v3"

# 天気データの取得をシミュレートするサンプル関数。
def get_weather(location):
    """指定した場所の現在の天気を取得する"""
    print("get_weather 関数を呼び出します。場所: ", location)
    # 実際のアプリケーションでは、ここで外部の天気 API を呼び出す必要があります。
    # これは簡略化した例で、ハードコードされたデータを返します。
    return json.dumps({"位置": location, "温度": "摂氏 20 度"})

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "ある場所の天気を取得します。ユーザーはまず場所を提供する必要があります",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "都市情報、例：上海",
                    }
                },
                "required": ["location"]
            },
        }
    },
]

messages = [
    {
        "role": "user",
        "content": "上海の天気はどうですか？"
    }
]

# リクエストを送信し、レスポンスを出力する
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,
        # 注意：ここには tools パラメータを含めないでください
    )
    print(answer_response.choices[0].message)
```
