> This page is for version 1.14.0 (default).
> For other versions, use one of these documentation indexes:
> - 1.14.0 (default): https://docs.nvidia.com/nim/llama-3-1-nemotron-safety-guard-8b/1.14.0/llms.txt
> - 1.10.1: https://docs.nvidia.com/nim/llama-3-1-nemotron-safety-guard-8b/1.10.1/llms.txt

> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.nvidia.com/nim/llama-3-1-nemotron-safety-guard-8b/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.nvidia.com/nim/llama-3-1-nemotron-safety-guard-8b/_mcp/server.

# OpenAI-compatible chat endpoint

POST /v1/chat/completions
Content-Type: application/json

Reference: https://docs.nvidia.com/nim/llama-3-1-nemotron-safety-guard-8b/api-reference/create-chat-completion-v-1-chat-completions-post

## Request

### Body (application/json)

This endpoint expects a NIMLLMChatCompletionRequest.

- `messages` (list of NIMLLMChatCompletionMessage, required) — A list of messages comprising the conversation so far.
- `model` (string, required) — The model to use.
- `frequency_penalty` (double, optional, nullable, default: 0) — Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.
- `logit_bias` (map from string to double, optional, nullable) — Modify the likelihood of specified tokens appearing in the completion. Accepts a JSON object that maps tokens (specified by their token ID in the tokenizer) to an associated bias value from -100 to 100. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token.
- `logprobs` (boolean, optional, nullable, default: false) — Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the `content` of `message`.
- `top_logprobs` (integer, optional, nullable) — An integer specifying the number of most likely tokens to return at each token position, each with an associated log probability. `logprobs` must be set to `true` if this parameter is used.
- `max_tokens` (integer, optional, nullable) — The maximum number of tokens that can be generated.
- `max_completion_tokens` (integer, optional, nullable) — Alternative to max_tokens. If set, will be used as max_tokens.
- `n` (integer, optional, nullable, default: 1) — How many completions to generate for each prompt.
- `presence_penalty` (double, optional, nullable, default: 0) — Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.
- `response_format` (ResponseFormat, optional, nullable) — An object specifying the format that the model must output. Setting to `{ "type": "json_object" }` enables JSON mode, which guarantees the message the model generates is valid JSON.
- `seed` (integer, optional, nullable) — Changing the seed will produce a different response with similar characteristics. Fixing the seed will reproduce the same results if all other parameters are also kept constant.
- `stop` (NimllmChatCompletionRequestStop, optional, nullable) — Sequences where the API will stop generating further tokens.
- `stream` (boolean, optional, nullable, default: false) — If set, partial message deltas will be sent, like in ChatGPT. Tokens will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) as they become available, with the stream terminated by a `data: [DONE]`
- `stream_options` (StreamOptions, optional, nullable)
- `temperature` (double, optional, nullable, default: 1) — What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.
- `top_p` (double, optional, nullable, default: 1) — An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or `temperature` but not both.
- `tools` (list of ChatCompletionToolsParam, optional, nullable)
- `tool_choice` (NimllmChatCompletionRequestToolChoice, optional, nullable, default: none) — Controls which (if any) tool is called by the model.
- `parallel_tool_calls` (boolean, optional, nullable, default: false)
- `user` (string, optional, nullable) — A unique identifier representing your end-user.
- `top_k` (integer, optional, nullable, default: -1) — How many of the top tokens to sample from. Must be -1 or greater than or equal to 1.
- `min_p` (double, optional, nullable)
- `repetition_penalty` (double, optional, nullable, default: 1) — How much to penalize tokens based on how frequently they occur in the text. A value of 1 means no penalty, while values larger than 1 discourage and values smaller encourage.
- `include_stop_str_in_output` (boolean, optional, nullable, default: false) — Whether to include the stop string in the output. This is only applied when the stop or stop_token_ids is set. Can be a boolean or null.
- `ignore_eos` (boolean, optional, nullable, default: false) — Whether to ignore End of Sequence (EOS) tokens. It is advised to set max_tokens when this is set to avoid overly long response times.
- `min_tokens` (integer, optional, nullable, default: 0) — Min Tokens, can be an integer or null.
- `prompt_logprobs` (integer, optional, nullable)
- `add_special_tokens` (boolean, optional, default: false) — If true, special tokens (e.g. BOS) will be added to the prompt on top of what is added by the chat template. For most models, the chat template takes care of adding the special tokens so this should be set to false (as is the default).
- `documents` (list of map from string to string, optional, nullable) — A list of dicts representing documents that will be accessible to the model if it is performing RAG (retrieval-augmented generation). If the template does not support RAG, this argument will have no effect. We recommend that each document should be a dict containing "title" and "text" keys.
- `chat_template` (string, optional, nullable) — A Jinja template to use for this conversion. As of transformers v4.44, default chat template is no longer allowed, so you must provide a chat template if the tokenizer does not define one.
- `chat_template_kwargs` (NimllmChatCompletionRequestChatTemplateKwargs, optional, nullable) — Additional kwargs to pass to the template renderer. Will be accessible by the chat template.
- `mm_processor_kwargs` (NimllmChatCompletionRequestMmProcessorKwargs, optional, nullable) — Additional kwargs to pass to the HF processor.
- `guided_json` (NimllmChatCompletionRequestGuidedJson, optional, nullable) — If specified, the output will follow the JSON schema. Can be a string, an object, a reference to a BaseModel, or null.
- `guided_regex` (string, optional, nullable) — If specified, the output will follow the regex pattern. Can be a string or null.
- `guided_choice` (list of string, optional, nullable) — If specified, the output will be exactly one of the choices.
- `guided_grammar` (string, optional, nullable) — If specified, the output will follow the context-free grammar. Can be a string or null.
- `guided_decoding_backend` (string, optional, nullable) — If specified, will override the default guided decoding backend of the server for this specific request. If set, must be one of 'outlines' / 'lm-format-enforcer' / name of a custom decoding backend
- `guided_whitespace_pattern` (string, optional, nullable) — If specified, will override the default whitespace pattern for guided json decoding.
- `request_id` (string, optional) — The request_id related to this request. If the caller does not set it, a random_uuid will be generated. This id is used through out the inference process and return in response.
- `return_tokens_as_token_ids` (boolean, optional, nullable) — If specified with 'logprobs', tokens are represented as strings of the form 'token\_id:\{token\_id}' so that tokens that are not JSON-encodable can be identified.
- `nvext` (NVExt, optional, nullable) — Extension dictionary for NIM API.

