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

# Function calling と JSON モード機能の実装

Function calling (関数呼び出し) は、ユーザーの入力に基づいてモデルが関数呼び出しを選択・提案できるようにすることで動的なワークフローを実現し、エージェント型ワークフローの構築に役立ちます。関数 (ツール) のセットを定義してモデルにコンテキストを与えることで、必要に応じて、モデルに関数の推奨と引数の補完をさせることができます。

## Function calling の仕組み

Function calling により、リアルタイムデータや構造化出力を活用する適応的なワークフローを構築でき、よりダイナミックで応答性の高いモデルとの対話が実現します。

1. **ツールを含むクエリの送信:** まず、JSON Schema で定義された利用可能なツール群とともに、ユーザーのクエリを送信します。このスキーマで各関数のパラメータを指定します。
2. **モデルによる処理と提案:** モデルはクエリを解釈して意図を判断し、会話として応答するか、関数呼び出しを提案するかを決定します。関数が呼び出される場合、スキーマに基づいて引数を補完します。
3. **モデルからの応答の受信:** モデルからの応答には、関数呼び出しの提案が含まれる場合があります。提供された引数で関数を実行し、その結果をモデルに返すことで対話を継続します。

## 対応モデル

* `Meta-Llama-3.3-70B-Instruct`
* `Qwen3-235B-A22B-Instruct-2507`
* `gpt-oss-120b`
* `DeepSeek-V3.1`
* `DeepSeek-V3.2`
* `MiniMax-M2.7`
* `MiniMax-M3`
* `gemma-4-31B-it`

<Note>
  `gpt-oss-120b` でツール呼び出しリクエストの品質を高めるには、`reasoning_effort` を `high` に設定してください。
</Note>

## 使用例

以下では、Function calling を使用する各ステップを順に説明し、最後のステップの後にエンドツーエンドの実装例を紹介します。

### ステップ 1: 関数スキーマの定義

関数の JSON スキーマを定義します。以下を指定する必要があります。

* 関数の名前。
* 関数の動作の説明。
* パラメータ、そのデータ型、および説明。

```json Example schema for getting the weather theme={}
{
  "type": "function",
  "function": {
    "name": "get_weather",
    "description": "Gets the current weather information for a given city.",
    "parameters": {
      "type": "object",
      "properties": {
        "city": {
          "type": "string",
          "description": "Name of the city to get weather information for."
        }
      },
      "required": ["city"]
    }
  }
}
```

### ステップ 2: リクエストでの Function calling の設定

リクエストを送信する際、`tools` パラメータに関数定義を含め、`tool_choice` に以下のいずれかを設定します。

* `auto`: メッセージの生成と関数呼び出しのどちらを行うかをモデルに委ねます。このフィールドを指定しない場合のデフォルトです。
* `required`: モデルに関数呼び出しの生成を強制します。モデルは常に 1 つ以上の関数を選択して呼び出します。
* `none`: モデルによる関数呼び出しを禁止し、テキスト応答を強制します。
* 特定の関数呼び出しを強制するには、`tool_choice = {"type": "function", "function": {"name": "get_weather"}}` と設定します。これにより、モデルは指定された関数のみを使用します。

<Note>
  `gpt-oss-120b` で特定の関数呼び出しを強制する場合は、Chat Completions API 形式 (`{"type": "function", "function": {"name": "function_name"}}`) を使用してください。OpenAI Responses API 形式 (内側に `"function"` キーを持たない `{"type": "function", "name": "function_name"}`) は未対応です。`allowed_tools` パラメータも未対応です。
</Note>

<Note>
  以下のコードブロックは、20°C から 50°C までのランダムな気温を返す架空の天気検索の例です。正確なリアルタイムの気象データが必要な場合は、適切な天気 API を使用してください。
</Note>