## Response

### 200

Successful Response

- `create_chat_completion_v1_chat_completions_post_Response_200`
  - ChatCompletionResponse: vllm__entrypoints__openai__protocol__ChatCompletionResponse
  - ChatCompletionStreamResponse: ChatCompletionStreamResponse

## Errors

### 400 Bad Request Error

Received an invalid request possibly containing unsupported or out-of-range parameter values.

- `message` (string, required)
- `type` (string, required)
- `code` (integer, required)
- `object` (string, optional, default: error)
- `param` (string, optional, nullable)

### 404 Not Found Error

The requested model does not exist.

- `message` (string, required)
- `type` (string, required)
- `code` (integer, required)
- `object` (string, optional, default: error)
- `param` (string, optional, nullable)

### 415 Unsupported Media Type Error

Unsupported Media Type

- `message` (string, required)
- `type` (string, required)
- `code` (integer, required)
- `object` (string, optional, default: error)
- `param` (string, optional, nullable)

### 422 Unprocessable Entity Error

Validation Error

- `detail` (list of ValidationError, optional)

### 500 Internal Server Error

Internal Server Error

- `message` (string, required)
- `type` (string, required)
- `code` (integer, required)
- `object` (string, optional, default: error)
- `param` (string, optional, nullable)

## Types

### NIMLLMChatCompletionMessage

- `role` (enum, required) — The role of the message's author.
  - Allowed values: `assistant`, `user`, `system`, `tool`, `function`