<CodeGroup>
  ```python Python (SambaNova) theme={}
  import sambanova
  import random
  import json

  # Initialize the client with the SambaNova base URL and API key
  client = sambanova.SambaNova(
      base_url="your-sambanova-base-url",
      api_key="your-sambanova-api-key"
  )

  MODEL = 'Meta-Llama-3.3-70B-Instruct'

  def get_weather(city: str) -> dict:
      """
      Fake weather lookup: returns a random temperature between 20°C and 50°C.
      """
      temp = random.randint(20, 50)
      return {
          "city": city,
          "temperature_celsius": temp
      }

  tools = [
      {
          "type": "function",
          "function": {
              "name": "get_weather",
              "description": "Get weather of a location, the user should supply a location first",
              "parameters": {
                  "type": "object",
                  "properties": {
                      "city": {
                          "type": "string",
                          "description": "The city and state, e.g. San Francisco, CA",
                      }
                  },
                  "required": ["city"]
              },
          }
      },
  ]

  messages = [{"role": "user", "content": "What's the weather like in Paris today?"}]


  completion = client.chat.completions.create(
      model=MODEL,
      messages=messages,
      tools=tools
  )

  print(completion)
  ```

  ```python Python (OpenAI) theme={}
  import openai
  import random
  import json

  # Initialize the client with the SambaNova base URL and API key
  client = openai.OpenAI(
      base_url="your-sambanova-base-url",
      api_key="your-sambanova-api-key"
  )

  MODEL = 'Meta-Llama-3.3-70B-Instruct'

  def get_weather(city: str) -> dict:
      """
      Fake weather lookup: returns a random temperature between 20°C and 50°C.
      """
      temp = random.randint(20, 50)
      return {
          "city": city,
          "temperature_celsius": temp
      }

  tools = [
      {
          "type": "function",
          "function": {
              "name": "get_weather",
              "description": "Get weather of a location, the user should supply a location first",
              "parameters": {
                  "type": "object",
                  "properties": {
                      "city": {
                          "type": "string",
                          "description": "The city and state, e.g. San Francisco, CA",
                      }
                  },
                  "required": ["city"]
              },
          }
      },
  ]

  messages = [{"role": "user", "content": "What's the weather like in Paris today?"}]


  completion = client.chat.completions.create(
      model=MODEL,
      messages=messages,
      tools=tools
  )

  print(completion)
  ```
</CodeGroup>

### ステップ 3: ツール呼び出しの処理

モデルが関数の呼び出しを選択した場合、レスポンスに `tool_calls` が含まれます。関数呼び出しの詳細を抽出し、提供されたパラメータで対応する関数を実行します。

```python Example code theme={}
tool_call = completion.choices[0].message.tool_calls[0]
args = json.loads(tool_call.function.arguments)

result = get_weather(args["city"])
```

### ステップ 4: 関数の結果をモデルに返す

結果を計算したら、それをモデルに渡して会話を継続するか、出力を確認します。

```python Example code theme={}
messages.append(completion.choices[0].message)  # append model's function call message
messages.append({                               # append result message
    "role": "tool",
    "tool_call_id": tool_call.id,
    "content": str(result)
})

completion_2 = client.chat.completions.create(
    model=MODEL,
    messages=messages,

)
print(completion_2.choices[0].message.content)
```

### ステップ 5: 出力例

出力例:

```text theme={}
The current weather in Paris is 25 degrees Celsius.
```

### エンドツーエンドの例

<Note>
  以下のコードブロックは、20°C から 50°C までのランダムな気温を返す架空の天気検索の例です。正確なリアルタイムの気象データが必要な場合は、適切な天気 API を使用してください。
</Note>