- `content` (NimllmChatCompletionMessageContent, optional, nullable) — The contents of the message. For a reward model, the predicted attributes, i.e. reward scores, will be returned.
- `tool_call_id` (string, optional, nullable) — The id of the tool call.
- `name` (string, optional, nullable) — The name of the tool called.
- `tool_calls` (list of vllm__entrypoints__openai__protocol__ToolCall, optional, nullable) — The tool(s) called by the model.

### ResponseFormat

- `type` (enum, required) — Must be one of `text`, `json_schema` or `json_object`.
  - Allowed values: `text`, `json_object`, `json_schema`
- `json_schema` (JsonSchemaResponseFormat, optional, nullable)

### NimllmChatCompletionRequestStop

Sequences where the API will stop generating further tokens.

- string
- list of string

### StreamOptions

- `include_usage` (boolean, optional, nullable, default: true)
- `continuous_usage_stats` (boolean, optional, nullable, default: false)

### ChatCompletionToolsParam

- `function` (FunctionDefinition, required)
- `type` ("function", optional, default: function)

### NimllmChatCompletionRequestToolChoice

Controls which (if any) tool is called by the model.

- enum
  - Allowed values: `none`, `auto`, `required`
- ChatCompletionNamedToolChoiceParam: ChatCompletionNamedToolChoiceParam

### NimllmChatCompletionRequestChatTemplateKwargs

Additional kwargs to pass to the template renderer. Will be accessible by the chat template.

### NimllmChatCompletionRequestMmProcessorKwargs

Additional kwargs to pass to the HF processor.

### NimllmChatCompletionRequestGuidedJson

If specified, the output will follow the JSON schema. Can be a string, an object, a reference to a BaseModel, or null.

- string
- map from string to any
- BaseModel: BaseModel

### NVExt

- `ignore_eos` (boolean, optional, nullable, default: false) — Whether to ignore End of Sequence (EOS) tokens. It is advised to set max_tokens when this is set to avoid overly long response times.
- `repetition_penalty` (double, optional, nullable, default: 1) — How much to penalize tokens based on how frequently they occur in the text. A value of 1 means no penalty, while values larger than 1 discourage and values smaller encourage.
- `top_k` (integer, optional, default: -1) — How many of the top tokens to sample from. Must be -1 or greater than or equal to 1, and cannot be null. If not set, then the default is -1 which disables top_k sampling (greedy).
- `guided_choice` (list of string, optional, nullable) — If specified, the output will be exactly one of the choices.
- `guided_json` (NvExtGuidedJson, optional, nullable) — If specified, the output will follow the JSON schema. Can be a string, an object, a reference to a BaseModel, or null.
- `guided_regex` (string, optional, nullable) — If specified, the output will follow the regex pattern. Can be a string or null.
- `guided_grammar` (string, optional, nullable) — If specified, the output will follow the context-free grammar. Can be a string or null.
- `guided_decoding_backend` (string, optional, nullable) — If specified, will override the default guided decoding backend of the server for this specific request. If set, must be one of 'xgrammar' / name of a custom decoding backend
- `min_tokens` (integer, optional, nullable, default: 0) — The minimum number of tokens to generate. If set, the model will generate at least this many tokens before stopping.
- `max_thinking_tokens` (integer, optional, nullable) — The maximum number of tokens to spend on thinking. If set, the model will think for a maximum of this many tokens before generating a response. This is only supported for models that support guided decoding. The model may go slightly over this limit, but will not exceed it by more than 10%.

### vllm__entrypoints__openai__protocol__ChatCompletionResponse

- `model` (string, required)
- `choices` (list of ChatCompletionResponseChoice, required)
- `usage` (UsageInfo, required)
- `id` (string, optional)
- `object` ("chat.completion", optional, default: chat.completion)
- `created` (integer, optional)
- `prompt_logprobs` (list of map from string to Logprob, optional, nullable)
- `kv_transfer_params` (VllmEntrypointsOpenaiProtocolChatCompletionResponseKvTransferParams, optional, nullable) — KVTransfer parameters.

### ChatCompletionStreamResponse