<CodeGroup>
  ```python Python (SambaNova) theme={}
  import sambanova
  import random
  import json

  # Define the SambaNova client
  client = sambanova.SambaNova(
      base_url="your-sambanova-base-url",
      api_key="your-sambanova-api-key"
  )

  MODEL = 'Meta-Llama-3.3-70B-Instruct'

  def get_weather(city: str) -> dict:
      """
      Fake weather lookup: returns a random temperature between 20°C and 50°C.
      """
      temp = random.randint(20, 50)
      return {
          "city": city,
          "temperature_celsius": temp
      }


  tools = [
      {
          "type": "function",
          "function": {
              "name": "get_weather",
              "description": "Get weather of a location, the user should supply a location first",
              "parameters": {
                  "type": "object",
                  "properties": {
                      "city": {
                          "type": "string",
                          "description": "The city and state, e.g. San Francisco, CA",
                      }
                  },
                  "required": ["city"]
              },
          }
      },
  ]

  messages = [{"role": "user", "content": "What's the weather like in Paris today?"}]


  completion = client.chat.completions.create(
      model=MODEL,
      messages=messages,
      tools=tools
  )

  print(completion)


  tool_call = completion.choices[0].message.tool_calls[0]
  args = json.loads(tool_call.function.arguments)

  result = get_weather(args["city"])


  messages.append({                               # append model's function call message
   "role": "assistant",
   "content": None,
   "tool_calls": [tool_call]
  })

  messages.append({                               # append result message
   "role": "tool",
   "tool_call_id": tool_call.id,
   "content": json.dumps(result)
  })

  completion_2 = client.chat.completions.create(
      model=MODEL,
      messages=messages,

  )
  print(completion_2.choices[0].message.content)
  ```

  ```python Python (OpenAI) theme={}
  import openai
  import random
  import json

  # Define the OpenAI client
  client = openai.OpenAI(
      base_url="your-sambanova-base-url",
      api_key="your-sambanova-api-key"
  )

  MODEL = 'Meta-Llama-3.3-70B-Instruct'

  def get_weather(city: str) -> dict:
      """
      Fake weather lookup: returns a random temperature between 20°C and 50°C.
      """
      temp = random.randint(20, 50)
      return {
          "city": city,
          "temperature_celsius": temp
      }


  tools = [
      {
          "type": "function",
          "function": {
              "name": "get_weather",
              "description": "Get weather of a location, the user should supply a location first",
              "parameters": {
                  "type": "object",
                  "properties": {
                      "city": {
                          "type": "string",
                          "description": "The city and state, e.g. San Francisco, CA",
                      }
                  },
                  "required": ["city"]
              },
          }
      },
  ]

  messages = [{"role": "user", "content": "What's the weather like in Paris today?"}]


  completion = client.chat.completions.create(
      model=MODEL,
      messages=messages,
      tools=tools
  )

  print(completion)


  tool_call = completion.choices[0].message.tool_calls[0]
  args = json.loads(tool_call.function.arguments)

  result = get_weather(args["city"])


  messages.append({                               # append model's function call message
   "role": "assistant",
   "content": None,
   "tool_calls": [tool_call]
  })

  messages.append({                               # append result message
   "role": "tool",
   "tool_call_id": tool_call.id,
   "content": json.dumps(result)
  })

  completion_2 = client.chat.completions.create(
      model=MODEL,
      messages=messages,

  )
  print(completion_2.choices[0].message.content)
  ```
</CodeGroup>

## JSON スキーマ

`response_format` パラメータに定義済みのスキーマを設定すると、指定した構造に一致する JSON オブジェクトをモデルに生成させることができます。

<CodeGroup>
  ```python Python (SambaNova) theme={}
  import sambanova
  import json

  # Define the SambaNova client
  client = sambanova.SambaNova(
      base_url="your-sambanova-base-url",
      api_key="your-sambanova-api-key"
  )

  MODEL = "DeepSeek-V3.1"

  # Define the schema
  response_format = {
      "type": "json_schema",
      "json_schema": {
          "name": "data_extraction",
          "schema": {
              "type": "object",
              "properties": {
                  "section": {
                      "type": "string"
                  },
                  "products": {
                      "type": "array",
                      "items": {
                          "type": "string"
                      }
                  }
              },
              "required": ["section", "products"],
              "additionalProperties": False
          },
          "strict": False
      }
  }

  # Call the API
  completion = client.chat.completions.create(
      model=MODEL,
      messages=[
          {
              "role": "system",
              "content": "You are an expert at structured data extraction. You will be given unstructured text and should convert it into the given structure."
          },
          {
              "role": "user",
              "content": "the section 24 has appliances, and videogames"
          }
      ],
      response_format=response_format
  )

  # Print the parsed result
  print(completion)
  ```

  ```python Python (OpenAI) theme={}
  import openai
  import json

  # Define the OpenAI client
  client = openai.OpenAI(
      base_url="your-sambanova-base-url",
      api_key="your-sambanova-api-key"
  )

  MODEL = "DeepSeek-V3.1"

  # Define the schema
  response_format = {
      "type": "json_schema",
      "json_schema": {
          "name": "data_extraction",
          "schema": {
              "type": "object",
              "properties": {
                  "section": {
                      "type": "string"
                  },
                  "products": {
                      "type": "array",
                      "items": {
                          "type": "string"
                      }
                  }
              },
              "required": ["section", "products"],
              "additionalProperties": False
          },
          "strict": False
      }
  }

  # Call the API
  completion = client.chat.completions.create(
      model=MODEL,
      messages=[
          {
              "role": "system",
              "content": "You are an expert at structured data extraction. You will be given unstructured text and should convert it into the given structure."
          },
          {
              "role": "user",
              "content": "the section 24 has appliances, and videogames"
          }
      ],
      response_format=response_format
  )

  # Print the parsed result
  print(completion)
  ```
</CodeGroup>

<Note>
  `strict` パラメータは、API では `true` と `false` のどちらの値も受け付けられます。

  * `false` がデフォルトです。現時点で実際に適用される唯一の値であり、モデルはスキーマに対してベストエフォートでのマッチングを行います。
  * `true` はエラーにはなりませんが、現時点では動作上の追加の影響はありません。

  厳密な適用が利用可能になった際には、`strict: true` を設定すると、ベストエフォートでの対応ではなく、スキーマへの厳密な準拠がモデルに要求されるようになります。
</Note>

## JSON モード

リクエストで `response_format` パラメータに `json_object` を設定すると、モデルに有効な JSON を出力させることができます。モデルが有効な JSON を生成できなかった場合は、エラーが返されます。

<Note>
  モデルが有効な JSON の生成に失敗した場合、エラーメッセージ **Model did not output valid JSON** が返されます。
</Note>

<CodeGroup>
  ```python Python (SambaNova) theme={}
  import sambanova

  # Define the SambaNova client
  client = sambanova.SambaNova(
      base_url="your-sambanova-base-url",
      api_key="your-sambanova-api-key"
  )

  MODEL = 'Meta-Llama-3.3-70B-Instruct'


  def run_conversation(user_prompt):
      # Initial conversation with user input
      messages = [
          {
              "role": "system",
              "content": "Always provide the response in this JSON format: {\"country\": \"name\", \"capital\": \"xx\"}"
          },

          {
              "role": "user",
              "content": user_prompt,
          }
      ]

      # First API call to get model's response
      response = client.chat.completions.create(
          model=MODEL,
          messages=messages,
          max_tokens=500,
          response_format = { "type": "json_object"},
          # stream = True
      )

      response_message = response.choices[0].message
      print(response_message)


  run_conversation('what is the capital of Austria')
  ```

  ```python Python (OpenAI) theme={}
  import openai

  # Define the OpenAI client
  client = openai.OpenAI(
      base_url="your-sambanova-base-url",
      api_key="your-sambanova-api-key"
  )

  MODEL = 'Meta-Llama-3.3-70B-Instruct'


  def run_conversation(user_prompt):
      # Initial conversation with user input
      messages = [
          {
              "role": "system",
              "content": "Always provide the response in this JSON format: {\"country\": \"name\", \"capital\": \"xx\"}"
          },

          {
              "role": "user",
              "content": user_prompt,
          }
      ]

      # First API call to get model's response
      response = client.chat.completions.create(
          model=MODEL,
          messages=messages,
          max_tokens=500,
          response_format = { "type": "json_object"},
          # stream = True
      )

      response_message = response.choices[0].message
      print(response_message)


  run_conversation('what is the capital of Austria')
  ```
</CodeGroup>

```json Example response theme={}
ChatCompletionMessage(content='{"country": "Austria", "capital": "Vienna"}', role='assistant', function_call=None, tool_calls=None)
```

### 構造化出力のその他の方法

JSON モード以外にも、Instructor ライブラリを使用して構造化出力を生成できます。詳細は [Instructor 連携](/docs/ja/integrations/instructor) ページをご参照ください。

デフォルトのサーバー側の動作に頼らず、ツール呼び出しのフォーマットと解析を自分で制御したい場合は、クライアント側でのテンプレートレンダリングと出力解析を組み合わせた Completions API を使用してください。[カスタムチャットテンプレートと出力解析](/docs/ja/build/chat-templates) をご参照ください。