- `model` (string, required)
- `choices` (list of ChatCompletionResponseStreamChoice, required)
- `id` (string, optional)
- `object` ("chat.completion.chunk", optional, default: chat.completion.chunk)
- `created` (integer, optional)
- `usage` (UsageInfo, optional, nullable)

### ValidationError

- `loc` (list of ValidationErrorLocItems, required)
- `msg` (string, required)
- `type` (string, required)

### NimllmChatCompletionMessageContent

The contents of the message. For a reward model, the predicted attributes, i.e. reward scores, will be returned.

- string
- list of NimllmChatCompletionMessageContentOneOf1Items

### vllm__entrypoints__openai__protocol__ToolCall

- `function` (FunctionCall, required)
- `id` (string, optional)
- `type` ("function", optional, default: function)

### JsonSchemaResponseFormat

- `name` (string, required)
- `description` (string, optional, nullable)
- `schema` (JsonSchemaResponseFormatSchema, optional, nullable)
- `strict` (boolean, optional, nullable)

### FunctionDefinition

- `name` (string, required)
- `description` (string, optional, nullable)
- `parameters` (FunctionDefinitionParameters, optional, nullable)

### ChatCompletionNamedToolChoiceParam

- `function` (ChatCompletionNamedFunction, required)
- `type` ("function", optional, default: function)

### BaseModel

### NvExtGuidedJson

If specified, the output will follow the JSON schema. Can be a string, an object, a reference to a BaseModel, or null.

- string
- map from string to any
- BaseModel: BaseModel

### ChatCompletionResponseChoice

- `index` (integer, required)
- `message` (ChatMessage, required)
- `logprobs` (ChatCompletionLogProbs, optional, nullable)
- `finish_reason` (string, optional, nullable, default: stop)
- `stop_reason` (ChatCompletionResponseChoiceStopReason, optional, nullable)

### UsageInfo

- `prompt_tokens` (integer, optional, default: 0)
- `total_tokens` (integer, optional, default: 0)
- `completion_tokens` (integer, optional, nullable, default: 0)
- `prompt_tokens_details` (PromptTokenUsageInfo, optional, nullable)

### Logprob

- `logprob` (double, required)
- `rank` (integer, optional, nullable)
- `decoded_token` (string, optional, nullable)

### VllmEntrypointsOpenaiProtocolChatCompletionResponseKvTransferParams

KVTransfer parameters.

### ChatCompletionResponseStreamChoice

- `index` (integer, required)
- `delta` (DeltaMessage, required)
- `logprobs` (ChatCompletionLogProbs, optional, nullable)
- `finish_reason` (string, optional, nullable)
- `stop_reason` (ChatCompletionResponseStreamChoiceStopReason, optional, nullable)

### ValidationErrorLocItems

- string
- integer

### NimllmChatCompletionMessageContentOneOf1Items

- NIMVLMChatCompletionContentPartImage: NIMVLMChatCompletionContentPartImage
- NIMVLMChatCompletionContentPartText: NIMVLMChatCompletionContentPartText

### FunctionCall

- `name` (string, required)
- `arguments` (string, required)

### JsonSchemaResponseFormatSchema

### FunctionDefinitionParameters

### ChatCompletionNamedFunction

- `name` (string, required)

### ChatMessage

- `role` (string, required)
- `reasoning_content` (string, optional, nullable)
- `content` (string, optional, nullable)
- `tool_calls` (list of vllm__entrypoints__openai__protocol__ToolCall, optional)

### ChatCompletionLogProbs

- `content` (list of ChatCompletionLogProbsContent, optional, nullable)

### ChatCompletionResponseChoiceStopReason

- integer
- string

### PromptTokenUsageInfo

- `cached_tokens` (integer, optional, nullable)

### DeltaMessage

- `role` (string, optional, nullable)
- `content` (string, optional, nullable)
- `reasoning_content` (string, optional, nullable)
- `tool_calls` (list of DeltaToolCall, optional)

### ChatCompletionResponseStreamChoiceStopReason

- integer
- string

### NIMVLMChatCompletionContentPartImage

- `image_url` (ImageURL, required)
- `type` ("image_url", required)

### NIMVLMChatCompletionContentPartText

- `text` (string, required)
- `type` ("text", required)

### ChatCompletionLogProbsContent

- `token` (string, required)
- `logprob` (double, optional, default: -9999)
- `bytes` (list of integer, optional, nullable)
- `top_logprobs` (list of ChatCompletionLogProb, optional)

### DeltaToolCall

- `index` (integer, required)
- `id` (string, optional, nullable)
- `type` ("function", optional, nullable)
- `function` (DeltaFunctionCall, optional, nullable)

### ImageURL

- `url` (string, required)
- `detail` ("auto", optional)

### ChatCompletionLogProb

- `token` (string, required)
- `logprob` (double, optional, default: -9999)
- `bytes` (list of integer, optional, nullable)

### DeltaFunctionCall

- `name` (string, optional, nullable)
- `arguments` (string, optional, nullable)

## Examples

**Request**

```json
{
  "messages": [
    {
      "role": "assistant"
    }
  ],
  "model": "string"
}
```

**Response**

```json
{
  "choices": [
    {
      "finish_reason": "string",
      "index": 1,
      "logprobs": {
        "content": [
          {
            "bytes": [
              1
            ],
            "logprob": -9999,
            "token": "string",
            "top_logprobs": [
              {
                "bytes": [
                  1
                ],
                "logprob": -9999,
                "token": "string"
              }
            ]
          }
        ]
      },
      "message": {
        "content": "string",
        "reasoning_content": "string",
        "role": "string",
        "tool_calls": [
          {
            "function": {
              "arguments": "string",
              "name": "string"
            },
            "id": "string",
            "type": "function"
          }
        ]
      },
      "stop_reason": 1
    }
  ],
  "created": 1,
  "id": "string",
  "kv_transfer_params": {},
  "model": "string",
  "object": "chat.completion",
  "prompt_logprobs": [
    {}
  ],
  "usage": {
    "completion_tokens": 1,
    "prompt_tokens": 0,
    "prompt_tokens_details": {
      "cached_tokens": 1
    },
    "total_tokens": 0
  }
}
```

**SDK Code**

```python
import requests

url = "https://api.example.com/v1/chat/completions"

payload = {
    "messages": [{ "role": "assistant" }],
    "model": "string"
}
headers = {"Content-Type": "application/json"}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript
const url = 'https://api.example.com/v1/chat/completions';
const options = {
  method: 'POST',
  headers: {'Content-Type': 'application/json'},
  body: '{"messages":[{"role":"assistant"}],"model":"string"}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.example.com/v1/chat/completions"

	payload := strings.NewReader("{\n  \"messages\": [\n    {\n      \"role\": \"assistant\"\n    }\n  ],\n  \"model\": \"string\"\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby
require 'uri'
require 'net/http'

url = URI("https://api.example.com/v1/chat/completions")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Content-Type"] = 'application/json'
request.body = "{\n  \"messages\": [\n    {\n      \"role\": \"assistant\"\n    }\n  ],\n  \"model\": \"string\"\n}"

response = http.request(request)
puts response.read_body
```

```java
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.example.com/v1/chat/completions")
  .header("Content-Type", "application/json")
  .body("{\n  \"messages\": [\n    {\n      \"role\": \"assistant\"\n    }\n  ],\n  \"model\": \"string\"\n}")
  .asString();
```

```php
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.example.com/v1/chat/completions', [
  'body' => '{
  "messages": [
    {
      "role": "assistant"
    }
  ],
  "model": "string"
}',
  'headers' => [
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp
using RestSharp;

var client = new RestClient("https://api.example.com/v1/chat/completions");
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"messages\": [\n    {\n      \"role\": \"assistant\"\n    }\n  ],\n  \"model\": \"string\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = ["Content-Type": "application/json"]
let parameters = [
  "messages": [["role": "assistant"]],
  "model": "string"
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.example.com/v1/chat/completions")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```